From d1f6de0069a85cfe24f25890f91495d1975e2c9c Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 1 Nov 2026 06:34:31 +1300 Subject: [PATCH 1/6] Prepare scoped Logging audit receipts and authenticated readback Receive compatible preserved #2940 source 326635a364cc8e0f2e232b790674560dc7c242c1 against the current Account containment parent. Preserve stronger UUID moderation and StartSession behavior, use forward V1004-V1007, omit unsupported historical projection-version claims, and retain disabled live audit writes and Account recovery/retention holds. --- .../account-service/operations.md | 2 +- .../account-service/runtime-and-data.md | 2 +- .../logging-admin-service/api-contracts.md | 4 +- .../logging-admin-service/configuration.md | 4 +- .../logging-admin-service/runtime-and-data.md | 2 + .../system-architecture-authz-route-matrix.md | 4 +- ...ystem-architecture-authz-route-matrix.yaml | 6 +- design/project-management/ai-observations.md | 3 + .../player-access-and-session.md | 6 + ...hared-runtime-contracts-and-persistence.md | 4 +- .../preview/validate-preview-artifact.py | 3 +- dev-tools/tests/compose-grpc-mtls-contract.sh | 51 +- ...d-identity-controller-manifest-contract.sh | 300 +++++- .../test_check_authz_route_matrix.py | 25 + docker/docker-compose.grpc-mtls.override.yml | 1 + k8s/base/logging-admin-service.yaml | 4 + k8s/helm/firemud/templates/apps.yaml | 4 +- .../service/AccountAuditDeliveryJob.java | 7 +- .../service/AccountAuditDeliveryJobTest.java | 9 +- .../AccountAuditGrpcAuthConfiguration.java | 37 + .../dto/AccountAuditReceiptDto.java | 13 + .../dto/AccountAuditReceiptOutcome.java | 8 + .../dto/AccountAuditReceiptStatus.java | 7 + .../loggingadmin/dto/AccountAuditScope.java | 16 + .../dto/CreateLogEventRequest.java | 24 +- .../entity/AccountAuditReceipt.java | 31 + .../AccountAuditReceiptInsertResult.java | 3 + .../AccountAuditReceiptRepository.java | 128 +++ .../repository/LogEventRepository.java | 15 +- .../AuditReceiptNotFoundException.java | 7 + .../AuditStorageUnavailableException.java | 7 + .../loggingadmin/service/LogEventService.java | 6 +- .../service/impl/LogEventServiceImpl.java | 243 ++++- .../service/impl/LoggingAdminGrpcService.java | 237 ++++- .../V1004__account_audit_receipts.sql | 47 + ...1005__account_audit_receipt_projection.sql | 68 ++ ...ce_account_audit_receipt_digest_format.sql | 5 + ...nforce_account_audit_projection_tenant.sql | 5 + ...oggingAdminApplicationIntegrationTest.java | 900 ++++++++++++++++++ .../AccountAuditReceiptRepositoryTest.java | 136 +++ .../impl/AccountAuditPeerGrpcMtlsTest.java | 379 ++++++++ .../service/impl/LogEventServiceImplTest.java | 474 +++++++++ .../impl/LoggingAdminGrpcServiceAuthTest.java | 479 +++++++++- 43 files changed, 3573 insertions(+), 143 deletions(-) create mode 100644 services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/config/AccountAuditGrpcAuthConfiguration.java create mode 100644 services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/AccountAuditReceiptDto.java create mode 100644 services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/AccountAuditReceiptOutcome.java create mode 100644 services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/AccountAuditReceiptStatus.java create mode 100644 services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/AccountAuditScope.java create mode 100644 services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/entity/AccountAuditReceipt.java create mode 100644 services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/entity/AccountAuditReceiptInsertResult.java create mode 100644 services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/repository/AccountAuditReceiptRepository.java create mode 100644 services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/AuditReceiptNotFoundException.java create mode 100644 services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/AuditStorageUnavailableException.java create mode 100644 services/logging-admin-service/src/main/resources/db/migration/V1004__account_audit_receipts.sql create mode 100644 services/logging-admin-service/src/main/resources/db/migration/V1005__account_audit_receipt_projection.sql create mode 100644 services/logging-admin-service/src/main/resources/db/migration/V1006__enforce_account_audit_receipt_digest_format.sql create mode 100644 services/logging-admin-service/src/main/resources/db/migration/V1007__enforce_account_audit_projection_tenant.sql create mode 100644 services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/repository/AccountAuditReceiptRepositoryTest.java create mode 100644 services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/AccountAuditPeerGrpcMtlsTest.java create mode 100644 services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/LogEventServiceImplTest.java diff --git a/design/architecture/microservices/account-service/operations.md b/design/architecture/microservices/account-service/operations.md index a054fd8f7a..bb4895bcf7 100644 --- a/design/architecture/microservices/account-service/operations.md +++ b/design/architecture/microservices/account-service/operations.md @@ -66,7 +66,7 @@ ORDER BY legacy_source.tenant_id, legacy_source.account_id, legacy_source.member ## Saga Participation -The Account audit handoff is a mandatory owner-local durable-outbox target, not a compensated Saga step. Global registration creates only global account/security state and emits a platform-scoped audit with no `tenantId` from that transaction; tenant-scoped profile and membership operations are separate and use the exact committed `tenantId`. Explicit `JoinPublicProductionMembership` emits its separate tenant-scoped audit from the membership transaction. The target contract also requires global `account_security_lock`, `platform_access_ban`, recovery, and suspicious-activity audits to use platform scope and omit `tenantId`; those producers are not yet converged to the current outbox path. Producer consequences are defined in [Account Runtime and Data](./runtime-and-data.md#architecture-and-runtime-notes), while the normative ingress, envelope, receipt, readback, retention, and authorization contract is owned by [Logging & Admin API Contracts](../logging-admin-service/api-contracts.md#account-audit-ingress-and-receipt). **Current local implementation:** registration and successful explicit JOIN append immutable audit envelopes to Account's SQL outbox in the same local transaction as their owner-state writes. Account's delivery job sends the unchanged envelope and marks it complete only after matching terminal receipt evidence; unavailable, `UNIMPLEMENTED`, timeout, mismatched, or ambiguous responses leave the same event `PENDING` for retry. The Logging & Admin receipt receiver, durable receipt persistence/deduplication, exact payload-digest validation, and readback are separate #2848 work and are not implemented in this Account core. This local producer status does not claim PostgreSQL runtime proof or direct text-client end-to-end proof. Durable recovery/reconciliation of a JOIN operation left `PENDING` after an unknown database commit outcome remains open under the Overseer decision and ADR 0025, with recovery ownership assigned to #2848. These audit paths are not Account Saga steps. No Account workflow is currently authorized as a `common-saga` adopter in this document or tracker; existing `accountCreation` and `purchase` `SagaRunner` calls are unclassified implementation drift. Any future Account Saga must first satisfy the explicit owner, boundary, negative-case, and focused-proof classification in [Transaction Strategies](../../system-architecture-transactions.md#mandatory-workflow-adopter-classification). +The Account audit handoff is a mandatory owner-local durable-outbox target, not a compensated Saga step. Global registration creates only global account/security state and emits a platform-scoped audit with no `tenantId` from that transaction; tenant-scoped profile and membership operations are separate and use the exact committed `tenantId`. Explicit `JoinPublicProductionMembership` emits its separate tenant-scoped audit from the membership transaction. The target contract also requires global `account_security_lock`, `platform_access_ban`, recovery, and suspicious-activity audits to use platform scope and omit `tenantId`; those producers are not yet converged to the current outbox path. Producer consequences are defined in [Account Runtime and Data](./runtime-and-data.md#architecture-and-runtime-notes), while the normative ingress, envelope, receipt, readback, retention, and authorization contract is owned by [Logging & Admin API Contracts](../logging-admin-service/api-contracts.md#account-audit-ingress-and-receipt). **Current local implementation:** registration and successful explicit JOIN append immutable audit envelopes to Account's SQL outbox in the same local transaction as their owner-state writes. Account's directly callable offline delivery method submits the unchanged envelope and marks it complete only after matching terminal receipt evidence; unavailable, `UNIMPLEMENTED`, timeout, mismatched, or ambiguous responses leave the same event `PENDING` for retry. The offline receipt/projection owner and authenticated readback are now locally prepared at the [Logging-owned boundary](../logging-admin-service/api-contracts.md#account-audit-ingress-and-receipt). Live `CreateLogEvent` refuses before storage and Account delivery is not automatically scheduled; outstanding outbox rows retain their original identity and remain pending. Account exact readback and guarded evidence recording, retention/cleanup and complete authenticated composition remain unimplemented or unqualified. This local producer status does not claim PostgreSQL runtime proof or direct text-client end-to-end proof. Durable recovery/reconciliation of a JOIN operation left `PENDING` after an unknown database commit outcome remains open under the Overseer decision and ADR 0025, with recovery ownership assigned to #2848. These audit paths are not Account Saga steps. No Account workflow is currently authorized as a `common-saga` adopter in this document or tracker; existing `accountCreation` and `purchase` `SagaRunner` calls are unclassified implementation drift. Any future Account Saga must first satisfy the explicit owner, boundary, negative-case, and focused-proof classification in [Transaction Strategies](../../system-architecture-transactions.md#mandatory-workflow-adopter-classification). The current `PurchaseWorkflowService` implementation for one-time payments and donations is non-exposed, unsupported provider-mutating drift, not a V1 product path or entitlement authority. It currently enters the shared runner to create a payment intent, record the transaction with the Logging & Admin Service, and refund through compensation if the log step fails. The target Account containment boundary requires every generic purchase or donation entry point to reject before entering that runner or making any Stripe call; no supported V1 flow may invoke it. Current V1 remains the hosting-billing boundary in [ADR 0143](../../decisions/adr-0143-stripe-v1-hosting-billing-and-deferred-creator-monetization.md), while the future marketplace direction in [ADR 0179](../../decisions/adr-0179-firemud-managed-creator-commerce-boundary.md) remains deferred and must be implemented and proved separately. diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index c2436f53a7..a61ee0d66a 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -93,7 +93,7 @@ The unregistered canonical gameplay LOGIN primary-credential adapter reuses Acco Raw Telnet and other non-WebSocket text streams never see or transmit these JWT profiles. First-party browser/mobile gameplay clients use only the bounded `player-bootstrap` profile for HTTPS bootstrap; the one-use WebSocket connect token is a separate edge credential. Generic `Service JWT` and `aud=internal` profiles are forbidden. Workload-only calls use mTLS and exact method allowlists without a bearer token. Gameplay protocol clients (Telnet and WebSocket) never see or transmit private delegation tokens. - The live service hashes and verifies raw passwords with `argon2-jvm` Argon2 using `iterations=2`, `memory=65536 KiB`, and `parallelism=1`, with unique salts before PostgreSQL storage. - **Target state:** one versioned issued-token registry record per token is stored in Redis as described in [JWT and Token Contracts](../../system-architecture-jwt-and-token-contracts.md); gameplay session bindings are owned by the Game Session Service and are not managed directly here. **Current runtime:** authentication still uses the legacy Account session key rather than the ADR 0035 registry record. -- **Target state:** global Account registration creates only global account/security state and records a durable, owner-local audit outbox entry in that same local transaction. Tenant-scoped profile and membership operations are separate from registration; registration audit uses explicit **platform scope** and never fabricates a `tenantId`, creates membership, or restores membership. Tenant-scoped profile and successful `JoinPublicProductionMembership` events use explicit **tenant scope** with the exact committed `tenantId`; they never use platform scope. The sole membership writer remains explicit `JoinPublicProductionMembership`; a successful JOIN records its separate tenant-scoped audit/outbox consequence in the same membership transaction as described below. Each outbox record preserves one stable `auditEventId` and immutable event envelope/digest across retries, then delivers that unchanged record through the canonical Account audit-ingress, receipt, and readback contract owned by [Logging & Admin API Contracts](../logging-admin-service/api-contracts.md#account-audit-ingress-and-receipt). Any upstream Account domain-event digest is payload evidence; Logging & Admin's receiver computes its separate `payloadDigest` over the exact payload bytes. Account treats delivery as complete only after an exact receiver receipt; unavailable, timeout, mismatched, or ambiguous responses remain retryable with the same identity and never mint a replacement event. A terminal `MINIMIZED/NON_REPLAYABLE` result after the receiver's safe watermark is recorded against that same outbox identity, ends producer retry/reconciliation, and does not create a replacement event. Account's outbox cleanup remains gated by the receiver/readback horizon and safe-watermark rules owned by Logging & Admin; Account does not invent a second retention policy. This does not make Logging & Admin a second authority for Account state. **Current local implementation:** global registration and successful explicit JOIN append immutable Account audit envelopes in their respective local transactions. Account's delivery job submits the unchanged envelope and marks it delivered only after matching terminal receipt evidence; unavailable, `UNIMPLEMENTED`, timeout, mismatched, or ambiguous responses leave the same outbox identity `PENDING` for retry. The Logging & Admin receipt receiver, durable deduplication, exact payload-byte digest validation, receipt readback, and terminal minimized receipt handling are separate #2848 work and are not implemented in this Account core. After a matching terminal minimized receipt, Account atomically clears only its producer payload and retains compact event, digest, and receiver identity evidence; `COMMITTED` producer payloads still lack configured safe-watermark, hold, reference, and finite-retention cleanup proof. These are local producer facts, not PostgreSQL runtime or direct text end-to-end proof. The JOIN intent is committed before entitlement work, while policy binding, membership, audit outbox, and terminal outcome share one second transaction. Request-driven retry can resume a pending intent but does not resolve an unknown database commit outcome; durable JOIN recovery/reconciliation remains #2848 work, and no periodic pending-operation reconciler is claimed. +- **Target state:** global Account registration creates only global account/security state and records a durable, owner-local audit outbox entry in that same local transaction. Tenant-scoped profile and membership operations are separate from registration; registration audit uses explicit **platform scope** and never fabricates a `tenantId`, creates membership, or restores membership. Tenant-scoped profile and successful `JoinPublicProductionMembership` events use explicit **tenant scope** with the exact committed `tenantId`; they never use platform scope. The sole membership writer remains explicit `JoinPublicProductionMembership`; a successful JOIN records its separate tenant-scoped audit/outbox consequence in the same membership transaction as described below. Each outbox record preserves one stable `auditEventId` and immutable event envelope/digest across retries, then delivers that unchanged record through the canonical Account audit-ingress, receipt, and readback contract owned by [Logging & Admin API Contracts](../logging-admin-service/api-contracts.md#account-audit-ingress-and-receipt). Any upstream Account domain-event digest is payload evidence; Logging & Admin's receiver computes its separate `payloadDigest` over the exact payload bytes. Account treats delivery as complete only after an exact receiver receipt; unavailable, timeout, mismatched, or ambiguous responses remain retryable with the same identity and never mint a replacement event. A terminal `MINIMIZED/NON_REPLAYABLE` result after the receiver's safe watermark is recorded against that same outbox identity, ends producer retry/reconciliation, and does not create a replacement event. Account's outbox cleanup remains gated by the receiver/readback horizon and safe-watermark rules owned by Logging & Admin; Account does not invent a second retention policy. This does not make Logging & Admin a second authority for Account state. **Current local implementation:** global registration and successful explicit JOIN append immutable Account audit envelopes in their respective local transactions. Account's directly callable offline delivery method submits the unchanged envelope and marks it delivered only after matching terminal receipt evidence; unavailable, `UNIMPLEMENTED`, timeout, mismatched, or ambiguous responses leave the same outbox identity `PENDING` for retry. The offline receipt/projection owner and authenticated readback are now locally prepared at the [Logging-owned boundary](../logging-admin-service/api-contracts.md#account-audit-ingress-and-receipt). Live `CreateLogEvent` refuses before storage and Account delivery is not automatically scheduled; outstanding outbox rows retain their original identity and remain pending. Account exact readback and guarded evidence recording, retention/cleanup and complete authenticated composition remain unimplemented or unqualified. After a matching terminal minimized receipt, Account atomically clears only its producer payload and retains compact event, digest, and receiver identity evidence; `COMMITTED` producer payloads still lack configured safe-watermark, hold, reference, and finite-retention cleanup proof. These are local producer facts, not PostgreSQL runtime or direct text end-to-end proof. The JOIN intent is committed before entitlement work, while policy binding, membership, audit outbox, and terminal outcome share one second transaction. Request-driven retry can resume a pending intent but does not resolve an unknown database commit outcome; durable JOIN recovery/reconciliation remains #2848 work, and no periodic pending-operation reconciler is claimed. - **Target state:** Safety-restriction, recovery, and suspicious-activity events are delivered to Logging & Admin through Account's owner-local outbox, with delivery complete only after the exact receipt/readback or terminal reconciliation. Because `account_security_lock` and `platform_access_ban` and their recovery evidence are global, those audits use explicit **platform scope** and omit `tenantId`; Account remains the enforcement owner and Logging & Admin does not own or mutate Account restriction state. **Current implementation status:** registration and successful explicit JOIN use the durable outbox/receipt path described above. The remaining safety-restriction, recovery, and suspicious-activity audit producers have not been converged to that owner-local outbox, so their target delivery and receipt guarantees are not claimed as current behavior. - Account may consume bounded relationship/projection data for Entity-owned actor discovery across games; Entity Management owns persisted actor rows, actor identity, playable-state namespace, creation/provisioning, and gameplay state. Account is not the actor writer or ownership authority. See [ADR 0140](../../decisions/adr-0140-realm-authored-controllable-actor-entry.md). - The core `account` record represents a global platform account identified by `accountId`. Tables that represent per-game state or billing attach to tenants via a `tenantId` column so the same platform account can join multiple games without data leakage. Every tenant-scoped query enforces this filter as described in [Multi-Tenancy](../../system-architecture-multi-tenancy.md). diff --git a/design/architecture/microservices/logging-admin-service/api-contracts.md b/design/architecture/microservices/logging-admin-service/api-contracts.md index cec8f87e82..f04b93a4d5 100644 --- a/design/architecture/microservices/logging-admin-service/api-contracts.md +++ b/design/architecture/microservices/logging-admin-service/api-contracts.md @@ -24,7 +24,7 @@ Target `CreateLogEventRequest` carries `scope` (`platform` or `tenant`), `tenant `CreateLogEventResponse` returns `scope`, the matching `tenantId` only for tenant scope, `auditEventId`, stable receiver-generated `receiptId`, receiver `logEventId`, `schemaVersion`, `payloadDigestVersion`, `payloadDigest`, `status`, and `outcome`. The durable envelope/receipt stores and exact-compares the complete immutable tuple and exact payload bytes defined above while they are retained, and exposes the receipt fields for readback. Its status/outcome vocabulary is `COMMITTED/ACCEPTED` for the first durable write, `COMMITTED/DUPLICATE` for an exact retry before minimization, `MINIMIZED/NON_REPLAYABLE` for a matching request after payload minimization, and `CONFLICT/IDEMPOTENCY_CONFLICT` for a mismatch proven by retained metadata. `MINIMIZED/NON_REPLAYABLE` is a successful typed domain result, so both `CreateLogEvent` and `ReadLogEventReceipt` return gRPC status `OK` with only the bounded digest-only receipt metadata; they do not return payload bytes, claim exact payload equality, or create a replacement identity. The concrete readback is `logging_admin.v1.LoggingAdminService/ReadLogEventReceipt`, whose request carries the same complete tuple and whose response is `ReadLogEventReceiptResponse` with the same receipt fields. Before minimization, an exact readback returns `OK` with `COMMITTED/DUPLICATE` or the original terminal result; after minimization, an exact identity/digest read returns `OK` with `MINIMIZED/NON_REPLAYABLE`. A missing receipt returns canonical non-OK gRPC status `NOT_FOUND`; receiver/dependency unavailability returns canonical non-OK gRPC status `UNAVAILABLE`; neither is an empty typed success. Authorization is a workload-only method: the receiver derives the exact `account-service` mTLS identity, requires the `CreateLogEvent` or `ReadLogEventReceipt` method-specific allowlist entry, and accepts no bearer token or `AdminRole` in that path. -At this stage, `CreateLogEvent` returns gRPC `UNIMPLEMENTED` before request validation or dispatch, and `ReadLogEventReceipt` has no handler. The target workload-only mTLS/method-allowlist receiver, durable receipt/readback, and runtime proof remain unavailable; the target contract is not an implementation claim. +Local receiving preparation authenticates the exact same-namespace Account mTLS workload for both methods. `CreateLogEvent` then returns non-OK `UNAVAILABLE` before envelope validation or storage; its positive transactional receipt/projection owner remains callable only through offline fixtures. `ReadLogEventReceipt` implements the scope-qualified immutable-tuple readback above. Account has not integrated that separate readback or a guarded historical-evidence recorder. Live delivery remains disabled until the retention, cleanup and complete authenticated producer/receiver proof qualify; local implementation and proof status belong to [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#logging-account-audit-receiving-preparation). The receipt retention class and cleanup owner are defined in [Logging & Admin Runtime and Data](./runtime-and-data.md#audit-envelope-and-receipt-retention). @@ -40,7 +40,7 @@ Routine rollback is expected to leave ordinary gameplay available while scoped A ## Implementation Status -- Account-to-Logging audit delivery remains partial in this reconstruction: typed `CreateLogEvent` returns gRPC `UNIMPLEMENTED` and never invokes the legacy generic `log_events` writer. The typed receipt receiver implementation and focused proof are owned by [#2848](https://github.com/benhook1013/FireMUD/pull/2848) and are not integrated in this revision; the target contract above is unchanged. Account's post-commit best-effort delivery path does not establish receiver durability or receipt confirmation. +- Account-to-Logging audit delivery remains disabled. The exact Account-authenticated read adapter and offline transactional receipt/projection owner are locally prepared, while `CreateLogEvent` refuses before storage and Account delivery is not automatically scheduled. Historical receipt provenance, guarded Account evidence recording, retention/cleanup and complete authenticated composition remain held; see the [receiving tracker](../../../project-management/implementation-tracking/player-access-and-session.md#logging-account-audit-receiving-preparation). - Feature-flag toggles and scoped tick-remediation pause/resume ingress routes now hard fail closed as unavailable operator mutations until the minimum three-part schema/authorization gate exists: their action-family schemas, shared cross-language `mutationDigest/v1` golden vectors, and Account-issued authorization-reference issuance plus redemption by the receiving authoritative owner. This minimum gate is necessary but not sufficient for live-success support; supported execution also requires the complete durable, idempotent, fenced owner-mutation contract in [ADR 0048](../../decisions/adr-0048-durable-idempotent-operator-write-execution.md), including durable intent/audit, stable digest-bound request identity, authoritative-owner state, safety/recovery gates, and durable acknowledgement. The HTTP entrypoints preserve authentication, authorization, and basic request validation, then return `503 Service Unavailable` with stable action-specific unavailable error codes (`FEATURE_FLAG_TOGGLE_UNAVAILABLE` or `TICK_REMEDIATION_UNAVAILABLE`) without invoking a service, owner, or audit dependency. The internal `ToggleFeatureFlag` gRPC entrypoint preserves admin-role, positive-tenant, and feature-name validation, then returns an application-level `UNAVAILABLE` error without dispatch. No Logging & Admin feature-flag or tick forwarding method remains callable internally. Admission-pointer reads, audit, and prepared-upgrade proof reads remain live. The current-pointer list forwards only the caller's authorized tenant scopes; an empty owner request remains reserved for global platform administrators and moderators. Each current pointer in the selected scope requires exact latest-audit identity/catalog evidence, and unavailable authority in that scope returns `503`. Public POST/operator mutation routes under `/admission-pointers`, `/cutover`, or `/version-upgrades` are target-only absent: no public HTTP handlers or Gateway write forwarding exist. Internal preparation/cutover service and control-plane implementation remains behind internal trust boundaries, and there is no current UI control. - Availability vocabulary is explicit: **implemented-but-externally-gated** means an executable public controller/owner path exists but the shared mutation gate is incomplete; **target-only absent** means no executable public route exists. Admission-pointer mutation, version-upgrade preparation, and prepared cutover use the latter classification at public HTTP ingress even though internal preparation/cutover implementation remains. Quota-override ingress is also target-only absent. No generic tick-remediation payload or reserved `remediate` route is part of the target; each future recovery operation requires a named typed contract implemented by its authoritative workflow owner. - No forwarded owner mutation is currently supported as a live Logging & Admin capability until its minimum schema/authorization gate and the complete durable, idempotent, fenced owner-execution contract in [ADR 0048](../../decisions/adr-0048-durable-idempotent-operator-write-execution.md) are implemented and proved. The service-local `POST /moderation/actions` endpoint and `ApplyModerationAction` gRPC path now hard fail closed after their narrow tenant/admin checks: HTTP returns `503 Service Unavailable`, gRPC returns an application-level `UNAVAILABLE` error, and neither path dispatches or persists the generic legacy `moderation_actions` row. They remain unsupported, nonconformant implementation drift and must not be wired or called as available mutations; separate fixed-category policy/audit evidence and owner enforcement state are absent, and they are not Gateway-forwarded or supported at external ingress. In the target local workflow, once its applicable schema/authorization and local durable intent/audit requirements are implemented, Logging & Admin records durable intent/case/audit evidence and redeems its one Account reference exactly once; it never forwards that reference or performs owner enforcement. A future typed owner-enforcement command uses a separately issued reference redeemed by its receiving owner. Game Session and Social & Groups synchronously consume the live `EvaluateModerationPolicy` read at the `GAMEPLAY_ADMISSION` and `CHAT_SEND` enforcement boundaries, but that evaluation does not make the legacy action route live. Fixed-category owner commands, monotonic owner state, bounded appeals, and broader policy coverage are not implemented. Existing Game Session `/sessions*` lifecycle routes are current owner-local hooks, not a complete external Logging & Admin route family. Separate current read and investigation surfaces include the PostgreSQL-backed log query, saga reads, metrics, and owner/control-plane reads; profile-aware indexed or console/journal query integration and embedded dashboard endpoints remain target-only and unimplemented. diff --git a/design/architecture/microservices/logging-admin-service/configuration.md b/design/architecture/microservices/logging-admin-service/configuration.md index 288d081343..165f48910e 100644 --- a/design/architecture/microservices/logging-admin-service/configuration.md +++ b/design/architecture/microservices/logging-admin-service/configuration.md @@ -23,12 +23,14 @@ The Logging & Admin Service does **not** connect to Redis at runtime. It consume | `FIREMUD_AUTH_JWT_SECRET` | Legacy HMAC JWT validation secret (transitional only; not for player-facing environments) | *(none)* | | `FIREMUD_AUTH_JWT_SECRET_PATH` | Legacy file path for HMAC JWT validation secret (transitional only; not for player-facing environments) | *(none)* | | `FIREMUD_AUTH_JWT_EXPIRATION_MS` | Lifetime of issued JWTs in milliseconds | `3600000` | -| `FIREMUD_GRPC_WORKLOAD_NAMESPACE` | Canonical namespace for internal gRPC workload identity checks, including the exact Account identity on the StartSession reservation evidence RPC and enabled StartSession coordinator composition; blank configuration denies that method | *(none)* | +| `FIREMUD_GRPC_WORKLOAD_NAMESPACE` | Canonical namespace for internal gRPC workload identity checks, including Account audit methods, the StartSession reservation evidence RPC and enabled StartSession coordinator composition; blank configuration denies those methods | *(none)* | | `FIREMUD_GRPC_ACCOUNT_RESERVATION_EVIDENCE_APPROVED_LEAF_FILE` | Absolute path to the protected, method-scoped Account leaf-approval file for `ReadCurrentClaimEvidence`; blank, unreadable, or invalid policy denies the method | *(none)* | | `FIREMUD_SERVICES_ACCOUNT_SERVICE` | gRPC endpoint (host:port) for the Account Service | *(none)* | | `FIREMUD_SERVICES_GAME_SESSION_SERVICE` | gRPC endpoint (host:port) for the Game Session Service | *(none)* | | `FIREMUD_LOGGING_ADMIN_START_SESSION_OPERATOR_AUTHORIZATION_ENABLED` | Explicitly enables the local StartSession authorization coordinator composition | `false` | +Account audit receiving uses the configured namespace with the exact certificate-derived Account workload identity. The owned Compose mTLS profile supplies `dev`; Kubernetes base and Helm bind the value to `metadata.namespace`. This namespace binding does not upgrade Logging’s shared TLS transport to a distinct protected workload certificate or activate audit writes; the [audit contract](./api-contracts.md#account-audit-ingress-and-receipt) owns those boundaries. + ## Conditional StartSession Coordinator Composition The `FIREMUD_LOGGING_ADMIN_START_SESSION_OPERATOR_AUTHORIZATION_ENABLED` opt-in defaults to `false`. When explicitly enabled, Spring composes the existing durable reservation service with `StartSessionAuthorizationCoordinator` and an Account `StartSessionOperatorAuthorizationClient`; the client is initialized and closed through the managed Spring bean lifecycle. diff --git a/design/architecture/microservices/logging-admin-service/runtime-and-data.md b/design/architecture/microservices/logging-admin-service/runtime-and-data.md index e6b985ac88..738f60ea65 100644 --- a/design/architecture/microservices/logging-admin-service/runtime-and-data.md +++ b/design/architecture/microservices/logging-admin-service/runtime-and-data.md @@ -10,6 +10,8 @@ Logging & Admin uses the common stack outlined in [Logging & Monitoring](../../s Logging & Admin is the operator-facing policy, audit, and observability coordination plane. It owns moderation policy definitions, operator intent, audit history, the target/hypothetical quota and limit override UX, control-plane inspection, and the availability boundary between core operator actions and observability-backed experiences. It does not own gameplay coordination state, runtime feature-flag truth, entity state, or another service's persistence, and it must invoke those owning services through their canonical contracts. For Account audit ingress, it owns only the receiver-side envelope, durable receipt/readback, deduplication, and audit projection defined normatively in [Account Audit Ingress and Receipt](./api-contracts.md#account-audit-ingress-and-receipt); the durable envelope/receipt is keyed by the exact platform/tenant scope plus `auditEventId`, stores and exact-compares the complete immutable retry tuple and exact payload bytes, and retains the receipt fields required for readback. Missing receipts and receiver/dependency unavailability use canonical non-OK gRPC `NOT_FOUND` and `UNAVAILABLE` statuses respectively. Account remains the producer and account-state authority. +Local receipt/projection storage preparation and authenticated readback are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#logging-account-audit-receiving-preparation). The live Create RPC remains unavailable before storage, Account delivery is not automatically scheduled, and this preparation supplies no retention cleanup, historical provenance upgrade or Account recovery authority. + ### Audit envelope and receipt retention The Account audit envelope/receipt is a Logging & Admin-owned **retry and idempotency receipt** plus **purpose-bound audit evidence** family under [ADR 0163](../../decisions/adr-0163-service-owned-retention-classes-with-cross-service-safety.md). The full retry-equivalence tuple and exact payload bytes remain durable through the longest applicable producer retry, receiver readback, duplicate-delivery, and reconciliation horizon, using existing canonical/configured horizons and the applicable legal-hold and erasure-owner links; this service does not invent a duplicate duration. After the producer safe watermark proves that horizon has ended and no legal hold or unresolved reconciliation reference remains, the payload may be minimized or removed, but the receipt retains `scope`, the applicable `tenantId`, `auditEventId`, `producerService`, `eventType`, `occurredAt`, `schemaVersion`, `payloadDigestVersion`, `payloadDigest`, `receiptId`, `logEventId`, terminal `status`/`outcome`, and the source/lineage identifiers needed for later exact proof. A late `CreateLogEvent` retry or `ReadLogEventReceipt` request after minimization is an explicit terminal non-replayable result, never an accepted duplicate or an exact successful readback; the retained digest and receipt metadata must not be presented as proof of exact payload equality. Garbage collection requires terminality, the safe watermark, no pending or ambiguous delivery/readback reference, and no legal hold; age alone is never sufficient. Missing, stale, conflicting, or unavailable evidence while any of those gates may still apply fails closed and cannot authorize deletion or a new event under the old identity. diff --git a/design/architecture/system-architecture-authz-route-matrix.md b/design/architecture/system-architecture-authz-route-matrix.md index 26e8ff5045..593864372a 100644 --- a/design/architecture/system-architecture-authz-route-matrix.md +++ b/design/architecture/system-architecture-authz-route-matrix.md @@ -229,8 +229,8 @@ For every first public-production text entry, the target command sequence is `LO | Logging & Admin | `POST /feature-flags/toggle`, `POST /tick-remediation/pause`, `POST /tick-remediation/resume` | `tenant_regular` operator ingress | **Target; not currently routable.** Exact `control-ui` profile and current operator role. Tenant-role branches require live membership and membership-generation freshness; privileged global-role branches require live `current_global_role` and `role_appropriate_assurance`, while the global `platformAdmin` branch uses target-tenant generation without target membership. Each mutation also requires its action schema, shared `mutationDigest/v1` golden vectors, and Account authorization-reference issuance/redemption before enablement. | | Logging & Admin | `POST /moderation/actions` | `tenant_regular` operator ingress for `gameplay_ban`, `chat_mute`, and `chat_ban`; `account_scoped` platform-jurisdiction ingress for `platform_access_ban` | **Target; unavailable/gated.** The closed `action` selector selects exactly one matrix variant and rejects `account_security_lock`, unknown, and legacy values before branch authorization. Tenant-scoped categories retain the `tenant_regular` branch: `moderator`, `tenantAdmin`, and `platformAdmin` use the existing tenant membership/tenant-generation or global target-tenant-generation consequences. `platform_access_ban` uses the separate `account_scoped` branch: only global `platformAdmin` with `privileged_control`, explicit global target-account binding and platform scope, no `tenantId`, no tenant billing generation, and no membership or tenant-generation checks. Both variants link the root moderation policy-intent authorization contract: Logging & Admin redeems the local Account reference at its receiving boundary; any later owner-enforcement command uses a distinct identity/digest/reference/fingerprint and is redeemed by the selected owner. Target mutation contract: `durable_intent_then_moderation_record_idempotency`. Account remains the enforcement owner for the global restriction; target Game Session and Social & Groups enforcement reads the applicable owner-local durable restriction state or projection. **Current compatibility drift:** both consumers instead call the live `EvaluateModerationPolicy` read at their enforcement boundaries; that read is not a second target moderation authority. Owner-enforcement command coverage remains a recorded gap. | | Logging & Admin | `POST /reports` | `player_bootstrap_tenant` | **Target-only; not currently routable.** Accepts caller-bound `player-bootstrap`, derives `tenantId` and `reporterAccountId` from the authenticated caller and live membership, applies `moderation_report_policy`, and writes a caller-bound durable report record. | -| Logging & Admin | `CreateLogEvent` | `internal_workload` Account audit ingress | **Target-only; receiver and proof unavailable.** The target accepts only the exact Account Service workload mTLS identity (`spiffe://firemud/ns/{namespace}/sa/account-service`), with no bearer token or operator role. The current handler returns gRPC `UNIMPLEMENTED` before request validation, dispatch, or receipt writing; it does not implement the target typed Account receipt capability. The target receiver, PostgreSQL runtime, and direct end-to-end proof remain unavailable. | -| Logging & Admin | `ReadLogEventReceipt` | `internal_workload` Account audit receipt readback | **Target-only; handler and proof unavailable.** The target uses the same exact Account Service mTLS-only caller boundary and no bearer token or operator role, then reads the receipt by the complete immutable envelope tuple. The current service has no read handler and returns gRPC `UNIMPLEMENTED`; receipt readback, PostgreSQL runtime, and direct end-to-end proof remain unavailable. | +| Logging & Admin | `CreateLogEvent` | `internal_workload` Account audit ingress | The RPC authenticates the exact Account Service workload mTLS identity (`spiffe://firemud/ns/{namespace}/sa/account-service`), then returns gRPC `UNAVAILABLE` before envelope validation or storage. Positive receipt/projection persistence remains offline fixture behavior; live writes remain gated on the [receiver retention lifecycle and runtime proof](./microservices/logging-admin-service/api-contracts.md#implementation-status). | +| Logging & Admin | `ReadLogEventReceipt` | `internal_workload` Account audit receipt readback | The local read handler uses the same exact Account Service mTLS-only caller boundary and looks up the scope-qualified receipt identity before checking immutable metadata. Exact payload-byte equality applies only while those bytes remain retained; a digest-only read is limited to a `MINIMIZED/NON_REPLAYABLE` receipt and does not prove payload equality. Receipt semantics are owned by [Account Audit Ingress and Receipt](./microservices/logging-admin-service/api-contracts.md#account-audit-ingress-and-receipt). Account has not integrated this separate readback; historical producer evidence, retention lifecycle, PostgreSQL and direct end-to-end proof remain [activation gates](./microservices/logging-admin-service/api-contracts.md#implementation-status). | | Logging & Admin | `POST /admission-pointers`, `POST /admission-pointers/cutover`, `POST /admission-pointers/version-upgrades` | `tenant_regular` operator ingress | **Target; not currently routable.** This is a target inventory row only: the public OpenAPI surface no longer exposes the admission-pointer open/close/cutover mutations, and the remaining controller/owner paths are implementation drift. The `GET` read/audit/proof-read routes remain live; the `POST` preparation operation is separately gated. Exact `control-ui` profile and current operator role are required for any future ingress. Tenant-role branches require live membership and membership-generation freshness; privileged global-role branches require live `current_global_role` and `role_appropriate_assurance`, while the global `platformAdmin` branch uses target-tenant generation without target membership. Action schemas, shared `mutationDigest/v1` vectors, and Account authorization-reference issuance/redemption are required before external support; the global branch additionally requires target-only `privileged_control`. | | Game Session Service | `ToggleFeatureFlag`, `PauseTicksForScope`, `ResumeTicksForScope`, `SetAdmissionPointer`, `PrepareVersionUpgrade`, `ExecutePreparedVersionCutover` | `internal_workload` mirrored owner RPCs | **Target; not currently routable.** Exact Logging & Admin mTLS workload identity plus an Account-redeemed bounded operator authorization reference; no end-user JWT. These owner RPCs cannot be enabled until the corresponding action schema, shared `mutationDigest/v1` golden vectors, and Account authorization-reference issuance/redemption flow exist. | | Game Session Service | `StartSession` / `RestartSession` / `StopSession` | `internal_workload` operator RPCs | **Status: `target_not_currently_routable` as external operator support.** Exact Logging & Admin mTLS workload identity plus an Account-redeemed bounded operator authorization reference; no end-user JWT. The canonical external ingress is Logging & Admin; direct owner edge exposure is denied during migration. | diff --git a/design/architecture/system-architecture-authz-route-matrix.yaml b/design/architecture/system-architecture-authz-route-matrix.yaml index af282009ba..5346b77e49 100644 --- a/design/architecture/system-architecture-authz-route-matrix.yaml +++ b/design/architecture/system-architecture-authz-route-matrix.yaml @@ -3720,12 +3720,12 @@ routes: end_user_token_required: false implementation_status: known_drift: - - current_handler_retains_AdminRoleGuard_and_returns_UNAVAILABLE_without_dispatch; target_Account_mTLS_audit_receipt_receiver_and_runtime_proof_are_unavailable + - exact_Account_mTLS_peer_is_authenticated_then_CreateLogEvent_returns_UNAVAILABLE_before_validation_or_storage; positive_receipt_projection_is_offline_fixture_only_and_live_activation_remains_retention_and_runtime_proof_gated - service: logging-admin-service route: ReadLogEventReceipt transport: grpc scope: account - route_status: target_not_currently_routable + route_status: current_openapi_operator_surface classification: internal_workload auth_path: exact_mtls_workload issued_token_state: none @@ -3741,7 +3741,7 @@ routes: end_user_token_required: false implementation_status: known_drift: - - current_service_has_no_ReadLogEventReceipt_handler_and_returns_UNIMPLEMENTED; target_Account_mTLS_receipt_readback_and_runtime_proof_are_unavailable + - local_Account_mTLS_receipt_readback_is_implemented_but_not_invoked_by_Account; historical_evidence_retention_lifecycle_and_PostgreSQL_end_to_end_proof_remain_activation_gates - service: logging-admin-service route: ReadCurrentClaimEvidence transport: grpc diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 420a4e383f..8d2d682b34 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -13,3 +13,6 @@ A small inbox for unresolved agent, tooling, environment, and workflow issues; s - `2026-11-01` (Pacific/Auckland): API helper inputs and reply-file shape required local recovery. - A read-only helper correctly refused its supplied external proof directory. Root copied and hash-verified the authorized inputs inside the worktree, without changing permissions, then resumed it. The reply command help omitted the required JSON array-of-string-arrays shape, so Root read its validator to construct the response. Next: add a concise help example in the owning API wrapper; this was reported to Overseer and is not a repository runtime blocker. + +- `2026-11-01` (Pacific/Auckland): CI wait pending-status attribution requires separate provider reads. + - On #3365, the successful Validation CheckRun coexisted with a pending same-name status linked to a later metadata run, while the actual substantive Validation run was still active. Root incorrectly reported a barrier failure before locating that run and corrected Overseer immediately. CI wait named the conflicting status but omitted its description and target URL, requiring separate provider reads to establish attribution. Next: expose those bounded attribution fields in the owning controller diagnostic; reported to FireController Worker. Pending is not evidence that CI failed. 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 a28bf79088..0f0709f0ad 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -768,3 +768,9 @@ No competing target state is currently recorded. Future design discussion is req | Social Groups and Automation | Authenticated gameplay-adjacent communication/presence and runtime script/event admission using the same identity/routing guardrails | Positive-ID/current-account readers; gameplay routing bundles; canonical REST/gRPC error envelopes | | Logging & Admin | Authenticated operator/control-plane reads, mutation/remediation actor identity, audit and response projection; StartSession compares and persists the Account-returned owner tuple for handoff | Control-plane client readers; `ApiResponse` REST boundary; owner-tuple consequence in [Logging & Admin API Contracts](../../architecture/microservices/logging-admin-service/api-contracts.md) under [ADR 0047](../../architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md); implementation/proof status in [AA-1.3](#capability-status) | | Game Logic | Current-state command aggregation after recovery; currently stateless `LOOK`, movement-derived room context, and communication fan-out inputs | Post-restart gameplay command paths backed by shared world/session state | + +### Logging Account audit receiving preparation + +Local receiving work for #2940 preserves the original offline envelope/receipt, scope-qualified bounded projection and exact immutable-tuple/digest owner under the [Logging audit contract](../../architecture/microservices/logging-admin-service/api-contracts.md#account-audit-ingress-and-receipt). Forward Logging migrations V1004–V1007 preserve the existing StartSession and moderation migrations; the donor V2–V5 files are not substituted into current history. Both audit methods require exact same-namespace Account workload identity; `ReadLogEventReceipt` supplies the read adapter, while Create authenticates and returns `UNAVAILABLE` before storage. Account delivery remains directly fixture-callable but is not automatically scheduled. No hardcoded audit projection-version marker is imported into the canonical proto or treated as historical evidence. + +R1419 passes 70 fresh selected cases (49 Logging units, fifteen application/PostgreSQL cases and six Account delivery cases), including exact retry/conflict, scope isolation, projection/receipt rollback, concurrent deduplication and retained-row forward-migration constraints. Seven additional physical loopback mTLS cases pass with the actual selected JWT interceptor and certificate-derived peer identity; their receipt owner is mocked, so they prove caller/method isolation rather than durable storage. Owning jOOQ generation, enabled main/unit/integration static analysis, full Java formatting and documentation checks pass, together with 229 authorization-matrix cases, source/image Compose mTLS and hosted-manifest contracts and scoped ShellCheck. The initial test aggregate left static tasks disabled; the subsequent `fullCheck` run executes and passes them. Fresh source-built runtime proof remains pending. Positive storage fixtures do not prove authenticated production writes, Account exact readback or guarded historical evidence recording. Live write/scheduling restoration requires the genuine producer/receiver chain and owning retention/cleanup gates; no new release, cleanup, production or registration authority is supplied. diff --git a/design/project-management/implementation-tracking/shared-runtime-contracts-and-persistence.md b/design/project-management/implementation-tracking/shared-runtime-contracts-and-persistence.md index 36198ce20e..dacd139eed 100644 --- a/design/project-management/implementation-tracking/shared-runtime-contracts-and-persistence.md +++ b/design/project-management/implementation-tracking/shared-runtime-contracts-and-persistence.md @@ -123,7 +123,7 @@ The [gRPC outcome and transport classification](../../architecture/system-archit ### Audit, Moderation, and Authority Boundaries -Logging & Admin's typed `CreateLogEvent` RPC is present but currently returns gRPC `UNIMPLEMENTED` without invoking the legacy generic `log_events` writer, so it is not an available ingress. Target account-audit receipt/readback persistence and focused receiver proof remain unimplemented; the normative receiver contract is [Account Audit Ingress and Receipt](../../architecture/microservices/logging-admin-service/api-contracts.md#account-audit-ingress-and-receipt). Account-creation audit delivery remains partial: the producer is still a post-commit best-effort effect rather than the target owner-local outbox, and it does not establish receiver durability or receipt confirmation; see [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#implementation-status) for its current implementation, proof, and gap status. Account logging for payment uses the separate existing `LogEvent` RPC and persistence path; it does not fabricate moderation fields, delete accounts, or stop sessions. Moderation mutation remains a separate explicit operator/admin operation. +The local Account audit receiving preparation now supplies offline receipt/projection storage and an exact Account-authenticated read adapter; `CreateLogEvent` authenticates then refuses before storage, and automatic Account delivery is disabled. Account transaction-owned outbox production, current local proof, historical evidence and recovery limits are tracked in [Player Access and Session](./player-access-and-session.md#logging-account-audit-receiving-preparation). The [Logging audit contract](../../architecture/microservices/logging-admin-service/api-contracts.md#account-audit-ingress-and-receipt) and [retention owner](../../architecture/microservices/logging-admin-service/runtime-and-data.md#audit-envelope-and-receipt-retention) define the remaining live-write, exact readback and cleanup gates. This preparation activates no payment or moderation mutation capability. Current status only: Logging & Admin exposes the non-destructive `EvaluateModerationPolicy` read and a gated/unavailable moderation-action seam; current focused proof is partial and covers bounded read, denied, and validation paths only. It does not cover target mutation or appeal workflows, or focused `CHAT_SEND` stale/unavailable dependency and owner-read failure cases. The remaining implementation and proof gaps are tracked against [ADR 0141](../../architecture/decisions/adr-0141-fixed-safety-restriction-categories-and-independent-lifecycles.md) and [ADR 0142](../../architecture/decisions/adr-0142-bounded-moderation-appeal-cases.md). @@ -178,7 +178,7 @@ Current runtime wiring keeps gameplay ticks, Redis coordination, per-command exe | --- | --- | --- | | Common platform/security | Internal auth propagation, service identity parsing, deprecated gameplay-attestation helpers pending removal and authority-boundary proof, gRPC app-error representation/observability, and proto time-field guard | Shared Java seams, deprecated attestation debt pending removal, gRPC helpers, Gradle/root verification | | Owning domain services | Domain authority, tenant/access enforcement, local transaction boundary, durable local state, and app-error mapping | Service REST/gRPC APIs and service-local Flyway schema | -| Logging & Admin | Current separate `LogEvent` RPC and `log_events` persistence path; typed `CreateLogEvent` RPC is present but returns `UNIMPLEMENTED` and is unavailable; moderation policy definition/evaluation, operator projections, and target moderation/report persistence (currently unavailable/gated) | Audit/log-event and moderation/control-plane REST/gRPC contracts; target receiver boundary: [Account Audit Ingress and Receipt](../../architecture/microservices/logging-admin-service/api-contracts.md#account-audit-ingress-and-receipt) | +| Logging & Admin | Offline Account audit receipt/projection owner and authenticated readback; live Create remains unavailable and automatic Account delivery disabled. Moderation policy definition/evaluation, operator projections and target moderation/report persistence remain partial or gated | Audit/log-event and moderation/control-plane REST/gRPC contracts; target receiver boundary: [Account Audit Ingress and Receipt](../../architecture/microservices/logging-admin-service/api-contracts.md#account-audit-ingress-and-receipt) | | Game Session | Player-session authority, exact script-pin authority and rollout-history ownership, gameplay-attestation call sites pending removal and consumer-level authority proof, lifecycle finalization/compensation, tick runtime coordination, and gameplay control-plane delegation | Session/gameplay gRPC, script-pin and rollout-history contracts, deprecated attestation debt pending removal, Redis/runtime records, and durable SQL ledgers | | Common saga | Shared saga repository ownership and short synchronous saga persistence/runner contract | Schema-qualified jOOQ repositories and saga steps | | jOOQ/Flyway tooling | Generated relational access, migration history, service-schema conventions, and Postgres-backed proof support | Build/codegen tasks, Flyway resources, reset/bootstrap tooling | diff --git a/dev-tools/hosted/preview/validate-preview-artifact.py b/dev-tools/hosted/preview/validate-preview-artifact.py index 0056cb115b..f9c762ad36 100644 --- a/dev-tools/hosted/preview/validate-preview-artifact.py +++ b/dev-tools/hosted/preview/validate-preview-artifact.py @@ -68,6 +68,7 @@ def _expected_chart_label(chart_metadata_path: Path) -> str: DISTINCT_GRPC_WORKLOADS = ( PUBLICATION_GRPC_WORKLOADS | ACCOUNT_GRPC_WORKLOADS | GAME_SESSION_GRPC_WORKLOADS | SOCIAL_GROUPS_GRPC_WORKLOADS ) +NAMESPACE_BOUND_GRPC_WORKLOADS = DISTINCT_GRPC_WORKLOADS | {"logging-admin-service"} EXPECTED_NAMES = { "Deployment": SERVICE_IMAGES | {"postgres", "redis-coord", "redis-cache", "minio"}, "Service": SERVICE_IMAGES | {"spring-cloud-gateway-mtls", "postgres", "redis-coord", "redis-cache", "minio"}, @@ -1474,7 +1475,7 @@ def validate_service_consumers( fail(f"Deployment/{service} has an unexpected container layout") container = containers[0] - if service in DISTINCT_GRPC_WORKLOADS: + if service in NAMESPACE_BOUND_GRPC_WORKLOADS: workload_namespace_entries = [ entry for entry in container.get("env", []) diff --git a/dev-tools/tests/compose-grpc-mtls-contract.sh b/dev-tools/tests/compose-grpc-mtls-contract.sh index 31e5d1ea46..1531e559b4 100644 --- a/dev-tools/tests/compose-grpc-mtls-contract.sh +++ b/dev-tools/tests/compose-grpc-mtls-contract.sh @@ -301,6 +301,7 @@ for service in ( "world-management-service", "game-session-service", "game-design-service", + "logging-admin-service", ): headers = [index for index, line in enumerate(lines) if line == f" {service}:"] assert len(headers) == 1, service @@ -424,19 +425,34 @@ for service in "${services[@]}"; do rg -Fq "\${FIREMUD_COMPOSE_GRPC_MTLS_CERT_ROOT:?canonical smoke must set a run-owned mTLS certificate root}/workloads/$service:/app/certs:ro" "$mtls_compose" done -python3 - "$ROOT_DIR/dev-tools/verify-smoke-images.sh" <<'PY' +python3 - "$ROOT_DIR/dev-tools/verify-smoke-images.sh" "$mtls_compose" \ + "$ROOT_DIR/dev-tools/verify-fresh-bootstrap.sh" "$ROOT_DIR/dev-tools/verify-restart-state.sh" <<'PY' import pathlib import sys -source = pathlib.Path(sys.argv[1]).read_text(encoding="utf-8") -profile = source.index('COMPOSE_FILES+=( -f "$DOCKER_DIR/docker-compose.grpc-mtls.override.yml" )') +smoke_source_path, mtls_compose_path, *source_wrapper_paths = sys.argv[1:] +smoke_source = pathlib.Path(smoke_source_path).read_text(encoding="utf-8") +profile = smoke_source.index('COMPOSE_FILES+=( -f "$DOCKER_DIR/docker-compose.grpc-mtls.override.yml" )') for prior_overlay in ( 'docker-compose.smoke-images.override.yml', 'docker-compose.pr-local-minio.override.yml', ): - assert source.index(prior_overlay) < profile, prior_overlay -assert "COMPOSE_UP_ARGS=(up -d --remove-orphans)" in source -assert "--build" not in source + assert smoke_source.index(prior_overlay) < profile, prior_overlay +assert "COMPOSE_UP_ARGS=(up -d --remove-orphans)" in smoke_source +assert "--build" not in smoke_source + +mtls_override = pathlib.Path(mtls_compose_path).read_text(encoding="utf-8") +logging_block = mtls_override.split("\n logging-admin-service:\n", 1)[1].split( + "\n social-groups-service:\n", 1 +)[0] +assert "FIREMUD_GRPC_WORKLOAD_NAMESPACE: dev" in logging_block + +for wrapper_path in source_wrapper_paths: + wrapper = pathlib.Path(wrapper_path).read_text(encoding="utf-8") + base = wrapper.index('-f "$ROOT_DIR/docker/docker-compose.yml"') + local = wrapper.index('-f "$ROOT_DIR/docker/docker-compose.override.yml"') + mtls = wrapper.index('-f "$ROOT_DIR/docker/docker-compose.grpc-mtls.override.yml"') + assert base < local < mtls, wrapper_path PY for wrapper in verify-smoke-images.sh verify-fresh-bootstrap.sh verify-restart-state.sh; do @@ -460,6 +476,7 @@ if command -v docker >/dev/null 2>&1 && docker compose version >/dev/null 2>&1; cp "$ROOT_DIR/.env.sample" "$compose_fixture/.env" rendered_config="$TEST_ROOT/compose-config.json" + source_rendered_config="$TEST_ROOT/compose-source-config.json" FIREMUD_COMPOSE_GRPC_MTLS_CERT_ROOT="$fixture_root" SMOKE_IMAGE_TAG=contract \ FIREMUD_SMOKE_INITIAL_ADMISSION_CAPABILITY_HOST_PATH="$TEST_ROOT/config-probe-capability.json" \ FIREMUD_SMOKE_AUTHORED_WORLD_SOURCE_RECEIPT_DIR_HOST_PATH="$source_receipt_fixture" \ @@ -471,14 +488,26 @@ if command -v docker >/dev/null 2>&1 && docker compose version >/dev/null 2>&1; -f "$compose_fixture/docker/docker-compose.smoke-images.override.yml" \ -f "$compose_fixture/docker/docker-compose.grpc-mtls.override.yml" \ config --format json >"$rendered_config" - python3 - "$rendered_config" "$fixture_root" "$TEST_ROOT/config-probe-capability.json" "$source_receipt_fixture" <<'PY' + FIREMUD_COMPOSE_GRPC_MTLS_CERT_ROOT="$fixture_root" \ + FIREMUD_SMOKE_INITIAL_ADMISSION_CAPABILITY_HOST_PATH="$TEST_ROOT/config-probe-capability.json" \ + FIREMUD_SMOKE_AUTHORED_WORLD_SOURCE_RECEIPT_DIR_HOST_PATH="$source_receipt_fixture" \ + FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED=false \ + FIREMUD_SMOKE_RUN_ID='' FIREMUD_SMOKE_COMPOSE_PROJECT_NAME='' \ + docker compose --env-file "$compose_fixture/.env" \ + -f "$compose_fixture/docker/docker-compose.yml" \ + -f "$compose_fixture/docker/docker-compose.override.yml" \ + -f "$compose_fixture/docker/docker-compose.grpc-mtls.override.yml" \ + config --format json >"$source_rendered_config" + python3 - "$rendered_config" "$source_rendered_config" "$fixture_root" "$TEST_ROOT/config-probe-capability.json" "$source_receipt_fixture" <<'PY' import json import pathlib import sys -config_path, cert_root, capability_source, source_receipt_source = sys.argv[1:] +config_path, source_config_path, cert_root, capability_source, source_receipt_source = sys.argv[1:] config = json.loads(pathlib.Path(config_path).read_text(encoding="utf-8")) +source_config = json.loads(pathlib.Path(source_config_path).read_text(encoding="utf-8")) services = config["services"] +source_services = source_config["services"] app_names = { "account-service", "gateway", "automation-scripting-service", "entity-management-service", "game-design-service", "game-logic-service", @@ -501,10 +530,14 @@ for name in app_names: assert service.get("build") is None, f"image-only proof must not build {name}" for name in ( "account-service", "game-session-service", "entity-management-service", - "world-management-service", "game-design-service", + "world-management-service", "game-design-service", "logging-admin-service", ): namespace = services[name]["environment"].get("FIREMUD_GRPC_WORKLOAD_NAMESPACE") assert namespace == "dev", (name, namespace) +source_logging_namespace = source_services["logging-admin-service"]["environment"].get( + "FIREMUD_GRPC_WORKLOAD_NAMESPACE" +) +assert source_logging_namespace == "dev", ("source", "logging-admin-service", source_logging_namespace) game_session = services["game-session-service"] game_session_environment = game_session["environment"] assert game_session_environment.get("FIREMUD_SMOKE_RUN_ID") == "" diff --git a/dev-tools/tests/hosted-identity-controller-manifest-contract.sh b/dev-tools/tests/hosted-identity-controller-manifest-contract.sh index b0260d5d0f..52b6daf14b 100644 --- a/dev-tools/tests/hosted-identity-controller-manifest-contract.sh +++ b/dev-tools/tests/hosted-identity-controller-manifest-contract.sh @@ -4013,17 +4013,27 @@ def service_consumer_documents(): }, ] elif service != "spring-cloud-gateway": - container["env"] = [ - { - "name": "FIREMUD_GRPC_CERT_CHAIN_PATH", - "value": "/tls/client.crt", - }, - { - "name": "FIREMUD_GRPC_PRIVATE_KEY_PATH", - "value": "/tls/client.key", - }, - {"name": "FIREMUD_GRPC_CA_CERT_PATH", "value": "/tls/ca.crt"}, - ] + container["env"] = [] + if service == "logging-admin-service": + container["env"].append( + { + "name": "FIREMUD_GRPC_WORKLOAD_NAMESPACE", + "valueFrom": {"fieldRef": {"fieldPath": "metadata.namespace"}}, + } + ) + container["env"].extend( + [ + { + "name": "FIREMUD_GRPC_CERT_CHAIN_PATH", + "value": "/tls/client.crt", + }, + { + "name": "FIREMUD_GRPC_PRIVATE_KEY_PATH", + "value": "/tls/client.key", + }, + {"name": "FIREMUD_GRPC_CA_CERT_PATH", "value": "/tls/ca.crt"}, + ] + ) if service == "spring-cloud-gateway": container["env"] = validator._expected_gateway_container_env("pr-42") container["envFrom"] = copy.deepcopy(validator.EXPECTED_GATEWAY_ENV_FROM) @@ -4048,6 +4058,68 @@ def service_consumer_documents(): valid_consumers = service_consumer_documents() validator.validate_service_consumers(valid_consumers, "pr-42", "standalone", "public") +logging_namespace_failure = ( + "Deployment/logging-admin-service must bind " + "FIREMUD_GRPC_WORKLOAD_NAMESPACE to metadata.namespace" +) +missing_logging_namespace = copy.deepcopy(valid_consumers) +logging_deployment = next( + document + for document in missing_logging_namespace + if document["metadata"]["name"] == "logging-admin-service" +) +logging_container = logging_deployment["spec"]["template"]["spec"]["containers"][0] +logging_container["env"] = [ + entry + for entry in logging_container["env"] + if entry.get("name") != "FIREMUD_GRPC_WORKLOAD_NAMESPACE" +] +assert_rejected( + lambda: validator.validate_service_consumers( + missing_logging_namespace, "pr-42", "standalone", "public" + ), + logging_namespace_failure, +) + +duplicate_logging_namespace = copy.deepcopy(valid_consumers) +logging_deployment = next( + document + for document in duplicate_logging_namespace + if document["metadata"]["name"] == "logging-admin-service" +) +logging_container = logging_deployment["spec"]["template"]["spec"]["containers"][0] +logging_namespace = next( + entry + for entry in logging_container["env"] + if entry.get("name") == "FIREMUD_GRPC_WORKLOAD_NAMESPACE" +) +logging_container["env"].append(copy.deepcopy(logging_namespace)) +assert_rejected( + lambda: validator.validate_service_consumers( + duplicate_logging_namespace, "pr-42", "standalone", "public" + ), + logging_namespace_failure, +) + +wrong_logging_namespace = copy.deepcopy(valid_consumers) +logging_deployment = next( + document + for document in wrong_logging_namespace + if document["metadata"]["name"] == "logging-admin-service" +) +logging_container = logging_deployment["spec"]["template"]["spec"]["containers"][0] +next( + entry + for entry in logging_container["env"] + if entry.get("name") == "FIREMUD_GRPC_WORKLOAD_NAMESPACE" +)["valueFrom"] = {"fieldRef": {"fieldPath": "metadata.name"}} +assert_rejected( + lambda: validator.validate_service_consumers( + wrong_logging_namespace, "pr-42", "standalone", "public" + ), + logging_namespace_failure, +) + missing_publication_trust_mount = copy.deepcopy(valid_consumers) publication_deployment = next( document @@ -4728,11 +4800,38 @@ def env_map(container, service): entries = container.get("env") if not isinstance(entries, list): fail(f"Deployment/{service} container has no env list") - return { - entry.get("name"): entry - for entry in entries - if isinstance(entry, dict) and entry.get("name") - } + result = {} + for entry in entries: + if not isinstance(entry, dict) or not entry.get("name"): + continue + name = entry["name"] + if name in result: + fail(f"Deployment/{service} has duplicate env name {name}") + result[name] = entry + return result + + +synthetic_duplicate_env_rejections = 0 +duplicate_namespace_env = { + "name": "FIREMUD_GRPC_WORKLOAD_NAMESPACE", + "valueFrom": {"fieldRef": {"fieldPath": "metadata.namespace"}}, +} +try: + env_map( + {"env": [duplicate_namespace_env, duplicate_namespace_env]}, + "synthetic duplicate fixture", + ) +except SystemExit as error: + if "duplicate env name FIREMUD_GRPC_WORKLOAD_NAMESPACE" not in str(error): + raise + synthetic_duplicate_env_rejections += 1 +else: + fail("synthetic duplicate env fixture was not rejected") +if synthetic_duplicate_env_rejections != 1: + fail( + "synthetic duplicate env proof expected one rejection, found " + f"{synthetic_duplicate_env_rejections}" + ) def assert_paths_and_mount(container, service, cert_path, key_path, ca_path): @@ -4757,6 +4856,32 @@ def assert_paths_and_mount(container, service, cert_path, key_path, ca_path): fail(f"Deployment/{service} grpc-tls must mount read-only at /tls") +def allows_shared_namespace_identity(service, env): + namespace_identity = env.get("FIREMUD_GRPC_WORKLOAD_NAMESPACE") + expected_namespace_identity = { + "name": "FIREMUD_GRPC_WORKLOAD_NAMESPACE", + "valueFrom": {"fieldRef": {"fieldPath": "metadata.namespace"}}, + } + if service == "logging-admin-service": + return namespace_identity == expected_namespace_identity + return namespace_identity is None + + +# The exact downward-API namespace identity is valid only for Logging & Admin +# among shared transports; every other shared service must reject this shape. +negative_shared_namespace_fixture = { + "FIREMUD_GRPC_WORKLOAD_NAMESPACE": { + "name": "FIREMUD_GRPC_WORKLOAD_NAMESPACE", + "valueFrom": {"fieldRef": {"fieldPath": "metadata.namespace"}}, + } +} +for service in shared_services: + if service != "logging-admin-service" and allows_shared_namespace_identity( + service, negative_shared_namespace_fixture + ): + fail(f"shared namespace identity fixture unexpectedly accepted for {service}") + + def assert_distinct_workload_service(service, deployment_map, source): deployment = deployment_for(service, deployment_map) container, pod_spec = workload_container(deployment, service) @@ -4840,7 +4965,14 @@ for service in shared_services: assert_paths_and_mount( container, service, "/tls/client.crt", "/tls/client.key", "/tls/ca.crt" ) - if "FIREMUD_GRPC_WORKLOAD_NAMESPACE" in env_map(container, service): + env = env_map(container, service) + if service == "logging-admin-service": + if not allows_shared_namespace_identity(service, env): + fail( + f"Deployment/{service} must derive FIREMUD_GRPC_WORKLOAD_NAMESPACE " + "from metadata.namespace" + ) + elif "FIREMUD_GRPC_WORKLOAD_NAMESPACE" in env: fail( f"Deployment/{service} shared transport unexpectedly declares " "FIREMUD_GRPC_WORKLOAD_NAMESPACE" @@ -4881,29 +5013,70 @@ for service in ( fail(f"Kustomize base Deployment/{service} must use non-rolling Recreate strategy") for service in distinct_workload_services: assert_distinct_workload_service(service, base_deployments, "Kustomize base") + +base_logging_admin = deployment_for("logging-admin-service", base_deployments) +base_logging_admin_container, base_logging_admin_pod = workload_container( + base_logging_admin, "logging-admin-service" +) +assert_paths_and_mount( + base_logging_admin_container, + "logging-admin-service", + "/tls/client.crt", + "/tls/client.key", + "/tls/ca.crt", +) +base_logging_admin_namespace = env_map( + base_logging_admin_container, "logging-admin-service" +).get("FIREMUD_GRPC_WORKLOAD_NAMESPACE") +if base_logging_admin_namespace != { + "name": "FIREMUD_GRPC_WORKLOAD_NAMESPACE", + "valueFrom": {"fieldRef": {"fieldPath": "metadata.namespace"}}, +}: + fail( + "Kustomize base Deployment/logging-admin-service must derive " + "FIREMUD_GRPC_WORKLOAD_NAMESPACE from metadata.namespace, " + f"found {base_logging_admin_namespace!r}" + ) +base_logging_admin_grpc_volume = named_entry( + base_logging_admin_pod.get("volumes"), + "grpc-tls", + "Kustomize base Deployment/logging-admin-service volumes", +) +if base_logging_admin_grpc_volume.get("secret", {}).get("secretName") != "firemud-grpc-tls": + fail( + "Kustomize base Deployment/logging-admin-service shared grpc-tls must use " + "firemud-grpc-tls" + ) PY -python3 - "$resolved_values" "$namespace_gate_values" <<'PY' +for certificate_identity_mode in standalone hosted-controller; do + for logging_spring_profile in true false; do + python3 - "$resolved_values" "$namespace_gate_values" "$certificate_identity_mode" "$logging_spring_profile" <<'PY' import sys from pathlib import Path import yaml values = yaml.safe_load(Path(sys.argv[1]).read_text(encoding="utf-8")) +certificate_identity_mode = sys.argv[3] +logging_spring_profile = sys.argv[4] == "true" +values["previewStack"]["certificateIdentity"]["mode"] = certificate_identity_mode services = values["previewStack"]["services"] by_name = {service["name"]: service for service in services} +by_name["logging-admin-service"]["springProfile"] = logging_spring_profile +by_name["logging-admin-service"]["mountGrpcTls"] = True by_name["game-design-service"]["springProfile"] = False by_name["game-design-service"]["mountGrpcTls"] = True by_name["world-management-service"]["mountGrpcTls"] = False Path(sys.argv[2]).write_text(yaml.safe_dump(values, sort_keys=False), encoding="utf-8") PY -if ! helm template hosted-identity-namespace-gates "$ROOT_DIR/k8s/helm/firemud" \ - -f "$namespace_gate_values" \ - >"$namespace_gate_rendered"; then - fail "Helm chart render failed for gRPC namespace gate fixture" -fi -python3 - "$namespace_gate_rendered" <<'PY' + if ! helm template "ns-gate-${certificate_identity_mode}-${logging_spring_profile}" "$ROOT_DIR/k8s/helm/firemud" \ + -f "$namespace_gate_values" \ + >"$namespace_gate_rendered"; then + fail "Helm chart render failed for gRPC namespace gate fixture (${certificate_identity_mode}, springProfile=${logging_spring_profile})" + fi + python3 - "$namespace_gate_rendered" "$certificate_identity_mode" "$logging_spring_profile" <<'PY' import sys from pathlib import Path @@ -4919,6 +5092,8 @@ deployments = { for document in yaml.safe_load_all(Path(sys.argv[1]).read_text(encoding="utf-8")) if isinstance(document, dict) and document.get("kind") == "Deployment" } +certificate_identity_mode = sys.argv[2] +logging_spring_profile = sys.argv[3] == "true" def env_map(service): @@ -4929,7 +5104,80 @@ def env_map(service): container = next((item for item in containers if item.get("name") == service), None) if container is None: fail(f"container/{service} is missing") - return {entry.get("name"): entry for entry in container.get("env", []) if entry.get("name")} + entries = container.get("env") + if not isinstance(entries, list): + fail(f"container/{service} has no env list") + result = {} + for entry in entries: + if not isinstance(entry, dict) or not entry.get("name"): + continue + name = entry["name"] + if name in result: + fail(f"Deployment/{service} has duplicate env name {name}") + result[name] = entry + return result + + +logging_env = env_map("logging-admin-service") +logging_deployment = deployments["logging-admin-service"] +logging_container = next( + item + for item in logging_deployment["spec"]["template"]["spec"]["containers"] + if item.get("name") == "logging-admin-service" +) +namespace_entries = [ + entry + for entry in logging_container["env"] + if isinstance(entry, dict) + and entry.get("name") == "FIREMUD_GRPC_WORKLOAD_NAMESPACE" +] +if len(namespace_entries) != 1: + fail( + "logging-admin-service must render exactly one " + "FIREMUD_GRPC_WORKLOAD_NAMESPACE, found " + f"{len(namespace_entries)}" + ) +namespace = logging_env.get("FIREMUD_GRPC_WORKLOAD_NAMESPACE") +if namespace != { + "name": "FIREMUD_GRPC_WORKLOAD_NAMESPACE", + "valueFrom": {"fieldRef": {"fieldPath": "metadata.namespace"}}, +}: + fail(f"logging-admin-service must derive namespace from metadata.namespace, found {namespace!r}") +if logging_spring_profile: + if logging_env.get("SPRING_PROFILES_ACTIVE") != { + "name": "SPRING_PROFILES_ACTIVE", + "value": "prod", + }: + fail("springProfile=true logging-admin-service must enable the prod profile") +elif "SPRING_PROFILES_ACTIVE" in logging_env: + fail("springProfile=false logging-admin-service unexpectedly enables the Spring profile") + +expected_paths = { + "FIREMUD_GRPC_CERT_CHAIN_PATH": "/tls/client.crt", + "FIREMUD_GRPC_PRIVATE_KEY_PATH": "/tls/client.key", + "FIREMUD_GRPC_CA_CERT_PATH": "/tls/ca.crt", +} +for name, value in expected_paths.items(): + if logging_env.get(name, {}).get("value") != value: + fail( + f"{certificate_identity_mode} logging-admin-service must retain shared " + f"{name}={value!r}, found {logging_env.get(name)!r}" + ) +pod_spec = logging_deployment["spec"]["template"]["spec"] +grpc_mounts = [ + mount + for mount in logging_container.get("volumeMounts", []) + if isinstance(mount, dict) and mount.get("name") == "grpc-tls" +] +if len(grpc_mounts) != 1 or grpc_mounts[0].get("mountPath") != "/tls" or grpc_mounts[0].get("readOnly") is not True: + fail(f"{certificate_identity_mode} logging-admin-service must retain its read-only shared /tls mount") +grpc_volumes = [ + volume + for volume in pod_spec.get("volumes", []) + if isinstance(volume, dict) and volume.get("name") == "grpc-tls" +] +if len(grpc_volumes) != 1 or grpc_volumes[0].get("secret", {}).get("secretName") != "firemud-grpc-tls": + fail(f"{certificate_identity_mode} logging-admin-service must retain the shared firemud-grpc-tls Secret") mounted_without_spring = env_map("game-design-service") @@ -4946,5 +5194,7 @@ without_mount = env_map("world-management-service") if "FIREMUD_GRPC_WORKLOAD_NAMESPACE" in without_mount: fail("publication workload without a gRPC TLS mount unexpectedly declares namespace") PY + done +done echo "hosted identity controller manifest contract passed" diff --git a/dev-tools/validation/test_check_authz_route_matrix.py b/dev-tools/validation/test_check_authz_route_matrix.py index ae9d805c22..bdbe08f3f8 100644 --- a/dev-tools/validation/test_check_authz_route_matrix.py +++ b/dev-tools/validation/test_check_authz_route_matrix.py @@ -2801,6 +2801,31 @@ def test_route_status_may_be_omitted_without_implying_routability(self): self.validator.validate_route_statuses(document["routes"], statuses, errors) self.assertEqual([], errors) + def test_account_audit_readback_is_routable_but_ingress_stays_gated(self): + document = self.validator.yaml.safe_load(MATRIX.read_text(encoding="utf-8")) + create = route_for(document, "logging-admin-service", "CreateLogEvent") + readback = route_for(document, "logging-admin-service", "ReadLogEventReceipt") + + self.assertEqual("target_not_currently_routable", create["route_status"]) + self.assertEqual("current_openapi_operator_surface", readback["route_status"]) + auth_fields = ( + "classification", + "auth_path", + "issued_token_state", + "accepted_token_profiles", + "token_type", + "token_issuer", + "token_audience", + "method_policy", + "allowed_callers", + "mtls_callers", + "end_user_token_required", + ) + create_auth = {field: create[field] for field in auth_fields} + readback_auth = {field: readback[field] for field in auth_fields} + self.assertEqual(create_auth, readback_auth) + + def test_required_fields_use_snake_case(self): document = self.validator.yaml.safe_load(MATRIX.read_text(encoding="utf-8")) errors = [] diff --git a/docker/docker-compose.grpc-mtls.override.yml b/docker/docker-compose.grpc-mtls.override.yml index fe093dae93..8d8d05495a 100644 --- a/docker/docker-compose.grpc-mtls.override.yml +++ b/docker/docker-compose.grpc-mtls.override.yml @@ -113,6 +113,7 @@ services: logging-admin-service: environment: <<: *grpc-mtls-environment + FIREMUD_GRPC_WORKLOAD_NAMESPACE: dev volumes: - ${FIREMUD_COMPOSE_GRPC_MTLS_CERT_ROOT:?canonical smoke must set a run-owned mTLS certificate root}/workloads/logging-admin-service:/app/certs:ro diff --git a/k8s/base/logging-admin-service.yaml b/k8s/base/logging-admin-service.yaml index ead0a50c20..6bef595d46 100644 --- a/k8s/base/logging-admin-service.yaml +++ b/k8s/base/logging-admin-service.yaml @@ -24,6 +24,10 @@ spec: env: - name: SPRING_PROFILES_ACTIVE value: "prod" + - name: FIREMUD_GRPC_WORKLOAD_NAMESPACE + valueFrom: + fieldRef: + fieldPath: metadata.namespace - name: FIREMUD_GRPC_CERT_CHAIN_PATH value: /tls/client.crt - name: FIREMUD_GRPC_PRIVATE_KEY_PATH diff --git a/k8s/helm/firemud/templates/apps.yaml b/k8s/helm/firemud/templates/apps.yaml index 61b8b93672..678c165074 100644 --- a/k8s/helm/firemud/templates/apps.yaml +++ b/k8s/helm/firemud/templates/apps.yaml @@ -188,11 +188,13 @@ spec: - name: SERVICE_SCHEMA value: {{ default (replace "-" "_" $service.name) $service.schema | quote }} {{- if $service.mountGrpcTls }} - {{- if $usesGrpcWorkloadIdentity }} + {{- if or $usesGrpcWorkloadIdentity (eq $service.name "logging-admin-service") }} - name: FIREMUD_GRPC_WORKLOAD_NAMESPACE valueFrom: fieldRef: fieldPath: metadata.namespace + {{- end }} + {{- if $usesGrpcWorkloadIdentity }} - name: FIREMUD_GRPC_CERT_CHAIN_PATH value: /tls/tls.crt - name: FIREMUD_GRPC_PRIVATE_KEY_PATH diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuditDeliveryJob.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuditDeliveryJob.java index 66972e5535..52dfd2d251 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuditDeliveryJob.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuditDeliveryJob.java @@ -2,15 +2,13 @@ import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.time.Instant; -import java.util.concurrent.TimeUnit; import net.firedevops.firemud.accountservice.client.LoggingAdminClient; import net.firedevops.firemud.accountservice.repository.AccountAuditOutboxRepository; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; -/** Bounded delivery for retained V1 Account audit envelopes through Logging & Admin receipts. */ +/** Offline-fixture-callable delivery for retained V1 Account audit envelopes. */ @Component @SuppressFBWarnings( value = "EI_EXPOSE_REP2", @@ -26,9 +24,6 @@ public AccountAuditDeliveryJob( this.loggingAdminClient = loggingAdminClient; } - @Scheduled( - fixedDelayString = "${firemud.account.audit.delivery.interval-ms:60000}", - timeUnit = TimeUnit.MILLISECONDS) public void deliverPending() { Instant capturedNow = Instant.now(); for (var envelope : outbox.pending(50, capturedNow)) { diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuditDeliveryJobTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuditDeliveryJobTest.java index 09e8a6bed1..9aecb727b2 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuditDeliveryJobTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuditDeliveryJobTest.java @@ -2,6 +2,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; @@ -27,11 +28,9 @@ class AccountAuditDeliveryJobTest { private final AccountAuditDeliveryJob job = new AccountAuditDeliveryJob(outbox, client); @Test - void deliveryIsScheduledWithTheConfiguredBoundedInterval() throws Exception { - Scheduled scheduled = - AccountAuditDeliveryJob.class.getMethod("deliverPending").getAnnotation(Scheduled.class); - assertEquals( - "${firemud.account.audit.delivery.interval-ms:60000}", scheduled.fixedDelayString()); + void deliveryRemainsDirectlyCallableButIsNotAutomaticallyScheduled() throws Exception { + assertNull( + AccountAuditDeliveryJob.class.getMethod("deliverPending").getAnnotation(Scheduled.class)); } @Test diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/config/AccountAuditGrpcAuthConfiguration.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/config/AccountAuditGrpcAuthConfiguration.java new file mode 100644 index 0000000000..5301aae34d --- /dev/null +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/config/AccountAuditGrpcAuthConfiguration.java @@ -0,0 +1,37 @@ +package net.firedevops.firemud.loggingadmin.config; + +import java.util.HashSet; +import java.util.Set; +import net.firedevops.firemud.common.security.AuthTokenInterceptor; +import net.firedevops.firemud.common.security.GrpcAuthProperties; +import net.firedevops.firemud.common.security.JwtUtil; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.grpc.server.GlobalServerInterceptor; + +/** Allows mTLS-guarded Account audit methods to run without a JWT token. */ +@Configuration(proxyBeanMethods = false) +public class AccountAuditGrpcAuthConfiguration { + private static final Set ACCOUNT_AUDIT_METHODS = + Set.of( + "logging_admin.v1.LoggingAdminService/CreateLogEvent", + "logging_admin.v1.LoggingAdminService/ReadLogEventReceipt"); + + @Bean + @GlobalServerInterceptor + @ConditionalOnProperty( + prefix = "firemud.auth.grpc", + name = "interceptor-enabled", + havingValue = "true", + matchIfMissing = true) + @ConditionalOnMissingBean(AuthTokenInterceptor.class) + public AuthTokenInterceptor accountAuditAuthTokenInterceptor( + @Qualifier("jwtUtil") JwtUtil jwtUtil, GrpcAuthProperties properties) { + Set unauthenticatedMethods = new HashSet<>(properties.getPublicMethods()); + unauthenticatedMethods.addAll(ACCOUNT_AUDIT_METHODS); + return new AuthTokenInterceptor(jwtUtil, unauthenticatedMethods); + } +} diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/AccountAuditReceiptDto.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/AccountAuditReceiptDto.java new file mode 100644 index 0000000000..b80457862e --- /dev/null +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/AccountAuditReceiptDto.java @@ -0,0 +1,13 @@ +package net.firedevops.firemud.loggingadmin.dto; + +public record AccountAuditReceiptDto( + AccountAuditScope scope, + Long tenantId, + String auditEventId, + String receiptId, + long logEventId, + int schemaVersion, + int payloadDigestVersion, + String payloadDigest, + AccountAuditReceiptStatus status, + AccountAuditReceiptOutcome outcome) {} diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/AccountAuditReceiptOutcome.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/AccountAuditReceiptOutcome.java new file mode 100644 index 0000000000..35bdf8d33a --- /dev/null +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/AccountAuditReceiptOutcome.java @@ -0,0 +1,8 @@ +package net.firedevops.firemud.loggingadmin.dto; + +public enum AccountAuditReceiptOutcome { + ACCEPTED, + DUPLICATE, + NON_REPLAYABLE, + IDEMPOTENCY_CONFLICT +} diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/AccountAuditReceiptStatus.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/AccountAuditReceiptStatus.java new file mode 100644 index 0000000000..9c9a8f5047 --- /dev/null +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/AccountAuditReceiptStatus.java @@ -0,0 +1,7 @@ +package net.firedevops.firemud.loggingadmin.dto; + +public enum AccountAuditReceiptStatus { + COMMITTED, + MINIMIZED, + CONFLICT +} diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/AccountAuditScope.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/AccountAuditScope.java new file mode 100644 index 0000000000..e3f9b85a3d --- /dev/null +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/AccountAuditScope.java @@ -0,0 +1,16 @@ +package net.firedevops.firemud.loggingadmin.dto; + +public enum AccountAuditScope { + PLATFORM("platform"), + TENANT("tenant"); + + private final String databaseValue; + + AccountAuditScope(String databaseValue) { + this.databaseValue = databaseValue; + } + + public String databaseValue() { + return databaseValue; + } +} diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/CreateLogEventRequest.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/CreateLogEventRequest.java index bbded3dd0b..0e187d9160 100644 --- a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/CreateLogEventRequest.java +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/CreateLogEventRequest.java @@ -1,10 +1,22 @@ package net.firedevops.firemud.loggingadmin.dto; -import jakarta.validation.constraints.NotNull; -import jakarta.validation.constraints.Size; +import com.google.protobuf.ByteString; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.time.Instant; +/** The immutable Account audit envelope accepted by the existing CreateLogEvent RPC. */ +@SuppressFBWarnings( + value = "EI_EXPOSE_REP", + justification = + "Protobuf ByteString is immutable, so retaining and exposing the payload is safe.") public record CreateLogEventRequest( - @NotNull Long tenantId, - Long accountId, - @NotNull @Size(max = 50) String type, - @NotNull @Size(max = 255) String message) {} + AccountAuditScope scope, + Long tenantId, + String auditEventId, + String producerService, + String eventType, + Instant occurredAt, + int schemaVersion, + ByteString payload, + int payloadDigestVersion, + String payloadDigest) {} diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/entity/AccountAuditReceipt.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/entity/AccountAuditReceipt.java new file mode 100644 index 0000000000..2d3eeeb6c7 --- /dev/null +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/entity/AccountAuditReceipt.java @@ -0,0 +1,31 @@ +package net.firedevops.firemud.loggingadmin.entity; + +import java.util.UUID; + +/** A durable receiver-side audit envelope and its readback receipt. */ +public record AccountAuditReceipt( + long id, + long logEventId, + UUID receiptId, + String scope, + Long tenantId, + String auditEventId, + String producerService, + String eventType, + long occurredAtSeconds, + int occurredAtNanos, + int schemaVersion, + int payloadDigestVersion, + String payloadDigest, + byte[] payload, + String status, + String outcome) { + public AccountAuditReceipt { + payload = payload == null ? null : payload.clone(); + } + + @Override + public byte[] payload() { + return payload == null ? null : payload.clone(); + } +} diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/entity/AccountAuditReceiptInsertResult.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/entity/AccountAuditReceiptInsertResult.java new file mode 100644 index 0000000000..226e9d4046 --- /dev/null +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/entity/AccountAuditReceiptInsertResult.java @@ -0,0 +1,3 @@ +package net.firedevops.firemud.loggingadmin.entity; + +public record AccountAuditReceiptInsertResult(AccountAuditReceipt receipt, boolean inserted) {} diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/repository/AccountAuditReceiptRepository.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/repository/AccountAuditReceiptRepository.java new file mode 100644 index 0000000000..229b42fbf7 --- /dev/null +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/repository/AccountAuditReceiptRepository.java @@ -0,0 +1,128 @@ +package net.firedevops.firemud.loggingadmin.repository; + +import static net.firedevops.firemud.common.persistence.jooq.JooqPersistenceSupport.toLocalDateTime; +import static net.firedevops.firemud.loggingadmin.jooq.tables.AccountAuditReceipts.ACCOUNT_AUDIT_RECEIPTS; +import static net.firedevops.firemud.loggingadmin.jooq.tables.LogEvents.LOG_EVENTS; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.loggingadmin.dto.CreateLogEventRequest; +import net.firedevops.firemud.loggingadmin.entity.AccountAuditReceipt; +import net.firedevops.firemud.loggingadmin.entity.AccountAuditReceiptInsertResult; +import net.firedevops.firemud.loggingadmin.jooq.tables.records.AccountAuditReceiptsRecord; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.stereotype.Repository; + +@Repository +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Injected DSLContext is an internal Spring collaborator.") +public class AccountAuditReceiptRepository { + private static final String ACCOUNT_AUDIT_PROJECTION_TYPE = "ACCOUNT_AUDIT"; + private static final String ACCOUNT_AUDIT_PROJECTION_MESSAGE_PREFIX = "Account audit event "; + + private final DSLContext dsl; + + public AccountAuditReceiptRepository(DSLContext dsl) { + this.dsl = dsl; + } + + public AccountAuditReceiptInsertResult insertIfAbsent( + CreateLogEventRequest request, UUID receiptId) { + long tenantKey = request.tenantId() == null ? 0L : request.tenantId(); + long logEventId = insertOrFindProjection(request); + int inserted = + dsl.insertInto(ACCOUNT_AUDIT_RECEIPTS) + .set(ACCOUNT_AUDIT_RECEIPTS.LOG_EVENT_ID, logEventId) + .set(ACCOUNT_AUDIT_RECEIPTS.RECEIPT_ID, receiptId) + .set(ACCOUNT_AUDIT_RECEIPTS.SCOPE, request.scope().databaseValue()) + .set(ACCOUNT_AUDIT_RECEIPTS.TENANT_ID, request.tenantId()) + .set(ACCOUNT_AUDIT_RECEIPTS.TENANT_KEY, tenantKey) + .set(ACCOUNT_AUDIT_RECEIPTS.AUDIT_EVENT_ID, request.auditEventId()) + .set(ACCOUNT_AUDIT_RECEIPTS.PRODUCER_SERVICE, request.producerService()) + .set(ACCOUNT_AUDIT_RECEIPTS.EVENT_TYPE, request.eventType()) + .set(ACCOUNT_AUDIT_RECEIPTS.OCCURRED_AT_SECONDS, request.occurredAt().getEpochSecond()) + .set(ACCOUNT_AUDIT_RECEIPTS.OCCURRED_AT_NANOS, request.occurredAt().getNano()) + .set(ACCOUNT_AUDIT_RECEIPTS.SCHEMA_VERSION, request.schemaVersion()) + .set(ACCOUNT_AUDIT_RECEIPTS.PAYLOAD_DIGEST_VERSION, request.payloadDigestVersion()) + .set(ACCOUNT_AUDIT_RECEIPTS.PAYLOAD_DIGEST, request.payloadDigest()) + .set(ACCOUNT_AUDIT_RECEIPTS.PAYLOAD, request.payload().toByteArray()) + .set(ACCOUNT_AUDIT_RECEIPTS.STATUS, "COMMITTED") + .set(ACCOUNT_AUDIT_RECEIPTS.OUTCOME, "ACCEPTED") + .onConflictDoNothing() + .execute(); + AccountAuditReceipt receipt = + findByIdentity(request, tenantKey) + .orElseThrow( + () -> + new IllegalStateException( + "Account audit receipt identity conflict did not resolve to a receipt")); + return new AccountAuditReceiptInsertResult(receipt, inserted == 1); + } + + private long insertOrFindProjection(CreateLogEventRequest request) { + Long tenantKey = request.tenantId() == null ? Long.valueOf(0L) : request.tenantId(); + dsl.insertInto(LOG_EVENTS) + .set(LOG_EVENTS.SCOPE, request.scope().databaseValue()) + .set(LOG_EVENTS.TENANT_ID, request.tenantId()) + .set(LOG_EVENTS.TENANT_KEY, tenantKey) + .set(LOG_EVENTS.AUDIT_EVENT_ID, request.auditEventId()) + .set(LOG_EVENTS.TYPE, ACCOUNT_AUDIT_PROJECTION_TYPE) + .set(LOG_EVENTS.MESSAGE, ACCOUNT_AUDIT_PROJECTION_MESSAGE_PREFIX + request.auditEventId()) + .set(LOG_EVENTS.TIMESTAMP, toLocalDateTime(request.occurredAt())) + .set(LOG_EVENTS.ACCOUNT_ID, (Long) null) + .onConflictDoNothing() + .execute(); + + var tenantKeyCondition = LOG_EVENTS.TENANT_KEY.eq(tenantKey); + Long logEventId = + dsl.select(LOG_EVENTS.ID) + .from(LOG_EVENTS) + .where( + LOG_EVENTS + .SCOPE + .eq(request.scope().databaseValue()) + .and(tenantKeyCondition) + .and(LOG_EVENTS.AUDIT_EVENT_ID.eq(request.auditEventId()))) + .fetchOne(LOG_EVENTS.ID); + if (logEventId == null) { + throw new IllegalStateException("Account audit projection identity did not resolve"); + } + return logEventId; + } + + public Optional findByIdentity( + CreateLogEventRequest request, long tenantKey) { + return dsl.selectFrom(ACCOUNT_AUDIT_RECEIPTS) + .where( + ACCOUNT_AUDIT_RECEIPTS + .SCOPE + .eq(request.scope().databaseValue()) + .and(ACCOUNT_AUDIT_RECEIPTS.TENANT_KEY.eq(tenantKey)) + .and(ACCOUNT_AUDIT_RECEIPTS.AUDIT_EVENT_ID.eq(request.auditEventId()))) + .fetchOptional(this::toEntity); + } + + private AccountAuditReceipt toEntity(Record record) { + AccountAuditReceiptsRecord receiptRecord = (AccountAuditReceiptsRecord) record; + return new AccountAuditReceipt( + receiptRecord.getId(), + receiptRecord.getLogEventId(), + receiptRecord.getReceiptId(), + receiptRecord.getScope(), + receiptRecord.getTenantId(), + receiptRecord.getAuditEventId(), + receiptRecord.getProducerService(), + receiptRecord.getEventType(), + receiptRecord.getOccurredAtSeconds(), + receiptRecord.getOccurredAtNanos(), + receiptRecord.getSchemaVersion(), + receiptRecord.getPayloadDigestVersion(), + receiptRecord.getPayloadDigest(), + receiptRecord.getPayload(), + receiptRecord.getStatus(), + receiptRecord.getOutcome()); + } +} diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/repository/LogEventRepository.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/repository/LogEventRepository.java index 0abd0a35c2..3554945a10 100644 --- a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/repository/LogEventRepository.java +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/repository/LogEventRepository.java @@ -7,6 +7,7 @@ import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.util.List; import java.util.Optional; +import net.firedevops.firemud.loggingadmin.dto.AccountAuditScope; import net.firedevops.firemud.loggingadmin.entity.LogEvent; import net.firedevops.firemud.loggingadmin.jooq.tables.records.LogEventsRecord; import org.jooq.DSLContext; @@ -32,7 +33,12 @@ public List findByTenantIdAndMessageContainingIgnoreCase( Long tenantId, String message) { String filter = message == null ? "" : message; return dsl.selectFrom(LOG_EVENTS) - .where(LOG_EVENTS.TENANT_ID.eq(tenantId).and(LOG_EVENTS.MESSAGE.containsIgnoreCase(filter))) + .where( + LOG_EVENTS + .SCOPE + .eq(AccountAuditScope.TENANT.databaseValue()) + .and(LOG_EVENTS.TENANT_ID.eq(tenantId)) + .and(LOG_EVENTS.MESSAGE.containsIgnoreCase(filter))) .fetch(this::toEntity); } @@ -43,6 +49,7 @@ public Optional findFirstByTenantIdAndTypeAndMessage( LOG_EVENTS .TENANT_ID .eq(tenantId) + .and(LOG_EVENTS.SCOPE.eq(AccountAuditScope.TENANT.databaseValue())) .and(LOG_EVENTS.TYPE.eq(type)) .and(LOG_EVENTS.MESSAGE.eq(message))) .orderBy(LOG_EVENTS.ID.asc()) @@ -61,11 +68,13 @@ public LogEvent save(LogEvent entity) { int updated = dsl.update(LOG_EVENTS) .set(LOG_EVENTS.TENANT_ID, entity.getTenantId()) + .set(LOG_EVENTS.TENANT_KEY, entity.getTenantId()) + .set(LOG_EVENTS.SCOPE, AccountAuditScope.TENANT.databaseValue()) .set(LOG_EVENTS.TYPE, entity.getType()) .set(LOG_EVENTS.MESSAGE, entity.getMessage()) .set(LOG_EVENTS.TIMESTAMP, toLocalDateTime(entity.getTimestamp())) .set(LOG_EVENTS.ACCOUNT_ID, entity.getAccountId()) - .where(LOG_EVENTS.ID.eq(entity.getId())) + .where(LOG_EVENTS.ID.eq(entity.getId()).and(LOG_EVENTS.AUDIT_EVENT_ID.isNull())) .execute(); if (updated != 1) { throw new IllegalStateException("Failed to update log_events id=" + entity.getId()); @@ -79,6 +88,8 @@ private Optional findById(Long id) { private void populate(LogEventsRecord record, LogEvent entity) { record.setTenantId(entity.getTenantId()); + record.setTenantKey(entity.getTenantId()); + record.setScope(AccountAuditScope.TENANT.databaseValue()); record.setType(entity.getType()); record.setMessage(entity.getMessage()); record.setTimestamp(toLocalDateTime(entity.getTimestamp())); diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/AuditReceiptNotFoundException.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/AuditReceiptNotFoundException.java new file mode 100644 index 0000000000..52b49613b5 --- /dev/null +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/AuditReceiptNotFoundException.java @@ -0,0 +1,7 @@ +package net.firedevops.firemud.loggingadmin.service; + +public class AuditReceiptNotFoundException extends RuntimeException { + public AuditReceiptNotFoundException() { + super("Account audit receipt not found"); + } +} diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/AuditStorageUnavailableException.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/AuditStorageUnavailableException.java new file mode 100644 index 0000000000..c8abf99170 --- /dev/null +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/AuditStorageUnavailableException.java @@ -0,0 +1,7 @@ +package net.firedevops.firemud.loggingadmin.service; + +public class AuditStorageUnavailableException extends RuntimeException { + public AuditStorageUnavailableException(Throwable cause) { + super("Account audit receipt storage is unavailable", cause); + } +} diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/LogEventService.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/LogEventService.java index 0617b3ad2e..e86cc22dc0 100644 --- a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/LogEventService.java +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/LogEventService.java @@ -1,8 +1,10 @@ package net.firedevops.firemud.loggingadmin.service; +import net.firedevops.firemud.loggingadmin.dto.AccountAuditReceiptDto; import net.firedevops.firemud.loggingadmin.dto.CreateLogEventRequest; -import net.firedevops.firemud.loggingadmin.dto.LogEventDto; public interface LogEventService { - LogEventDto createLogEvent(CreateLogEventRequest request); + AccountAuditReceiptDto createLogEvent(CreateLogEventRequest request); + + AccountAuditReceiptDto readLogEventReceipt(CreateLogEventRequest request); } diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/LogEventServiceImpl.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/LogEventServiceImpl.java index fc3c54d6a0..729818f753 100644 --- a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/LogEventServiceImpl.java +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/LogEventServiceImpl.java @@ -1,13 +1,26 @@ package net.firedevops.firemud.loggingadmin.service.impl; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; -import io.micrometer.core.annotation.Timed; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; import java.time.Instant; +import java.util.Arrays; +import java.util.HexFormat; +import java.util.Objects; +import java.util.UUID; import net.firedevops.firemud.common.LoggingUtil; +import net.firedevops.firemud.loggingadmin.dto.AccountAuditReceiptDto; +import net.firedevops.firemud.loggingadmin.dto.AccountAuditReceiptOutcome; +import net.firedevops.firemud.loggingadmin.dto.AccountAuditReceiptStatus; import net.firedevops.firemud.loggingadmin.dto.CreateLogEventRequest; -import net.firedevops.firemud.loggingadmin.dto.LogEventDto; -import net.firedevops.firemud.loggingadmin.entity.LogEvent; -import net.firedevops.firemud.loggingadmin.repository.LogEventRepository; +import net.firedevops.firemud.loggingadmin.entity.AccountAuditReceipt; +import net.firedevops.firemud.loggingadmin.entity.AccountAuditReceiptInsertResult; +import net.firedevops.firemud.loggingadmin.repository.AccountAuditReceiptRepository; +import net.firedevops.firemud.loggingadmin.service.AuditReceiptNotFoundException; +import net.firedevops.firemud.loggingadmin.service.AuditStorageUnavailableException; import net.firedevops.firemud.loggingadmin.service.LogEventService; import org.slf4j.Logger; import org.springframework.stereotype.Service; @@ -19,31 +32,215 @@ justification = "Spring injects the shared repository singleton for this service seam.") public class LogEventServiceImpl implements LogEventService { private static final Logger logger = LoggingUtil.getLogger(LogEventServiceImpl.class); + private static final String ACCOUNT_SERVICE = "account-service"; + private static final String SHA_256_PREFIX = "sha256:"; - private final LogEventRepository repository; + private final AccountAuditReceiptRepository repository; - public LogEventServiceImpl(LogEventRepository repository) { + public LogEventServiceImpl(AccountAuditReceiptRepository repository) { this.repository = repository; } @Override @Transactional - @Timed(value = "logging.createLogEvent") - public LogEventDto createLogEvent(CreateLogEventRequest request) { - logger.info("Creating log event {} for tenant {}", request.type(), request.tenantId()); - LogEvent entity = new LogEvent(); - entity.setTenantId(request.tenantId()); - entity.setAccountId(request.accountId()); - entity.setType(request.type()); - entity.setMessage(request.message()); - entity.setTimestamp(Instant.now()); - entity = repository.save(entity); - return new LogEventDto( - entity.getId(), - entity.getTenantId(), - entity.getAccountId(), - entity.getType(), - entity.getMessage(), - entity.getTimestamp()); + public AccountAuditReceiptDto createLogEvent(CreateLogEventRequest request) { + validateEnvelope(request); + try { + AccountAuditReceiptInsertResult result = + repository.insertIfAbsent(request, UUID.randomUUID()); + return receiptOutcome(result.receipt(), request, result.inserted(), true); + } catch (org.jooq.exception.DataAccessException + | org.springframework.dao.DataAccessException ex) { + logger.warn("Account audit receipt write is unavailable: {}", ex.getClass().getSimpleName()); + throw new AuditStorageUnavailableException(ex); + } + } + + @Override + @Transactional(readOnly = true) + public AccountAuditReceiptDto readLogEventReceipt(CreateLogEventRequest request) { + validateEnvelopeMetadata(request); + boolean payloadSupplied = payloadSuppliedForRead(request); + if (payloadSupplied) { + validateExactPayload(request); + } + try { + long tenantKey = request.tenantId() == null ? 0L : request.tenantId(); + AccountAuditReceipt receipt = + repository + .findByIdentity(request, tenantKey) + .orElseThrow(AuditReceiptNotFoundException::new); + return receiptOutcome(receipt, request, false, payloadSupplied); + } catch (AuditReceiptNotFoundException ex) { + throw ex; + } catch (org.jooq.exception.DataAccessException + | org.springframework.dao.DataAccessException ex) { + logger.warn("Account audit receipt read is unavailable: {}", ex.getClass().getSimpleName()); + throw new AuditStorageUnavailableException(ex); + } + } + + private static AccountAuditReceiptDto receiptOutcome( + AccountAuditReceipt receipt, + CreateLogEventRequest request, + boolean inserted, + boolean payloadSupplied) { + if (inserted) { + return toDto( + receipt, AccountAuditReceiptStatus.COMMITTED, AccountAuditReceiptOutcome.ACCEPTED); + } + + boolean metadataMatches = metadataMatches(receipt, request); + if (!metadataMatches) { + return toDto( + receipt, + AccountAuditReceiptStatus.CONFLICT, + AccountAuditReceiptOutcome.IDEMPOTENCY_CONFLICT); + } + + byte[] retainedPayload = receipt.payload(); + if (retainedPayload == null) { + return toDto( + receipt, AccountAuditReceiptStatus.MINIMIZED, AccountAuditReceiptOutcome.NON_REPLAYABLE); + } + if (!payloadSupplied) { + return toDto( + receipt, + AccountAuditReceiptStatus.CONFLICT, + AccountAuditReceiptOutcome.IDEMPOTENCY_CONFLICT); + } + if (!Arrays.equals(retainedPayload, request.payload().toByteArray())) { + return toDto( + receipt, + AccountAuditReceiptStatus.CONFLICT, + AccountAuditReceiptOutcome.IDEMPOTENCY_CONFLICT); + } + + if ("MINIMIZED".equals(receipt.status()) || "NON_REPLAYABLE".equals(receipt.outcome())) { + return toDto( + receipt, AccountAuditReceiptStatus.MINIMIZED, AccountAuditReceiptOutcome.NON_REPLAYABLE); + } + if (!"COMMITTED".equals(receipt.status())) { + throw new IllegalStateException("Unknown persisted account audit receipt status"); + } + return toDto( + receipt, AccountAuditReceiptStatus.COMMITTED, AccountAuditReceiptOutcome.DUPLICATE); + } + + private static boolean metadataMatches( + AccountAuditReceipt receipt, CreateLogEventRequest request) { + Instant occurredAt = request.occurredAt(); + return receipt.scope().equals(request.scope().databaseValue()) + && Objects.equals(receipt.tenantId(), request.tenantId()) + && receipt.auditEventId().equals(request.auditEventId()) + && receipt.producerService().equals(request.producerService()) + && receipt.eventType().equals(request.eventType()) + && receipt.occurredAtSeconds() == occurredAt.getEpochSecond() + && receipt.occurredAtNanos() == occurredAt.getNano() + && receipt.schemaVersion() == request.schemaVersion() + && receipt.payloadDigestVersion() == request.payloadDigestVersion() + && receipt.payloadDigest().equals(request.payloadDigest()); + } + + private static AccountAuditReceiptDto toDto( + AccountAuditReceipt receipt, + AccountAuditReceiptStatus status, + AccountAuditReceiptOutcome outcome) { + return new AccountAuditReceiptDto( + "platform".equals(receipt.scope()) + ? net.firedevops.firemud.loggingadmin.dto.AccountAuditScope.PLATFORM + : net.firedevops.firemud.loggingadmin.dto.AccountAuditScope.TENANT, + receipt.tenantId(), + receipt.auditEventId(), + receipt.receiptId().toString(), + receipt.logEventId(), + receipt.schemaVersion(), + receipt.payloadDigestVersion(), + receipt.payloadDigest(), + status, + outcome); + } + + private static void validateEnvelope(CreateLogEventRequest request) { + validateEnvelopeMetadata(request); + validateExactPayload(request); + } + + private static void validateEnvelopeMetadata(CreateLogEventRequest request) { + if (request == null + || request.scope() == null + || request.auditEventId() == null + || request.auditEventId().isBlank() + || request.producerService() == null + || !ACCOUNT_SERVICE.equals(request.producerService()) + || request.eventType() == null + || request.eventType().isBlank() + || request.occurredAt() == null + || request.schemaVersion() <= 0 + || request.payload() == null + || request.payloadDigest() == null) { + throw new IllegalArgumentException("Account audit envelope is incomplete"); + } + if (!isCanonicalUuid(request.auditEventId())) { + throw new IllegalArgumentException("auditEventId must be a canonical UUID"); + } + if (request.scope() == net.firedevops.firemud.loggingadmin.dto.AccountAuditScope.PLATFORM) { + if (request.tenantId() != null) { + throw new IllegalArgumentException("tenantId must be absent for platform scope"); + } + } else if (request.tenantId() == null || request.tenantId() <= 0) { + throw new IllegalArgumentException("tenantId must be positive for tenant scope"); + } + if (request.payloadDigestVersion() != 1) { + throw new IllegalArgumentException("payloadDigestVersion must be 1"); + } + if (!request.payloadDigest().matches("sha256:[0-9a-f]{64}")) { + throw new IllegalArgumentException("payloadDigest must be lowercase sha256 hex"); + } + } + + private static void validateExactPayload(CreateLogEventRequest request) { + byte[] payloadBytes = request.payload().toByteArray(); + validateUtf8(payloadBytes); + String computedDigest = SHA_256_PREFIX + sha256Hex(payloadBytes); + if (!computedDigest.equals(request.payloadDigest())) { + throw new IllegalArgumentException("payloadDigest does not match the exact payload bytes"); + } + } + + private static boolean payloadSuppliedForRead(CreateLogEventRequest request) { + if (!request.payload().isEmpty()) { + return true; + } + String emptyPayloadDigest = SHA_256_PREFIX + sha256Hex(new byte[0]); + return emptyPayloadDigest.equals(request.payloadDigest()); + } + + private static boolean isCanonicalUuid(String value) { + try { + return value.equals(UUID.fromString(value).toString()); + } catch (IllegalArgumentException ex) { + return false; + } + } + + private static void validateUtf8(byte[] payload) { + try { + StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(java.nio.ByteBuffer.wrap(payload)); + } catch (CharacterCodingException ex) { + throw new IllegalArgumentException("payload must contain exact UTF-8 bytes", ex); + } + } + + private static String sha256Hex(byte[] payload) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(payload)); + } catch (NoSuchAlgorithmException ex) { + throw new IllegalStateException("SHA-256 is unavailable", ex); + } } } diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/LoggingAdminGrpcService.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/LoggingAdminGrpcService.java index 7fe45e1381..6c7db77354 100644 --- a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/LoggingAdminGrpcService.java +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/LoggingAdminGrpcService.java @@ -1,26 +1,41 @@ package net.firedevops.firemud.loggingadmin.service.impl; +import com.google.protobuf.ByteString; +import com.google.protobuf.Timestamp; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import io.grpc.Status; import io.grpc.stub.StreamObserver; import io.micrometer.core.annotation.Timed; import io.micrometer.core.instrument.MeterRegistry; +import java.time.Instant; import java.util.List; +import java.util.Map; import java.util.Set; import java.util.UUID; import net.firedevops.firemud.common.grpc.GrpcAppErrors; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.security.AdminAuthorizationException; import net.firedevops.firemud.common.security.AdminRoleGuard; import net.firedevops.firemud.common.security.JwtClaims; import net.firedevops.firemud.common.security.RequestIdValidation; import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.loggingadmin.dto.AccountAuditReceiptDto; +import net.firedevops.firemud.loggingadmin.dto.AccountAuditReceiptOutcome; +import net.firedevops.firemud.loggingadmin.dto.AccountAuditReceiptStatus; +import net.firedevops.firemud.loggingadmin.dto.AccountAuditScope; +import net.firedevops.firemud.loggingadmin.service.AuditReceiptNotFoundException; +import net.firedevops.firemud.loggingadmin.service.AuditStorageUnavailableException; import net.firedevops.firemud.loggingadmin.service.LogEventService; import net.firedevops.firemud.loggingadmin.service.LogQueryService; import net.firedevops.firemud.loggingadmin.service.ModerationService; import net.firedevops.firemud.loggingadmin.v1.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.dao.DataAccessException; import org.springframework.grpc.server.service.GrpcService; +import org.springframework.transaction.TransactionException; @GrpcService public class LoggingAdminGrpcService extends LoggingAdminServiceGrpc.LoggingAdminServiceImplBase { @@ -31,10 +46,16 @@ public class LoggingAdminGrpcService extends LoggingAdminServiceGrpc.LoggingAdmi "Feature-flag toggles are unavailable until the shared mutation gate is implemented"; private static final Set MODERATION_POLICY_CALLERS = Set.of("game-session-service", "social-groups-service"); + private static final String ACCOUNT_SERVICE = "account-service"; + private static final Map> ACCOUNT_AUDIT_CALLER_ALLOWLIST = + Map.of( + "CreateLogEvent", Set.of(ACCOUNT_SERVICE), + "ReadLogEventReceipt", Set.of(ACCOUNT_SERVICE)); private final LogQueryService logQueryService; private final LogEventService logEventService; private final ModerationService moderationService; + private final String workloadNamespace; @SuppressFBWarnings( value = "EI_EXPOSE_REP2", @@ -46,10 +67,21 @@ public LoggingAdminGrpcService( LogEventService logEventService, ModerationService moderationService, MeterRegistry meterRegistry) { + this(logQueryService, logEventService, moderationService, meterRegistry, null); + } + + @Autowired + public LoggingAdminGrpcService( + LogQueryService logQueryService, + LogEventService logEventService, + ModerationService moderationService, + MeterRegistry meterRegistry, + @Value("${firemud.grpc.workload-namespace:}") String workloadNamespace) { this.logQueryService = logQueryService; this.logEventService = logEventService; this.moderationService = moderationService; this.meterRegistry = meterRegistry; + this.workloadNamespace = workloadNamespace; } @Override @@ -176,13 +208,199 @@ public void queryLogs( @Timed(value = "loggingadminGrpc.createLogEvent") public void createLogEvent( CreateLogEventRequest request, StreamObserver responseObserver) { + try { + requireAccountAuditCaller("CreateLogEvent"); + } catch (AdminAuthorizationException ex) { + responseObserver.onError( + Status.PERMISSION_DENIED.withDescription(ex.getMessage()).asRuntimeException()); + return; + } + responseObserver.onError( Status.UNAVAILABLE - .withDescription( - "Typed account audit receipt receiver is unavailable in this service revision") + .withDescription("Account audit ingress is unavailable") .asRuntimeException()); } + @Override + @Timed(value = "loggingadminGrpc.readLogEventReceipt") + public void readLogEventReceipt( + ReadLogEventReceiptRequest request, + StreamObserver responseObserver) { + try { + requireAccountAuditCaller("ReadLogEventReceipt"); + AccountAuditReceiptDto receipt = logEventService.readLogEventReceipt(toAuditRequest(request)); + responseObserver.onNext(toReadLogEventReceiptResponse(receipt)); + responseObserver.onCompleted(); + } catch (AdminAuthorizationException ex) { + responseObserver.onError( + Status.PERMISSION_DENIED.withDescription(ex.getMessage()).asRuntimeException()); + } catch (IllegalArgumentException ex) { + responseObserver.onError( + Status.INVALID_ARGUMENT.withDescription(ex.getMessage()).asRuntimeException()); + } catch (AuditReceiptNotFoundException ex) { + responseObserver.onError( + Status.NOT_FOUND.withDescription(ex.getMessage()).asRuntimeException()); + } catch (AuditStorageUnavailableException ex) { + responseObserver.onError( + Status.UNAVAILABLE.withDescription(ex.getMessage()).asRuntimeException()); + } catch (DataAccessException | TransactionException ex) { + logger.warn( + "ReadLogEventReceipt transaction is unavailable: {}", ex.getClass().getSimpleName()); + responseObserver.onError( + Status.UNAVAILABLE + .withDescription("Account audit receipt storage is unavailable") + .asRuntimeException()); + } catch (Exception ex) { + logger.error("ReadLogEventReceipt failed before producing a receipt", ex); + responseObserver.onError( + Status.INTERNAL + .withDescription("Account audit receipt read failed") + .asRuntimeException()); + } + } + + private static net.firedevops.firemud.loggingadmin.dto.CreateLogEventRequest toAuditRequest( + ReadLogEventReceiptRequest request) { + return toAuditRequest( + request.getScope(), + request.getTenantId(), + request.getAuditEventId(), + request.getProducerService(), + request.getEventType(), + request.hasOccurredAt() ? request.getOccurredAt() : null, + request.getSchemaVersion(), + request.getPayload(), + request.getPayloadDigestVersion(), + request.getPayloadDigest()); + } + + private static net.firedevops.firemud.loggingadmin.dto.CreateLogEventRequest toAuditRequest( + net.firedevops.firemud.loggingadmin.v1.AccountAuditScope requestScope, + String tenantIdText, + String auditEventId, + String producerService, + String eventType, + Timestamp occurredAt, + int schemaVersion, + ByteString payload, + int payloadDigestVersion, + String payloadDigest) { + AccountAuditScope scope = + switch (requestScope) { + case ACCOUNT_AUDIT_SCOPE_PLATFORM -> AccountAuditScope.PLATFORM; + case ACCOUNT_AUDIT_SCOPE_TENANT -> AccountAuditScope.TENANT; + default -> throw new IllegalArgumentException("scope must be platform or tenant"); + }; + Long tenantId; + if (scope == AccountAuditScope.TENANT) { + tenantId = RequestIdValidation.requirePositiveLong(tenantIdText, "tenantId"); + } else { + if (!tenantIdText.isEmpty()) { + throw new IllegalArgumentException("tenantId must be absent for platform scope"); + } + tenantId = null; + } + if (!ACCOUNT_SERVICE.equals(producerService)) { + throw new IllegalArgumentException( + "producerService must match the authenticated account-service workload"); + } + if (occurredAt == null) { + throw new IllegalArgumentException("occurredAt is required"); + } + if (occurredAt.getSeconds() < -62135596800L + || occurredAt.getSeconds() > 253402300799L + || occurredAt.getNanos() < 0 + || occurredAt.getNanos() > 999999999) { + throw new IllegalArgumentException("occurredAt must be a valid protobuf timestamp"); + } + return new net.firedevops.firemud.loggingadmin.dto.CreateLogEventRequest( + scope, + tenantId, + auditEventId, + ACCOUNT_SERVICE, + eventType, + Instant.ofEpochSecond(occurredAt.getSeconds(), occurredAt.getNanos()), + schemaVersion, + payload, + payloadDigestVersion, + payloadDigest); + } + + static CreateLogEventResponse toCreateLogEventResponse(AccountAuditReceiptDto receipt) { + return CreateLogEventResponse.newBuilder() + .setScope(toProtoScope(receipt.scope())) + .setTenantId(receipt.tenantId() == null ? "" : receipt.tenantId().toString()) + .setAuditEventId(receipt.auditEventId()) + .setReceiptId(receipt.receiptId()) + .setLogEventId(Long.toString(receipt.logEventId())) + .setSchemaVersion(receipt.schemaVersion()) + .setPayloadDigestVersion(receipt.payloadDigestVersion()) + .setPayloadDigest(receipt.payloadDigest()) + .setStatus(toProtoStatus(receipt.status())) + .setOutcome(toProtoOutcome(receipt.outcome())) + .build(); + } + + private static ReadLogEventReceiptResponse toReadLogEventReceiptResponse( + AccountAuditReceiptDto receipt) { + return ReadLogEventReceiptResponse.newBuilder() + .setScope(toProtoScope(receipt.scope())) + .setTenantId(receipt.tenantId() == null ? "" : receipt.tenantId().toString()) + .setAuditEventId(receipt.auditEventId()) + .setReceiptId(receipt.receiptId()) + .setLogEventId(Long.toString(receipt.logEventId())) + .setSchemaVersion(receipt.schemaVersion()) + .setPayloadDigestVersion(receipt.payloadDigestVersion()) + .setPayloadDigest(receipt.payloadDigest()) + .setStatus(toProtoStatus(receipt.status())) + .setOutcome(toProtoOutcome(receipt.outcome())) + .build(); + } + + private static net.firedevops.firemud.loggingadmin.v1.AccountAuditScope toProtoScope( + AccountAuditScope scope) { + return switch (scope) { + case PLATFORM -> + net.firedevops.firemud.loggingadmin.v1.AccountAuditScope.ACCOUNT_AUDIT_SCOPE_PLATFORM; + case TENANT -> + net.firedevops.firemud.loggingadmin.v1.AccountAuditScope.ACCOUNT_AUDIT_SCOPE_TENANT; + }; + } + + private static net.firedevops.firemud.loggingadmin.v1.AccountAuditReceiptStatus toProtoStatus( + AccountAuditReceiptStatus status) { + return switch (status) { + case COMMITTED -> + net.firedevops.firemud.loggingadmin.v1.AccountAuditReceiptStatus + .ACCOUNT_AUDIT_RECEIPT_STATUS_COMMITTED; + case MINIMIZED -> + net.firedevops.firemud.loggingadmin.v1.AccountAuditReceiptStatus + .ACCOUNT_AUDIT_RECEIPT_STATUS_MINIMIZED; + case CONFLICT -> + net.firedevops.firemud.loggingadmin.v1.AccountAuditReceiptStatus + .ACCOUNT_AUDIT_RECEIPT_STATUS_CONFLICT; + }; + } + + private static net.firedevops.firemud.loggingadmin.v1.AccountAuditReceiptOutcome toProtoOutcome( + AccountAuditReceiptOutcome outcome) { + return switch (outcome) { + case ACCEPTED -> + net.firedevops.firemud.loggingadmin.v1.AccountAuditReceiptOutcome + .ACCOUNT_AUDIT_RECEIPT_OUTCOME_ACCEPTED; + case DUPLICATE -> + net.firedevops.firemud.loggingadmin.v1.AccountAuditReceiptOutcome + .ACCOUNT_AUDIT_RECEIPT_OUTCOME_DUPLICATE; + case NON_REPLAYABLE -> + net.firedevops.firemud.loggingadmin.v1.AccountAuditReceiptOutcome + .ACCOUNT_AUDIT_RECEIPT_OUTCOME_NON_REPLAYABLE; + case IDEMPOTENCY_CONFLICT -> + net.firedevops.firemud.loggingadmin.v1.AccountAuditReceiptOutcome + .ACCOUNT_AUDIT_RECEIPT_OUTCOME_IDEMPOTENCY_CONFLICT; + }; + } + @Override @Timed(value = "loggingadminGrpc.applyModerationAction") public void applyModerationAction( @@ -318,4 +536,19 @@ private static void requireAllowlistedInternalService( methodName + " requires an allowlisted internal service caller"); } } + + private void requireAccountAuditCaller(String methodName) { + Set allowedServices = ACCOUNT_AUDIT_CALLER_ALLOWLIST.get(methodName); + GrpcPeerIdentity peerIdentity = GrpcPeerIdentity.current(); + if (allowedServices == null + || peerIdentity == null + || !allowedServices.contains(peerIdentity.service()) + || workloadNamespace == null + || workloadNamespace.isBlank() + || !("spiffe://firemud/ns/" + workloadNamespace + "/sa/" + ACCOUNT_SERVICE) + .equals(peerIdentity.uri())) { + throw new AdminAuthorizationException( + methodName + " requires an allowlisted account-service mTLS peer"); + } + } } diff --git a/services/logging-admin-service/src/main/resources/db/migration/V1004__account_audit_receipts.sql b/services/logging-admin-service/src/main/resources/db/migration/V1004__account_audit_receipts.sql new file mode 100644 index 0000000000..4e1a61f25a --- /dev/null +++ b/services/logging-admin-service/src/main/resources/db/migration/V1004__account_audit_receipts.sql @@ -0,0 +1,47 @@ +CREATE TABLE account_audit_receipts ( + id BIGSERIAL PRIMARY KEY, + receipt_id UUID NOT NULL UNIQUE, + scope VARCHAR(16) NOT NULL, + tenant_id BIGINT, + tenant_key BIGINT NOT NULL, + audit_event_id VARCHAR(36) NOT NULL, + producer_service TEXT NOT NULL, + event_type TEXT NOT NULL, + occurred_at_seconds BIGINT NOT NULL, + occurred_at_nanos INTEGER NOT NULL, + schema_version INTEGER NOT NULL, + payload_digest_version INTEGER NOT NULL, + payload_digest TEXT NOT NULL, + payload BYTEA, + status VARCHAR(16) NOT NULL, + outcome VARCHAR(32) NOT NULL, + created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT chk_account_audit_receipt_scope + CHECK ( + (scope = 'platform' AND tenant_id IS NULL AND tenant_key = 0) + OR ( + scope = 'tenant' + AND tenant_id IS NOT NULL + AND tenant_id > 0 + AND tenant_key = tenant_id + ) + ), + CONSTRAINT chk_account_audit_receipt_occurred_at_nanos + CHECK (occurred_at_nanos BETWEEN 0 AND 999999999), + CONSTRAINT chk_account_audit_receipt_versions + CHECK (schema_version > 0 AND payload_digest_version = 1), + CONSTRAINT chk_account_audit_receipt_digest + CHECK (payload_digest LIKE 'sha256:%' AND length(payload_digest) = 71), + CONSTRAINT chk_account_audit_receipt_terminal_state + CHECK ( + (status = 'COMMITTED' AND outcome IN ('ACCEPTED', 'DUPLICATE') AND payload IS NOT NULL) + OR (status = 'MINIMIZED' AND outcome = 'NON_REPLAYABLE' AND payload IS NULL) + ) +); + +CREATE UNIQUE INDEX uq_account_audit_receipt_identity + ON account_audit_receipts (scope, tenant_key, audit_event_id); + +CREATE INDEX idx_account_audit_receipts_tenant_event + ON account_audit_receipts (tenant_id, audit_event_id) + WHERE scope = 'tenant'; diff --git a/services/logging-admin-service/src/main/resources/db/migration/V1005__account_audit_receipt_projection.sql b/services/logging-admin-service/src/main/resources/db/migration/V1005__account_audit_receipt_projection.sql new file mode 100644 index 0000000000..c0d9144b4e --- /dev/null +++ b/services/logging-admin-service/src/main/resources/db/migration/V1005__account_audit_receipt_projection.sql @@ -0,0 +1,68 @@ +ALTER TABLE log_events + ALTER COLUMN tenant_id DROP NOT NULL; + +ALTER TABLE log_events + ADD COLUMN scope VARCHAR(16) NOT NULL DEFAULT 'tenant', + ADD COLUMN audit_event_id VARCHAR(36), + ADD COLUMN tenant_key BIGINT NOT NULL DEFAULT 0; + +ALTER TABLE log_events + ADD CONSTRAINT chk_log_events_scope_tenant + CHECK ( + (scope = 'platform' AND tenant_id IS NULL AND tenant_key = 0) + OR ( + scope = 'tenant' + AND tenant_id IS NOT NULL + AND ( + (audit_event_id IS NOT NULL AND tenant_key = tenant_id) + OR (audit_event_id IS NULL AND tenant_key IN (0, tenant_id)) + ) + ) + ); + +CREATE UNIQUE INDEX uq_log_events_account_audit_identity + ON log_events (scope, tenant_key, audit_event_id); + +ALTER TABLE account_audit_receipts + ADD COLUMN log_event_id BIGINT; + +INSERT INTO log_events ( + scope, + tenant_id, + tenant_key, + audit_event_id, + type, + message, + timestamp, + account_id +) +SELECT receipt.scope, + receipt.tenant_id, + receipt.tenant_key, + receipt.audit_event_id, + 'ACCOUNT_AUDIT', + 'Account audit event ' || receipt.audit_event_id, + TIMESTAMP '1970-01-01 00:00:00' + + receipt.occurred_at_seconds * INTERVAL '1' SECOND + + (receipt.occurred_at_nanos / 1000) * INTERVAL '0.000001' SECOND, + NULL +FROM account_audit_receipts AS receipt; + +UPDATE account_audit_receipts AS receipt +SET log_event_id = ( + SELECT event.id + FROM log_events AS event + WHERE event.scope = receipt.scope + AND event.tenant_key = receipt.tenant_key + AND event.audit_event_id = receipt.audit_event_id +); + +ALTER TABLE account_audit_receipts + ALTER COLUMN log_event_id SET NOT NULL; + +ALTER TABLE account_audit_receipts + ADD CONSTRAINT uq_account_audit_receipts_log_event_id UNIQUE (log_event_id); + +ALTER TABLE account_audit_receipts + ADD CONSTRAINT fk_account_audit_receipts_log_event_id + FOREIGN KEY (log_event_id) REFERENCES log_events (id); diff --git a/services/logging-admin-service/src/main/resources/db/migration/V1006__enforce_account_audit_receipt_digest_format.sql b/services/logging-admin-service/src/main/resources/db/migration/V1006__enforce_account_audit_receipt_digest_format.sql new file mode 100644 index 0000000000..7879511c4a --- /dev/null +++ b/services/logging-admin-service/src/main/resources/db/migration/V1006__enforce_account_audit_receipt_digest_format.sql @@ -0,0 +1,5 @@ +-- PostgreSQL enforces this check on new or updated rows without scanning retained rows. +-- jOOQ excludes only PostgreSQL's NOT VALID flag and retains the check expression. +ALTER TABLE account_audit_receipts + ADD CONSTRAINT chk_account_audit_receipt_digest_format + CHECK (payload_digest ~ '^sha256:[0-9a-f]{64}$') /* [jooq ignore start] */ NOT VALID /* [jooq ignore stop] */; diff --git a/services/logging-admin-service/src/main/resources/db/migration/V1007__enforce_account_audit_projection_tenant.sql b/services/logging-admin-service/src/main/resources/db/migration/V1007__enforce_account_audit_projection_tenant.sql new file mode 100644 index 0000000000..9817fb8fb4 --- /dev/null +++ b/services/logging-admin-service/src/main/resources/db/migration/V1007__enforce_account_audit_projection_tenant.sql @@ -0,0 +1,5 @@ +-- PostgreSQL enforces this check for new or updated rows without scanning retained rows. +-- jOOQ excludes only PostgreSQL's NOT VALID flag and retains the check expression. +ALTER TABLE log_events + ADD CONSTRAINT chk_log_events_tenant_audit_positive_tenant_id + CHECK (scope <> 'tenant' OR audit_event_id IS NULL OR tenant_id > 0) /* [jooq ignore start] */ NOT VALID /* [jooq ignore stop] */; diff --git a/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/LoggingAdminApplicationIntegrationTest.java b/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/LoggingAdminApplicationIntegrationTest.java index fb290e412e..75cb52b632 100644 --- a/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/LoggingAdminApplicationIntegrationTest.java +++ b/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/LoggingAdminApplicationIntegrationTest.java @@ -1,25 +1,58 @@ package net.firedevops.firemud.loggingadmin; +import static net.firedevops.firemud.loggingadmin.jooq.tables.AccountAuditReceipts.ACCOUNT_AUDIT_RECEIPTS; +import static net.firedevops.firemud.loggingadmin.jooq.tables.LogEvents.LOG_EVENTS; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import com.google.protobuf.ByteString; import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; import java.time.Duration; +import java.time.Instant; +import java.time.LocalDateTime; +import java.util.HexFormat; +import java.util.List; import java.util.Map; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import javax.sql.DataSource; import net.firedevops.firemud.common.security.JwtUtil; import net.firedevops.firemud.loggingadmin.client.AccountClient; import net.firedevops.firemud.loggingadmin.client.GameSessionClient; import net.firedevops.firemud.loggingadmin.client.GameSessionControlPlaneClient; +import net.firedevops.firemud.loggingadmin.dto.AccountAuditReceiptDto; +import net.firedevops.firemud.loggingadmin.dto.AccountAuditReceiptOutcome; +import net.firedevops.firemud.loggingadmin.dto.AccountAuditReceiptStatus; +import net.firedevops.firemud.loggingadmin.dto.AccountAuditScope; +import net.firedevops.firemud.loggingadmin.dto.CreateLogEventRequest; +import net.firedevops.firemud.loggingadmin.dto.QueryLogsRequest; +import net.firedevops.firemud.loggingadmin.jooq.tables.records.AccountAuditReceiptsRecord; +import net.firedevops.firemud.loggingadmin.jooq.tables.records.LogEventsRecord; +import net.firedevops.firemud.loggingadmin.service.AuditStorageUnavailableException; +import net.firedevops.firemud.loggingadmin.service.LogEventService; +import net.firedevops.firemud.loggingadmin.service.LogQueryService; import net.firedevops.firemud.test.GatewayTestProperties; import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.MigrationVersion; +import org.jooq.DSLContext; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.boot.test.web.server.LocalServerPort; +import org.springframework.dao.DataIntegrityViolationException; import org.springframework.http.HttpHeaders; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.test.context.DynamicPropertyRegistry; @@ -75,6 +108,873 @@ static void configure(DynamicPropertyRegistry registry) { @MockitoBean private GameSessionClient gameSessionClient; @MockitoBean private GameSessionControlPlaneClient gameSessionControlPlaneClient; + @Autowired private DSLContext dsl; + @Autowired private DataSource dataSource; + @Autowired private LogEventService logEventService; + @Autowired private LogQueryService logQueryService; + + @Test + void accountAuditReceiptAndProjectionShareStableIdentityAcrossRetryAndConflict() { + String eventId = "82a6f475-0baa-4fd0-a86b-580f286a9940"; + String payload = "{\"accountId\":91,\"auditMarker\":\"tenant-retry-proof\"}"; + CreateLogEventRequest request = tenantAuditRequest(eventId, payload); + + var accepted = logEventService.createLogEvent(request); + var duplicate = logEventService.createLogEvent(request); + var conflict = + logEventService.createLogEvent(tenantAuditRequest(eventId, "{\"changed\":true}")); + + assertThat(accepted.status()).isEqualTo(AccountAuditReceiptStatus.COMMITTED); + assertThat(accepted.outcome()).isEqualTo(AccountAuditReceiptOutcome.ACCEPTED); + assertThat(duplicate.outcome()).isEqualTo(AccountAuditReceiptOutcome.DUPLICATE); + assertThat(duplicate.receiptId()).isEqualTo(accepted.receiptId()); + assertThat(duplicate.logEventId()).isEqualTo(accepted.logEventId()); + assertThat(conflict.status()).isEqualTo(AccountAuditReceiptStatus.CONFLICT); + assertThat(conflict.outcome()).isEqualTo(AccountAuditReceiptOutcome.IDEMPOTENCY_CONFLICT); + assertThat(conflict.logEventId()).isEqualTo(accepted.logEventId()); + + LogEventsRecord projection = + dsl.selectFrom(LOG_EVENTS).where(LOG_EVENTS.ID.eq(accepted.logEventId())).fetchOne(); + AccountAuditReceiptsRecord receipt = + dsl.selectFrom(ACCOUNT_AUDIT_RECEIPTS) + .where(ACCOUNT_AUDIT_RECEIPTS.AUDIT_EVENT_ID.eq(eventId)) + .fetchOne(); + assertThat(projection).isNotNull(); + assertThat(projection.getScope()).isEqualTo("tenant"); + assertThat(projection.getTenantId()).isEqualTo(42L); + assertThat(projection.getAuditEventId()).isEqualTo(eventId); + assertThat(projection.getType()).isEqualTo("ACCOUNT_AUDIT"); + assertThat(projection.getMessage()).isEqualTo("Account audit event " + eventId); + assertThat(projection.getMessage()).doesNotContain("accountId", "tenant-retry-proof"); + assertThat(receipt).isNotNull(); + assertThat(receipt.getLogEventId()).isEqualTo(projection.getId()); + assertThat(receipt.getPayload()).isEqualTo(payload.getBytes(StandardCharsets.UTF_8)); + assertThat(dsl.fetchCount(LOG_EVENTS, LOG_EVENTS.AUDIT_EVENT_ID.eq(eventId))).isOne(); + assertThat( + dsl.fetchCount( + ACCOUNT_AUDIT_RECEIPTS, ACCOUNT_AUDIT_RECEIPTS.AUDIT_EVENT_ID.eq(eventId))) + .isOne(); + assertThat(logQueryService.queryLogs(new QueryLogsRequest(42L, eventId))) + .containsExactly("Account audit event " + eventId); + } + + @Test + void auditEventIdHasDistinctPlatformAndTenantReceiptIdentities() { + String eventId = "9a25cba0-b6f3-40c2-82ec-4ffcad2f2081"; + String payload = "{\"accountId\":96,\"auditMarker\":\"scoped-identity-proof\"}"; + List requests = + List.of( + platformAuditRequest(eventId, payload), + auditRequest(AccountAuditScope.TENANT, 42L, eventId, payload), + auditRequest(AccountAuditScope.TENANT, 43L, eventId, payload)); + List accepted = + requests.stream().map(logEventService::createLogEvent).toList(); + + assertThat(accepted) + .extracting(AccountAuditReceiptDto::outcome) + .containsOnly(AccountAuditReceiptOutcome.ACCEPTED); + assertThat(accepted.stream().map(AccountAuditReceiptDto::receiptId).toList()) + .doesNotHaveDuplicates(); + assertThat(accepted.stream().map(AccountAuditReceiptDto::logEventId).toList()) + .doesNotHaveDuplicates(); + + for (int index = 0; index < requests.size(); index++) { + CreateLogEventRequest request = requests.get(index); + AccountAuditReceiptDto original = accepted.get(index); + + assertDuplicateOf(logEventService.createLogEvent(request), original); + assertDuplicateOf(logEventService.readLogEventReceipt(request), original); + + CreateLogEventRequest changedPayload = + auditRequest( + request.scope(), request.tenantId(), request.auditEventId(), "{\"changed\":true}"); + assertConflictWithOriginal(logEventService.createLogEvent(changedPayload), original); + + CreateLogEventRequest changedMetadata = + withOccurredAt(request, request.occurredAt().plusSeconds(1)); + assertConflictWithOriginal(logEventService.createLogEvent(changedMetadata), original); + + LogEventsRecord projection = + dsl.selectFrom(LOG_EVENTS).where(LOG_EVENTS.ID.eq(original.logEventId())).fetchOne(); + AccountAuditReceiptsRecord receipt = + dsl.selectFrom(ACCOUNT_AUDIT_RECEIPTS) + .where(ACCOUNT_AUDIT_RECEIPTS.RECEIPT_ID.eq(UUID.fromString(original.receiptId()))) + .fetchOne(); + assertThat(projection).isNotNull(); + assertThat(projection.getScope()).isEqualTo(request.scope().databaseValue()); + assertThat(projection.getTenantId()).isEqualTo(request.tenantId()); + assertThat(projection.getAuditEventId()).isEqualTo(eventId); + assertThat(receipt).isNotNull(); + assertThat(receipt.getScope()).isEqualTo(request.scope().databaseValue()); + assertThat(receipt.getTenantId()).isEqualTo(request.tenantId()); + assertThat(receipt.getLogEventId()).isEqualTo(original.logEventId()); + } + + assertThat(dsl.fetchCount(LOG_EVENTS, LOG_EVENTS.AUDIT_EVENT_ID.eq(eventId))).isEqualTo(3); + assertThat( + dsl.fetchCount( + ACCOUNT_AUDIT_RECEIPTS, ACCOUNT_AUDIT_RECEIPTS.AUDIT_EVENT_ID.eq(eventId))) + .isEqualTo(3); + assertThat(logQueryService.queryLogs(new QueryLogsRequest(42L, eventId))) + .containsExactly("Account audit event " + eventId); + assertThat(logQueryService.queryLogs(new QueryLogsRequest(43L, eventId))) + .containsExactly("Account audit event " + eventId); + assertThat(logQueryService.queryLogs(new QueryLogsRequest(44L, eventId))).isEmpty(); + } + + @Test + void platformAuditProjectionHasNoTenantAndIsExcludedFromTenantQuery() { + String eventId = "41613d4b-3e66-4c9a-9f1c-7e02f54d0c34"; + String marker = "platform-only-marker"; + String payload = "{\"accountId\":92,\"auditMarker\":\"" + marker + "\"}"; + CreateLogEventRequest request = platformAuditRequest(eventId, payload); + + var accepted = logEventService.createLogEvent(request); + + LogEventsRecord projection = + dsl.selectFrom(LOG_EVENTS).where(LOG_EVENTS.ID.eq(accepted.logEventId())).fetchOne(); + assertThat(projection).isNotNull(); + assertThat(projection.getScope()).isEqualTo("platform"); + assertThat(projection.getTenantId()).isNull(); + assertThat(projection.getAuditEventId()).isEqualTo(eventId); + assertThat(projection.getMessage()).isEqualTo("Account audit event " + eventId); + assertThat(projection.getMessage()).doesNotContain(marker); + assertThat(logQueryService.queryLogs(new QueryLogsRequest(42L, eventId))).isEmpty(); + } + + @Test + void receiptFailureRollsBackTheAlreadyInsertedAuditProjection() { + String eventId = "f15e1f7a-f2ee-4f90-b83d-77695bcac86c"; + dsl.execute( + "CREATE OR REPLACE FUNCTION fail_test_account_audit_receipt() RETURNS trigger " + + "LANGUAGE plpgsql AS $$ BEGIN IF NEW.audit_event_id = '" + + eventId + + "' THEN RAISE EXCEPTION 'injected receipt insert failure'; END IF; RETURN NEW; END $$"); + dsl.execute( + "CREATE TRIGGER fail_test_account_audit_receipt BEFORE INSERT ON account_audit_receipts " + + "FOR EACH ROW EXECUTE FUNCTION fail_test_account_audit_receipt()"); + try { + assertThatThrownBy( + () -> + logEventService.createLogEvent(tenantAuditRequest(eventId, "{\"accountId\":93}"))) + .isInstanceOf(AuditStorageUnavailableException.class); + assertThat(dsl.fetchCount(LOG_EVENTS, LOG_EVENTS.AUDIT_EVENT_ID.eq(eventId))).isZero(); + assertThat( + dsl.fetchCount( + ACCOUNT_AUDIT_RECEIPTS, ACCOUNT_AUDIT_RECEIPTS.AUDIT_EVENT_ID.eq(eventId))) + .isZero(); + } finally { + dsl.execute( + "DROP TRIGGER IF EXISTS fail_test_account_audit_receipt ON account_audit_receipts"); + dsl.execute("DROP FUNCTION IF EXISTS fail_test_account_audit_receipt()"); + } + } + + @Test + void concurrentExactRetriesCreateOneProjectionAndReturnTheSameIdentifiers() throws Exception { + String eventId = "4b7d9ee5-62f5-44dd-8b35-dcf6490d7404"; + CreateLogEventRequest request = tenantAuditRequest(eventId, "{\"accountId\":94}"); + CountDownLatch start = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future first = executor.submit(() -> createAfter(start, request)); + Future second = executor.submit(() -> createAfter(start, request)); + start.countDown(); + var firstResult = first.get(20, TimeUnit.SECONDS); + var secondResult = second.get(20, TimeUnit.SECONDS); + + assertThat(firstResult.logEventId()).isEqualTo(secondResult.logEventId()); + assertThat(firstResult.receiptId()).isEqualTo(secondResult.receiptId()); + assertThat(java.util.List.of(firstResult.outcome(), secondResult.outcome())) + .containsExactlyInAnyOrder( + AccountAuditReceiptOutcome.ACCEPTED, AccountAuditReceiptOutcome.DUPLICATE); + assertThat(dsl.fetchCount(LOG_EVENTS, LOG_EVENTS.AUDIT_EVENT_ID.eq(eventId))).isOne(); + assertThat( + dsl.fetchCount( + ACCOUNT_AUDIT_RECEIPTS, ACCOUNT_AUDIT_RECEIPTS.AUDIT_EVENT_ID.eq(eventId))) + .isOne(); + } finally { + executor.shutdownNow(); + } + } + + @Test + void forwardAuditMigrationsPreserveRetainedRowsAndEnforceReceiptAndProjectionChecks() { + String schema = "logging_admin_migration_" + UUID.randomUUID().toString().replace("-", ""); + UUID retainedInvalidReceiptId = UUID.fromString("30000000-0000-4000-8000-000000000002"); + String retainedInvalidDigest = "sha256:" + "g".repeat(64); + dsl.execute("CREATE SCHEMA " + schema); + try { + Flyway.configure() + .dataSource(dataSource) + .locations("classpath:db/migration") + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .target(MigrationVersion.fromVersion("1004")) + .load() + .migrate(); + + dsl.execute( + "INSERT INTO " + + schema + + ".log_events (tenant_id, type, message, timestamp, account_id) " + + "VALUES (?, ?, ?, ?, ?)", + 73L, + "PAYMENT", + "legacy payment log", + LocalDateTime.of(2025, 3, 1, 12, 0), + 12L); + seedPreProjectionReceipt( + schema, + UUID.fromString("30000000-0000-4000-8000-000000000001"), + "tenant", + 73L, + "10000000-0000-4000-8000-000000000001", + Instant.parse("2025-03-01T12:00:01.123456Z"), + false); + seedPreProjectionReceipt( + schema, + retainedInvalidReceiptId, + "tenant", + 73L, + "10000000-0000-4000-8000-000000000002", + Instant.parse("2025-03-01T12:00:02.987654Z"), + true); + seedPreProjectionReceipt( + schema, + UUID.fromString("40000000-0000-4000-8000-000000000001"), + "platform", + null, + "20000000-0000-4000-8000-000000000001", + Instant.parse("2025-03-01T12:00:03.123456Z"), + false); + seedPreProjectionReceipt( + schema, + UUID.fromString("40000000-0000-4000-8000-000000000002"), + "platform", + null, + "20000000-0000-4000-8000-000000000002", + Instant.parse("2025-03-01T12:00:04.987654Z"), + true); + + dsl.execute( + "UPDATE " + + schema + + ".account_audit_receipts SET payload_digest = ? WHERE receipt_id = ?", + retainedInvalidDigest, + retainedInvalidReceiptId); + assertThat( + dsl.fetchSingle( + "SELECT payload_digest FROM " + + schema + + ".account_audit_receipts WHERE receipt_id = ?", + retainedInvalidReceiptId) + .get(0, String.class)) + .isEqualTo(retainedInvalidDigest); + + Flyway.configure() + .dataSource(dataSource) + .locations("classpath:db/migration") + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .target(MigrationVersion.fromVersion("1005")) + .load() + .migrate(); + + dsl.execute( + "INSERT INTO " + + schema + + ".log_events (scope, tenant_id, tenant_key, audit_event_id, type, message, timestamp) " + + "VALUES ('tenant', 0, 0, '90000000-0000-4000-8000-000000000001', " + + "'ACCOUNT_AUDIT', 'retained zero tenant projection', TIMESTAMP '2025-03-01 15:00:00'), " + + "('tenant', -9, -9, '90000000-0000-4000-8000-000000000002', " + + "'ACCOUNT_AUDIT', 'retained negative tenant projection', TIMESTAMP '2025-03-01 15:00:01'), " + + "('tenant', 0, 0, NULL, 'PAYMENT', 'retained zero tenant legacy row', " + + "TIMESTAMP '2025-03-01 15:00:02'), " + + "('tenant', -9, 0, NULL, 'PAYMENT', 'retained negative tenant legacy row', " + + "TIMESTAMP '2025-03-01 15:00:03')"); + + Flyway.configure() + .dataSource(dataSource) + .locations("classpath:db/migration") + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .load() + .migrate(); + + assertThat( + dsl.fetchSingle( + "SELECT COUNT(*) FROM " + schema + ".log_events WHERE message = ?", + "legacy payment log") + .get(0, Integer.class)) + .isEqualTo(1); + assertThat( + dsl.fetchSingle( + "SELECT tenant_key FROM " + schema + ".log_events WHERE message = ?", + "legacy payment log") + .get(0, Long.class)) + .isEqualTo(0L); + assertThat( + dsl.fetch( + "SELECT tenant_id, tenant_key, audit_event_id, type, message, timestamp " + + "FROM " + + schema + + ".log_events WHERE message IN (?, ?, ?, ?) ORDER BY message", + "retained negative tenant legacy row", + "retained negative tenant projection", + "retained zero tenant legacy row", + "retained zero tenant projection")) + .extracting( + row -> + List.of( + row.get("tenant_id", Long.class), + row.get("tenant_key", Long.class), + row.get("audit_event_id", String.class) == null + ? "" + : row.get("audit_event_id", String.class), + row.get("type", String.class), + row.get("message", String.class), + row.get("timestamp", LocalDateTime.class))) + .containsExactly( + List.of( + -9L, + 0L, + "", + "PAYMENT", + "retained negative tenant legacy row", + LocalDateTime.of(2025, 3, 1, 15, 0, 3)), + List.of( + -9L, + -9L, + "90000000-0000-4000-8000-000000000002", + "ACCOUNT_AUDIT", + "retained negative tenant projection", + LocalDateTime.of(2025, 3, 1, 15, 0, 1)), + List.of( + 0L, + 0L, + "", + "PAYMENT", + "retained zero tenant legacy row", + LocalDateTime.of(2025, 3, 1, 15, 0, 2)), + List.of( + 0L, + 0L, + "90000000-0000-4000-8000-000000000001", + "ACCOUNT_AUDIT", + "retained zero tenant projection", + LocalDateTime.of(2025, 3, 1, 15, 0))); + assertThat( + dsl.fetchSingle("SELECT COUNT(*) FROM " + schema + ".account_audit_receipts") + .get(0, Integer.class)) + .isEqualTo(4); + assertThat( + dsl.fetchSingle( + "SELECT COUNT(*) FROM " + + schema + + ".account_audit_receipts AS receipt LEFT JOIN " + + schema + + ".log_events AS event ON event.id = receipt.log_event_id " + + "WHERE event.id IS NULL") + .get(0, Integer.class)) + .isEqualTo(0); + assertBackfilledReceipt( + schema, + "30000000-0000-4000-8000-000000000001", + "tenant", + 73L, + "10000000-0000-4000-8000-000000000001", + "COMMITTED", + "ACCEPTED", + digest("{\"retained\":true}".getBytes(StandardCharsets.UTF_8)), + "2025-03-01T12:00:01.123456"); + assertBackfilledReceipt( + schema, + "30000000-0000-4000-8000-000000000002", + "tenant", + 73L, + "10000000-0000-4000-8000-000000000002", + "MINIMIZED", + "NON_REPLAYABLE", + retainedInvalidDigest, + "2025-03-01T12:00:02.987654"); + assertBackfilledReceipt( + schema, + "40000000-0000-4000-8000-000000000001", + "platform", + null, + "20000000-0000-4000-8000-000000000001", + "COMMITTED", + "ACCEPTED", + digest("{\"retained\":true}".getBytes(StandardCharsets.UTF_8)), + "2025-03-01T12:00:03.123456"); + assertBackfilledReceipt( + schema, + "40000000-0000-4000-8000-000000000002", + "platform", + null, + "20000000-0000-4000-8000-000000000002", + "MINIMIZED", + "NON_REPLAYABLE", + digest("{\"retained\":true}".getBytes(StandardCharsets.UTF_8)), + "2025-03-01T12:00:04.987654"); + + assertThat( + dsl.fetchSingle( + "SELECT payload_digest FROM " + + schema + + ".account_audit_receipts WHERE receipt_id = ?", + retainedInvalidReceiptId) + .get(0, String.class)) + .isEqualTo(retainedInvalidDigest); + assertThat( + dsl.fetchSingle( + "SELECT convalidated FROM pg_constraint " + + "WHERE conrelid = to_regclass(?) AND conname = ?", + schema + ".account_audit_receipts", + "chk_account_audit_receipt_digest_format") + .get(0, Boolean.class)) + .isFalse(); + assertThat( + dsl.fetchSingle( + "SELECT convalidated FROM pg_constraint " + + "WHERE conrelid = to_regclass(?) AND conname = ?", + schema + ".log_events", + "chk_log_events_tenant_audit_positive_tenant_id") + .get(0, Boolean.class)) + .isFalse(); + + for (String invalidDigest : List.of("sha256:" + "A".repeat(64), "sha256:" + "g".repeat(64))) { + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE " + + schema + + ".account_audit_receipts SET payload_digest = ? " + + "WHERE receipt_id = ?", + invalidDigest, + retainedInvalidReceiptId)) + .isInstanceOf(DataIntegrityViolationException.class) + .hasMessageContaining("chk_account_audit_receipt_digest_format"); + } + assertThat( + dsl.fetchSingle( + "SELECT payload_digest FROM " + + schema + + ".account_audit_receipts WHERE receipt_id = ?", + retainedInvalidReceiptId) + .get(0, String.class)) + .isEqualTo(retainedInvalidDigest); + + byte[] validPayload = "{\"afterMigration\":true}".getBytes(StandardCharsets.UTF_8); + assertThatThrownBy( + () -> + insertMigrationReceipt( + schema, + UUID.fromString("80000000-0000-4000-8000-000000000001"), + "70000000-0000-4000-8000-000000000001", + "sha256:" + "A".repeat(64), + validPayload, + "COMMITTED", + "ACCEPTED")) + .isInstanceOf(DataIntegrityViolationException.class) + .hasMessageContaining("chk_account_audit_receipt_digest_format"); + assertThatThrownBy( + () -> + insertMigrationReceipt( + schema, + UUID.fromString("80000000-0000-4000-8000-000000000002"), + "70000000-0000-4000-8000-000000000002", + "sha256:" + "g".repeat(64), + validPayload, + "COMMITTED", + "ACCEPTED")) + .isInstanceOf(DataIntegrityViolationException.class) + .hasMessageContaining("chk_account_audit_receipt_digest_format"); + + insertMigrationReceipt( + schema, + UUID.fromString("80000000-0000-4000-8000-000000000003"), + "70000000-0000-4000-8000-000000000003", + digest(validPayload), + validPayload, + "COMMITTED", + "ACCEPTED"); + byte[] minimizedPayload = "retained digest evidence".getBytes(StandardCharsets.UTF_8); + insertMigrationReceipt( + schema, + UUID.fromString("80000000-0000-4000-8000-000000000004"), + "70000000-0000-4000-8000-000000000004", + digest(minimizedPayload), + null, + "MINIMIZED", + "NON_REPLAYABLE"); + assertThat( + dsl.fetchSingle( + "SELECT status FROM " + + schema + + ".account_audit_receipts WHERE receipt_id = ?", + UUID.fromString("80000000-0000-4000-8000-000000000003")) + .get(0, String.class)) + .isEqualTo("COMMITTED"); + var minimizedReceipt = + dsl.fetchSingle( + "SELECT status, outcome, payload IS NULL AS payload_is_null FROM " + + schema + + ".account_audit_receipts WHERE receipt_id = ?", + UUID.fromString("80000000-0000-4000-8000-000000000004")); + assertThat(minimizedReceipt.get("status", String.class)).isEqualTo("MINIMIZED"); + assertThat(minimizedReceipt.get("outcome", String.class)).isEqualTo("NON_REPLAYABLE"); + assertThat(minimizedReceipt.get("payload_is_null", Boolean.class)).isTrue(); + + dsl.execute( + "INSERT INTO " + + schema + + ".log_events (tenant_id, type, message, timestamp) VALUES (?, ?, ?, ?)", + 84L, + "PAYMENT", + "legacy insert", + LocalDateTime.of(2025, 3, 1, 13, 0)); + Long legacyLogId = + dsl.fetchSingle( + "SELECT id FROM " + schema + ".log_events WHERE message = ?", "legacy insert") + .get("id", Long.class); + assertThat( + dsl.fetchSingle( + "SELECT tenant_key FROM " + schema + ".log_events WHERE id = ?", legacyLogId) + .get(0, Long.class)) + .isEqualTo(0L); + + dsl.execute( + "UPDATE " + schema + ".log_events SET tenant_id = ? WHERE id = ?", 85L, legacyLogId); + assertThat( + dsl.fetchSingle( + "SELECT tenant_key FROM " + schema + ".log_events WHERE id = ?", legacyLogId) + .get(0, Long.class)) + .isEqualTo(0L); + + dsl.execute( + "INSERT INTO " + + schema + + ".log_events (scope, tenant_id, tenant_key, audit_event_id, type, message) " + + "VALUES (?, ?, ?, ?, ?, ?)", + "tenant", + 86L, + 86L, + "60000000-0000-4000-8000-000000000001", + "ACCOUNT_AUDIT", + "Account audit event 60000000-0000-4000-8000-000000000001"); + assertThat( + dsl.fetchSingle( + "SELECT tenant_key FROM " + schema + ".log_events WHERE audit_event_id = ?", + "60000000-0000-4000-8000-000000000001") + .get(0, Long.class)) + .isEqualTo(86L); + + dsl.execute( + "INSERT INTO " + + schema + + ".log_events (scope, tenant_id, tenant_key, audit_event_id, type, message) " + + "VALUES ('platform', NULL, 0, '60000000-0000-4000-8000-000000000002', " + + "'ACCOUNT_AUDIT', 'Account audit event 60000000-0000-4000-8000-000000000002')"); + assertThat( + dsl.fetchSingle( + "SELECT tenant_id, tenant_key FROM " + + schema + + ".log_events WHERE audit_event_id = ?", + "60000000-0000-4000-8000-000000000002") + .intoArray()) + .containsExactly(null, 0L); + + for (long invalidTenantId : List.of(0L, -9L)) { + String eventId = + invalidTenantId == 0 + ? "60000000-0000-4000-8000-000000000003" + : "60000000-0000-4000-8000-000000000004"; + assertThatThrownBy( + () -> + dsl.execute( + "INSERT INTO " + + schema + + ".log_events (scope, tenant_id, tenant_key, audit_event_id, type, message) " + + "VALUES ('tenant', ?, ?, ?, 'ACCOUNT_AUDIT', 'invalid tenant projection')", + invalidTenantId, + invalidTenantId, + eventId)) + .isInstanceOf(DataIntegrityViolationException.class) + .hasMessageContaining("chk_log_events_tenant_audit_positive_tenant_id"); + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE " + + schema + + ".log_events SET tenant_id = ?, tenant_key = ? " + + "WHERE audit_event_id = ?", + invalidTenantId, + invalidTenantId, + "60000000-0000-4000-8000-000000000001")) + .isInstanceOf(DataIntegrityViolationException.class) + .hasMessageContaining("chk_log_events_tenant_audit_positive_tenant_id"); + } + assertThat( + dsl.fetchSingle( + "SELECT tenant_id, tenant_key FROM " + + schema + + ".log_events WHERE audit_event_id = ?", + "60000000-0000-4000-8000-000000000001") + .intoArray()) + .containsExactly(86L, 86L); + + for (long legacyTenantId : List.of(0L, -9L)) { + dsl.execute( + "INSERT INTO " + + schema + + ".log_events (scope, tenant_id, tenant_key, type, message) " + + "VALUES ('tenant', ?, 0, 'PAYMENT', 'new non-audit legacy row')", + legacyTenantId); + } + + assertThatThrownBy( + () -> + dsl.execute( + "INSERT INTO " + + schema + + ".log_events (scope, tenant_id, tenant_key, audit_event_id, type, message) " + + "VALUES ('tenant', 73, 74, '50000000-0000-4000-8000-000000000001', " + + "'ACCOUNT_AUDIT', 'mismatched key')")) + .isInstanceOf(DataIntegrityViolationException.class) + .hasMessageContaining("chk_log_events_scope_tenant"); + } finally { + dsl.execute("DROP SCHEMA " + schema + " CASCADE"); + } + } + + private void insertMigrationReceipt( + String schema, + UUID receiptId, + String eventId, + String payloadDigest, + byte[] payload, + String status, + String outcome) { + Instant occurredAt = Instant.parse("2025-03-01T14:00:00.123456Z"); + dsl.execute( + "WITH projection AS (" + + "INSERT INTO " + + schema + + ".log_events (scope, tenant_id, tenant_key, audit_event_id, type, message, timestamp) " + + "VALUES (?, ?, ?, ?, ?, ?, ?) RETURNING id) " + + "INSERT INTO " + + schema + + ".account_audit_receipts (receipt_id, scope, tenant_id, tenant_key, audit_event_id, " + + "producer_service, event_type, occurred_at_seconds, occurred_at_nanos, schema_version, " + + "payload_digest_version, payload_digest, payload, status, outcome, log_event_id) " + + "SELECT ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, CAST(? AS BYTEA), ?, ?, projection.id " + + "FROM projection", + "tenant", + 73L, + 73L, + eventId, + "ACCOUNT_AUDIT", + "Account audit event " + eventId, + LocalDateTime.of(2025, 3, 1, 14, 0, 0, 123456000), + receiptId, + "tenant", + 73L, + 73L, + eventId, + "account-service", + "ACCOUNT_REGISTRATION", + occurredAt.getEpochSecond(), + occurredAt.getNano(), + 1, + 1, + payloadDigest, + payload, + status, + outcome); + } + + private void seedPreProjectionReceipt( + String schema, + UUID receiptId, + String scope, + Long tenantId, + String eventId, + Instant occurredAt, + boolean minimized) { + byte[] originalPayload = "{\"retained\":true}".getBytes(StandardCharsets.UTF_8); + long tenantKey = tenantId == null ? 0L : tenantId.longValue(); + dsl.execute( + "INSERT INTO " + + schema + + ".account_audit_receipts (receipt_id, scope, tenant_id, tenant_key, audit_event_id, " + + "producer_service, event_type, occurred_at_seconds, occurred_at_nanos, schema_version, " + + "payload_digest_version, payload_digest, payload, status, outcome) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + receiptId, + scope, + tenantId, + tenantKey, + eventId, + "account-service", + "ACCOUNT_REGISTRATION", + occurredAt.getEpochSecond(), + occurredAt.getNano(), + 1, + 1, + digest(originalPayload), + minimized ? null : originalPayload, + minimized ? "MINIMIZED" : "COMMITTED", + minimized ? "NON_REPLAYABLE" : "ACCEPTED"); + } + + private void assertBackfilledReceipt( + String schema, + String receiptId, + String scope, + Long tenantId, + String eventId, + String status, + String outcome, + String expectedPayloadDigest, + String timestamp) { + var receipt = + dsl.fetchOne( + "SELECT receipt.scope, receipt.tenant_id, receipt.tenant_key, receipt.audit_event_id, " + + "receipt.receipt_id, receipt.producer_service, receipt.event_type, " + + "receipt.occurred_at_seconds, receipt.occurred_at_nanos, receipt.schema_version, " + + "receipt.payload_digest_version, receipt.payload, receipt.payload_digest, " + + "receipt.status, receipt.outcome, receipt.log_event_id, event.id AS projection_id, " + + "event.type, event.message, event.timestamp, event.account_id FROM " + + schema + + ".account_audit_receipts AS receipt JOIN " + + schema + + ".log_events AS event ON event.id = receipt.log_event_id " + + "WHERE receipt.audit_event_id = ?", + eventId); + assertThat(receipt).isNotNull(); + assertThat(receipt.get("scope", String.class)).isEqualTo(scope); + assertThat(receipt.get("tenant_id", Long.class)).isEqualTo(tenantId); + assertThat(receipt.get("tenant_key", Long.class)).isEqualTo(tenantId == null ? 0L : tenantId); + assertThat(receipt.get("audit_event_id", String.class)).isEqualTo(eventId); + assertThat(receipt.get("receipt_id", UUID.class)).isEqualTo(UUID.fromString(receiptId)); + assertThat(receipt.get("producer_service", String.class)).isEqualTo("account-service"); + assertThat(receipt.get("event_type", String.class)).isEqualTo("ACCOUNT_REGISTRATION"); + Instant occurredAt = Instant.parse(timestamp + "Z"); + assertThat(receipt.get("occurred_at_seconds", Long.class)) + .isEqualTo(occurredAt.getEpochSecond()); + assertThat(receipt.get("occurred_at_nanos", Integer.class)).isEqualTo(occurredAt.getNano()); + assertThat(receipt.get("schema_version", Integer.class)).isEqualTo(1); + assertThat(receipt.get("payload_digest_version", Integer.class)).isEqualTo(1); + assertThat(receipt.get("payload_digest", String.class)).isEqualTo(expectedPayloadDigest); + assertThat(receipt.get("status", String.class)).isEqualTo(status); + assertThat(receipt.get("outcome", String.class)).isEqualTo(outcome); + assertThat(receipt.get("log_event_id", Long.class)) + .isEqualTo(receipt.get("projection_id", Long.class)); + assertThat(receipt.get("type", String.class)).isEqualTo("ACCOUNT_AUDIT"); + assertThat(receipt.get("message", String.class)).isEqualTo("Account audit event " + eventId); + assertThat(receipt.get("message", String.class)).doesNotContain("retained"); + assertThat(receipt.get("timestamp", LocalDateTime.class)) + .isEqualTo(LocalDateTime.parse(timestamp)); + assertThat(receipt.get("account_id", Long.class)).isNull(); + assertThat( + dsl.fetchSingle( + "SELECT COUNT(*) FROM " + schema + ".log_events WHERE audit_event_id = ?", + eventId) + .get(0, Integer.class)) + .isEqualTo(1); + if ("MINIMIZED".equals(status)) { + assertThat(receipt.get("payload", byte[].class)).isNull(); + } else { + assertThat(receipt.get("payload", byte[].class)) + .isEqualTo("{\"retained\":true}".getBytes(StandardCharsets.UTF_8)); + } + } + + private AccountAuditReceiptDto createAfter(CountDownLatch start, CreateLogEventRequest request) { + try { + if (!start.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("Concurrent audit test did not start"); + } + return logEventService.createLogEvent(request); + } catch (InterruptedException ex) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("Concurrent audit test was interrupted", ex); + } + } + + private static CreateLogEventRequest tenantAuditRequest(String eventId, String payload) { + return auditRequest(AccountAuditScope.TENANT, 42L, eventId, payload); + } + + private static CreateLogEventRequest platformAuditRequest(String eventId, String payload) { + return auditRequest(AccountAuditScope.PLATFORM, null, eventId, payload); + } + + private static CreateLogEventRequest auditRequest( + AccountAuditScope scope, Long tenantId, String eventId, String payload) { + return auditRequest(scope, tenantId, eventId, payload, Instant.parse("2026-09-24T00:00:00Z")); + } + + private static CreateLogEventRequest auditRequest( + AccountAuditScope scope, Long tenantId, String eventId, String payload, Instant occurredAt) { + ByteString payloadBytes = ByteString.copyFrom(payload, StandardCharsets.UTF_8); + return new CreateLogEventRequest( + scope, + tenantId, + eventId, + "account-service", + "ACCOUNT_AUDIT_INTEGRATION_TEST", + occurredAt, + 1, + payloadBytes, + 1, + digest(payloadBytes.toByteArray())); + } + + private static CreateLogEventRequest withOccurredAt( + CreateLogEventRequest request, Instant occurredAt) { + return auditRequest( + request.scope(), + request.tenantId(), + request.auditEventId(), + new String(request.payload().toByteArray(), StandardCharsets.UTF_8), + occurredAt); + } + + private static void assertDuplicateOf( + AccountAuditReceiptDto actual, AccountAuditReceiptDto expected) { + assertThat(actual.status()).isEqualTo(AccountAuditReceiptStatus.COMMITTED); + assertThat(actual.outcome()).isEqualTo(AccountAuditReceiptOutcome.DUPLICATE); + assertThat(actual.receiptId()).isEqualTo(expected.receiptId()); + assertThat(actual.logEventId()).isEqualTo(expected.logEventId()); + assertThat(actual.scope()).isEqualTo(expected.scope()); + assertThat(actual.tenantId()).isEqualTo(expected.tenantId()); + } + + private static void assertConflictWithOriginal( + AccountAuditReceiptDto actual, AccountAuditReceiptDto expected) { + assertThat(actual.status()).isEqualTo(AccountAuditReceiptStatus.CONFLICT); + assertThat(actual.outcome()).isEqualTo(AccountAuditReceiptOutcome.IDEMPOTENCY_CONFLICT); + assertThat(actual.receiptId()).isEqualTo(expected.receiptId()); + assertThat(actual.logEventId()).isEqualTo(expected.logEventId()); + assertThat(actual.scope()).isEqualTo(expected.scope()); + assertThat(actual.tenantId()).isEqualTo(expected.tenantId()); + } + + private static String digest(byte[] payload) { + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(payload)); + } catch (NoSuchAlgorithmException ex) { + throw new IllegalStateException("SHA-256 is unavailable", ex); + } + } + @Test void pingEndpointReturnsPong() throws Exception { String token = diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/repository/AccountAuditReceiptRepositoryTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/repository/AccountAuditReceiptRepositoryTest.java new file mode 100644 index 0000000000..bd54f49845 --- /dev/null +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/repository/AccountAuditReceiptRepositoryTest.java @@ -0,0 +1,136 @@ +package net.firedevops.firemud.loggingadmin.repository; + +import static net.firedevops.firemud.loggingadmin.jooq.tables.AccountAuditReceipts.ACCOUNT_AUDIT_RECEIPTS; +import static net.firedevops.firemud.loggingadmin.jooq.tables.LogEvents.LOG_EVENTS; +import static org.assertj.core.api.Assertions.assertThat; + +import com.google.protobuf.ByteString; +import java.nio.charset.StandardCharsets; +import java.sql.SQLException; +import java.time.Instant; +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; +import java.util.UUID; +import net.firedevops.firemud.loggingadmin.dto.AccountAuditScope; +import net.firedevops.firemud.loggingadmin.dto.CreateLogEventRequest; +import net.firedevops.firemud.loggingadmin.entity.AccountAuditReceiptInsertResult; +import net.firedevops.firemud.loggingadmin.jooq.tables.records.AccountAuditReceiptsRecord; +import org.jooq.DSLContext; +import org.jooq.Record1; +import org.jooq.Result; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.jooq.tools.jdbc.MockConnection; +import org.jooq.tools.jdbc.MockDataProvider; +import org.jooq.tools.jdbc.MockResult; +import org.junit.jupiter.api.Test; + +class AccountAuditReceiptRepositoryTest { + private static final String AUDIT_EVENT_ID = "audit-event-1"; + private static final UUID RECEIPT_ID = UUID.fromString("4829d25a-a6d1-4a43-b82b-3e82d538ad16"); + private static final long LOG_EVENT_ID = 91L; + + @Test + void projectionLookupUsesScopeTenantKeyAndExactEventIdentity() { + assertProjectionLookup(AccountAuditScope.PLATFORM, null, 0L); + assertProjectionLookup(AccountAuditScope.TENANT, 73L, 73L); + } + + private static void assertProjectionLookup( + AccountAuditScope scope, Long tenantId, long expectedTenantKey) { + DSLContext resultDsl = DSL.using(SQLDialect.POSTGRES); + List executedSql = new ArrayList<>(); + List projectionInsertBindings = new ArrayList<>(); + List projectionLookupBindings = new ArrayList<>(); + MockDataProvider provider = + context -> { + String sql = context.sql().trim().toLowerCase(Locale.ROOT); + executedSql.add(sql); + if (sql.startsWith("insert") && sql.contains("log_events")) { + projectionInsertBindings.add(context.bindings()); + return new MockResult[] {new MockResult(1)}; + } + if (sql.startsWith("select") && sql.contains("log_events")) { + projectionLookupBindings.add(context.bindings()); + Record1 row = resultDsl.newRecord(LOG_EVENTS.ID); + row.set(LOG_EVENTS.ID, LOG_EVENT_ID); + Result> result = resultDsl.newResult(LOG_EVENTS.ID); + result.add(row); + return new MockResult[] {new MockResult(1, result)}; + } + if (sql.startsWith("insert") && sql.contains("account_audit_receipts")) { + return new MockResult[] {new MockResult(1)}; + } + if (sql.startsWith("select") && sql.contains("account_audit_receipts")) { + AccountAuditReceiptsRecord row = receiptRecord(resultDsl, scope, tenantId); + Result result = resultDsl.newResult(ACCOUNT_AUDIT_RECEIPTS); + result.add(row); + return new MockResult[] {new MockResult(1, result)}; + } + throw new SQLException("Unexpected Account audit receipt query: " + sql); + }; + + DSLContext dsl = DSL.using(new MockConnection(provider), SQLDialect.POSTGRES); + AccountAuditReceiptInsertResult inserted = + new AccountAuditReceiptRepository(dsl).insertIfAbsent(request(scope, tenantId), RECEIPT_ID); + + assertThat(executedSql).hasSize(4); + assertThat(executedSql.get(0)).startsWith("insert").contains("log_events"); + assertThat(executedSql.get(1)).startsWith("select").contains("log_events"); + assertThat(executedSql.get(2)).startsWith("insert").contains("account_audit_receipts"); + assertThat(executedSql.get(3)).startsWith("select").contains("account_audit_receipts"); + assertThat(projectionInsertBindings).hasSize(1); + assertThat(projectionInsertBindings.get(0)).contains(expectedTenantKey, AUDIT_EVENT_ID); + + String lookupSql = executedSql.get(1); + assertThat(lookupSql) + .contains("scope", "tenant_key", "audit_event_id") + .doesNotContain("tenant_id"); + assertThat(projectionLookupBindings).hasSize(1); + assertThat(projectionLookupBindings.get(0)) + .containsExactly(scope.databaseValue(), expectedTenantKey, AUDIT_EVENT_ID); + assertThat(inserted.inserted()).isTrue(); + assertThat(inserted.receipt().logEventId()).isEqualTo(LOG_EVENT_ID); + assertThat(inserted.receipt().receiptId()).isEqualTo(RECEIPT_ID); + assertThat(inserted.receipt().scope()).isEqualTo(scope.databaseValue()); + assertThat(inserted.receipt().tenantId()).isEqualTo(tenantId); + assertThat(inserted.receipt().auditEventId()).isEqualTo(AUDIT_EVENT_ID); + } + + private static CreateLogEventRequest request(AccountAuditScope scope, Long tenantId) { + return new CreateLogEventRequest( + scope, + tenantId, + AUDIT_EVENT_ID, + "account-service", + "ACCOUNT_REGISTERED", + Instant.parse("2026-10-01T12:00:00Z"), + 1, + ByteString.copyFromUtf8("{}"), + 1, + "sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"); + } + + private static AccountAuditReceiptsRecord receiptRecord( + DSLContext dsl, AccountAuditScope scope, Long tenantId) { + AccountAuditReceiptsRecord row = dsl.newRecord(ACCOUNT_AUDIT_RECEIPTS); + row.setId(5L); + row.setLogEventId(LOG_EVENT_ID); + row.setReceiptId(RECEIPT_ID); + row.setScope(scope.databaseValue()); + row.setTenantId(tenantId); + row.setAuditEventId(AUDIT_EVENT_ID); + row.setProducerService("account-service"); + row.setEventType("ACCOUNT_REGISTERED"); + row.setOccurredAtSeconds(Instant.parse("2026-10-01T12:00:00Z").getEpochSecond()); + row.setOccurredAtNanos(0); + row.setSchemaVersion(1); + row.setPayloadDigestVersion(1); + row.setPayloadDigest("sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"); + row.setPayload("{}".getBytes(StandardCharsets.UTF_8)); + row.setStatus("COMMITTED"); + row.setOutcome("ACCEPTED"); + return row; + } +} diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/AccountAuditPeerGrpcMtlsTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/AccountAuditPeerGrpcMtlsTest.java new file mode 100644 index 0000000000..cec5e8cc57 --- /dev/null +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/AccountAuditPeerGrpcMtlsTest.java @@ -0,0 +1,379 @@ +package net.firedevops.firemud.loggingadmin.service.impl; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.verifyNoMoreInteractions; + +import com.google.protobuf.ByteString; +import com.google.protobuf.Timestamp; +import io.grpc.ManagedChannel; +import io.grpc.Metadata; +import io.grpc.Server; +import io.grpc.ServerInterceptors; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; +import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; +import io.grpc.stub.MetadataUtils; +import io.micrometer.core.instrument.simple.SimpleMeterRegistry; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.security.MessageDigest; +import java.time.Instant; +import java.util.HexFormat; +import java.util.List; +import java.util.Map; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.common.config.CommonSecurityAutoConfiguration; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.common.security.AuthTokenInterceptor; +import net.firedevops.firemud.common.security.GrpcAuthProperties; +import net.firedevops.firemud.common.security.JwtUtil; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.loggingadmin.config.AccountAuditGrpcAuthConfiguration; +import net.firedevops.firemud.loggingadmin.dto.AccountAuditReceiptDto; +import net.firedevops.firemud.loggingadmin.dto.AccountAuditReceiptOutcome; +import net.firedevops.firemud.loggingadmin.dto.AccountAuditReceiptStatus; +import net.firedevops.firemud.loggingadmin.dto.AccountAuditScope; +import net.firedevops.firemud.loggingadmin.service.LogEventService; +import net.firedevops.firemud.loggingadmin.service.LogQueryService; +import net.firedevops.firemud.loggingadmin.service.ModerationService; +import net.firedevops.firemud.loggingadmin.v1.CreateLogEventRequest; +import net.firedevops.firemud.loggingadmin.v1.LoggingAdminServiceGrpc; +import net.firedevops.firemud.loggingadmin.v1.QueryLogsRequest; +import net.firedevops.firemud.loggingadmin.v1.ReadLogEventReceiptRequest; +import net.firedevops.firemud.test.LoopbackMtlsTestPki; +import net.firedevops.firemud.test.LoopbackMtlsTestPki.IdentitySpec; +import net.firedevops.firemud.test.TlsTestSupport; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.boot.autoconfigure.AutoConfigurations; +import org.springframework.boot.autoconfigure.context.ConfigurationPropertiesAutoConfiguration; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; + +/** Physical TLS caller-policy proof with a mocked receipt owner, not durable storage proof. */ +class AccountAuditPeerGrpcMtlsTest { + private static final String NAMESPACE = "test"; + private static final String ACCOUNT_URI = "spiffe://firemud/ns/test/sa/account-service"; + private static final String EVENT_ID = "4cae05e8-7a6b-4b14-9d44-665e3eec450b"; + private static final String RECEIPT_ID = "d2719d4f-3b2a-4f64-a994-0f9ccdfdd2b3"; + private static final String PAYLOAD = "{\"auditMarker\":\"loopback-read\"}"; + private static final Instant OCCURRED_AT = Instant.parse("2026-10-01T12:00:00.123456789Z"); + private static final String JWT_SECRET = + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; + private static final String CLAIM_EVIDENCE_METHOD = + "logging_admin.v1.StartSessionReservationEvidenceService/ReadCurrentClaimEvidence"; + + @TempDir static Path temporaryDirectory; + + private static LoopbackMtlsTestPki.Pki pki; + private static AuthTokenInterceptor authInterceptor; + private static String payloadDigest; + + @BeforeAll + static void createTrustedWorkloadCertificatesAndSelectProductionAuthInterceptor() + throws Exception { + pki = + LoopbackMtlsTestPki.create( + temporaryDirectory, + "FireMUD Account audit peer test CA", + new IdentitySpec("logging", "spiffe://firemud/ns/test/sa/logging-admin-service", true), + new IdentitySpec("account", ACCOUNT_URI, false), + new IdentitySpec( + "world", "spiffe://firemud/ns/test/sa/world-management-service", false), + new IdentitySpec( + "other-account", "spiffe://firemud/ns/other/sa/account-service", false)); + payloadDigest = + "sha256:" + + HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256") + .digest(PAYLOAD.getBytes(StandardCharsets.UTF_8))); + new ApplicationContextRunner() + .withConfiguration( + AutoConfigurations.of( + ConfigurationPropertiesAutoConfiguration.class, + CommonSecurityAutoConfiguration.class)) + .withUserConfiguration(AccountAuditGrpcAuthConfiguration.class) + .withPropertyValues( + "firemud.auth.jwt-secret=" + JWT_SECRET, + "firemud.auth.grpc.public-methods[0]=" + CLAIM_EVIDENCE_METHOD) + .run( + context -> { + assertThat(context).hasSingleBean(AuthTokenInterceptor.class); + assertThat(context.getBean(GrpcAuthProperties.class).getPublicMethods()) + .containsExactly(CLAIM_EVIDENCE_METHOD); + authInterceptor = context.getBean(AuthTokenInterceptor.class); + assertThat(authInterceptor) + .isSameAs(context.getBean("accountAuditAuthTokenInterceptor")); + }); + } + + @Test + void exactAccountCertificateReachesCreateOnlyAsUnavailableWithoutOwnerAccess() throws Exception { + LogEventService owner = mock(LogEventService.class); + try (TransportServer server = startServer(owner); + ClientTransport client = newClient(server.port(), "account")) { + assertStatus(Status.Code.UNAVAILABLE, () -> client.stub().createLogEvent(createRequest())); + verifyNoInteractions(owner); + } + } + + @Test + void exactAccountCertificateReadsCanonicalReceiptWithoutJwtFromMockedOwner() throws Exception { + LogEventService owner = mock(LogEventService.class); + var expected = + new net.firedevops.firemud.loggingadmin.dto.CreateLogEventRequest( + AccountAuditScope.TENANT, + 42L, + EVENT_ID, + "account-service", + "PUBLIC_PRODUCTION_JOINED", + OCCURRED_AT, + 1, + ByteString.copyFromUtf8(PAYLOAD), + 1, + payloadDigest); + doAnswer( + invocation -> { + assertThat(GrpcPeerIdentity.current()).isNotNull(); + assertThat(GrpcPeerIdentity.current().uri()).isEqualTo(ACCOUNT_URI); + assertThat(SessionContext.hasAuthenticatedCallerContext()).isFalse(); + assertThat(invocation.getArgument(0, expected.getClass())).isEqualTo(expected); + return new AccountAuditReceiptDto( + AccountAuditScope.TENANT, + 42L, + EVENT_ID, + RECEIPT_ID, + 77L, + 1, + 1, + payloadDigest, + AccountAuditReceiptStatus.COMMITTED, + AccountAuditReceiptOutcome.DUPLICATE); + }) + .when(owner) + .readLogEventReceipt(expected); + try (TransportServer server = startServer(owner); + ClientTransport client = newClient(server.port(), "account")) { + var response = client.stub().readLogEventReceipt(readRequest()); + assertThat(response.hasError()).isFalse(); + assertThat(response.getScope()) + .isEqualTo( + net.firedevops.firemud.loggingadmin.v1.AccountAuditScope.ACCOUNT_AUDIT_SCOPE_TENANT); + assertThat(response.getTenantId()).isEqualTo("42"); + assertThat(response.getAuditEventId()).isEqualTo(EVENT_ID); + assertThat(response.getReceiptId()).isEqualTo(RECEIPT_ID); + assertThat(response.getLogEventId()).isEqualTo("77"); + assertThat(response.getSchemaVersion()).isEqualTo(1); + assertThat(response.getPayloadDigestVersion()).isEqualTo(1); + assertThat(response.getPayloadDigest()).isEqualTo(payloadDigest); + assertThat(response.getStatus()) + .isEqualTo( + net.firedevops.firemud.loggingadmin.v1.AccountAuditReceiptStatus + .ACCOUNT_AUDIT_RECEIPT_STATUS_COMMITTED); + assertThat(response.getOutcome()) + .isEqualTo( + net.firedevops.firemud.loggingadmin.v1.AccountAuditReceiptOutcome + .ACCOUNT_AUDIT_RECEIPT_OUTCOME_DUPLICATE); + verify(owner).readLogEventReceipt(expected); + verifyNoMoreInteractions(owner); + } + } + + @ParameterizedTest + @ValueSource(strings = {"world", "other-account"}) + void trustedWrongWorkloadOrNamespaceCannotUseEitherAuditMethod(String alias) throws Exception { + LogEventService owner = mock(LogEventService.class); + try (TransportServer server = startServer(owner); + ClientTransport client = newClient(server.port(), alias)) { + assertAuditDenied(client.stub()); + verifyNoInteractions(owner); + } + } + + @Test + void forgedPeerHeadersAndAdminServiceJwtCannotReplaceWorkloadCertificate() throws Exception { + LogEventService owner = mock(LogEventService.class); + Metadata spoofed = new Metadata(); + for (String header : List.of("x-peer-identity", "x-spiffe-id", "x-workload-identity")) { + spoofed.put(Metadata.Key.of(header, Metadata.ASCII_STRING_MARSHALLER), ACCOUNT_URI); + } + String token = + new JwtUtil(JWT_SECRET, 60_000L) + .generateToken( + "account-service", + Map.of( + "internalService", + true, + "serviceName", + "account-service", + "globalRoles", + List.of("platformAdmin"))); + spoofed.put( + Metadata.Key.of("authorization", Metadata.ASCII_STRING_MARSHALLER), "Bearer " + token); + try (TransportServer server = startServer(owner); + ClientTransport client = newClient(server.port(), "world")) { + assertAuditDenied( + client.stub().withInterceptors(MetadataUtils.newAttachHeadersInterceptor(spoofed))); + verifyNoInteractions(owner); + } + } + + @Test + void missingClientCertificateFailsHandshakeBeforeOwnerAccess() throws Exception { + LogEventService owner = mock(LogEventService.class); + CommonGrpcClientProperties tls = new CommonGrpcClientProperties(); + tls.setPlaintext(false); + var issued = pki.clientProperties(temporaryDirectory, pki.identity("account")); + tls.setCaCert(issued.getCaCert()); + try (TransportServer server = startServer(owner); + ClientTransport client = newClient(server.port(), tls)) { + assertHandshakeRejected(() -> client.stub().createLogEvent(createRequest())); + assertHandshakeRejected(() -> client.stub().readLogEventReceipt(readRequest())); + verifyNoInteractions(owner); + } + } + + @Test + void exactAccountCertificateDoesNotBypassJwtOnUnrelatedQueryMethod() throws Exception { + LogEventService owner = mock(LogEventService.class); + try (TransportServer server = startServer(owner); + ClientTransport client = newClient(server.port(), "account")) { + assertStatus( + Status.Code.UNAUTHENTICATED, + () -> client.stub().queryLogs(QueryLogsRequest.newBuilder().setTenantId("42").build())); + verifyNoInteractions(owner); + } + } + + private static CreateLogEventRequest createRequest() { + return CreateLogEventRequest.newBuilder() + .setScope( + net.firedevops.firemud.loggingadmin.v1.AccountAuditScope.ACCOUNT_AUDIT_SCOPE_TENANT) + .setTenantId("42") + .setAuditEventId(EVENT_ID) + .setProducerService("account-service") + .setEventType("PUBLIC_PRODUCTION_JOINED") + .setOccurredAt( + Timestamp.newBuilder() + .setSeconds(OCCURRED_AT.getEpochSecond()) + .setNanos(OCCURRED_AT.getNano())) + .setSchemaVersion(1) + .setPayload(ByteString.copyFromUtf8(PAYLOAD)) + .setPayloadDigestVersion(1) + .setPayloadDigest(payloadDigest) + .build(); + } + + private static ReadLogEventReceiptRequest readRequest() { + var request = createRequest(); + return ReadLogEventReceiptRequest.newBuilder() + .setScope(request.getScope()) + .setTenantId(request.getTenantId()) + .setAuditEventId(request.getAuditEventId()) + .setProducerService(request.getProducerService()) + .setEventType(request.getEventType()) + .setOccurredAt(request.getOccurredAt()) + .setSchemaVersion(request.getSchemaVersion()) + .setPayload(request.getPayload()) + .setPayloadDigestVersion(request.getPayloadDigestVersion()) + .setPayloadDigest(request.getPayloadDigest()) + .build(); + } + + private static void assertAuditDenied( + LoggingAdminServiceGrpc.LoggingAdminServiceBlockingStub stub) { + assertStatus(Status.Code.PERMISSION_DENIED, () -> stub.createLogEvent(createRequest())); + assertStatus(Status.Code.PERMISSION_DENIED, () -> stub.readLogEventReceipt(readRequest())); + } + + private static void assertStatus(Status.Code expected, Runnable invocation) { + assertThatThrownBy(invocation::run) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(expected)); + } + + private static void assertHandshakeRejected(Runnable invocation) { + assertThatThrownBy(invocation::run) + .isInstanceOf(StatusRuntimeException.class) + .satisfies(failure -> assertThat(TlsTestSupport.isTlsHandshakeRejection(failure)).isTrue()); + } + + private static TransportServer startServer(LogEventService owner) throws Exception { + var service = + new LoggingAdminGrpcService( + mock(LogQueryService.class), + owner, + mock(ModerationService.class), + new SimpleMeterRegistry(), + NAMESPACE); + var identity = pki.identity("logging"); + Server server = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer(identity.privateKey(), identity.certificate())) + .trustManager(pki.caCertificate()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService( + ServerInterceptors.intercept( + service, authInterceptor, new GrpcPeerIdentityInterceptor())) + .build() + .start(); + return new TransportServer(server); + } + + private static ClientTransport newClient(int port, String alias) throws Exception { + return newClient(port, pki.clientProperties(temporaryDirectory, pki.identity(alias))); + } + + private static ClientTransport newClient(int port, CommonGrpcClientProperties tls) + throws Exception { + return new ClientTransport( + new GrpcChannelFactory().buildChannel("127.0.0.1:" + port, 6565, tls, false)); + } + + private record TransportServer(Server server) implements AutoCloseable { + private int port() { + return server.getPort(); + } + + @Override + public void close() throws InterruptedException { + server.shutdownNow(); + if (!server.awaitTermination(2, TimeUnit.SECONDS)) { + throw new IllegalStateException("Loopback Account audit server did not terminate"); + } + } + } + + private record ClientTransport(ManagedChannel channel) implements AutoCloseable { + private LoggingAdminServiceGrpc.LoggingAdminServiceBlockingStub stub() { + return LoggingAdminServiceGrpc.newBlockingStub(channel) + .withDeadlineAfter(5, TimeUnit.SECONDS); + } + + @Override + public void close() throws InterruptedException { + if (!channel.shutdownNow().awaitTermination(2, TimeUnit.SECONDS)) { + throw new IllegalStateException("Loopback Account audit client did not terminate"); + } + } + } +} diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/LogEventServiceImplTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/LogEventServiceImplTest.java new file mode 100644 index 0000000000..430b34618c --- /dev/null +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/LogEventServiceImplTest.java @@ -0,0 +1,474 @@ +package net.firedevops.firemud.loggingadmin.service.impl; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import com.google.protobuf.ByteString; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.Instant; +import java.util.HexFormat; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.loggingadmin.dto.AccountAuditReceiptOutcome; +import net.firedevops.firemud.loggingadmin.dto.AccountAuditReceiptStatus; +import net.firedevops.firemud.loggingadmin.dto.AccountAuditScope; +import net.firedevops.firemud.loggingadmin.dto.CreateLogEventRequest; +import net.firedevops.firemud.loggingadmin.entity.AccountAuditReceipt; +import net.firedevops.firemud.loggingadmin.entity.AccountAuditReceiptInsertResult; +import net.firedevops.firemud.loggingadmin.repository.AccountAuditReceiptRepository; +import net.firedevops.firemud.loggingadmin.service.AuditReceiptNotFoundException; +import net.firedevops.firemud.loggingadmin.service.AuditStorageUnavailableException; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; +import org.springframework.dao.DataAccessResourceFailureException; + +class LogEventServiceImplTest { + private static final String AUDIT_EVENT_ID = "d2719d4f-3b2a-4f64-a994-0f9ccdfdd2b3"; + private static final UUID RECEIPT_ID = UUID.fromString("c0c1f03b-31b7-4281-aaf8-2d66f29e8770"); + private static final long LOG_EVENT_ID = 192L; + + private final AccountAuditReceiptRepository repository = + Mockito.mock(AccountAuditReceiptRepository.class); + private final LogEventServiceImpl service = new LogEventServiceImpl(repository); + + @Test + void firstWriteReturnsCommittedAcceptedReceipt() { + CreateLogEventRequest request = request(AccountAuditScope.PLATFORM, null, Instant.EPOCH, "{}"); + AccountAuditReceipt receipt = + receipt(request, request.payload().toByteArray(), "COMMITTED", "ACCEPTED"); + when(repository.insertIfAbsent(eq(request), any(UUID.class))) + .thenReturn(new AccountAuditReceiptInsertResult(receipt, true)); + + var result = service.createLogEvent(request); + + assertEquals(AccountAuditReceiptStatus.COMMITTED, result.status()); + assertEquals(AccountAuditReceiptOutcome.ACCEPTED, result.outcome()); + assertEquals(LOG_EVENT_ID, result.logEventId()); + verify(repository).insertIfAbsent(eq(request), any(UUID.class)); + } + + @Test + void exactRetryReturnsOriginalReceiptAsDuplicate() { + CreateLogEventRequest request = request(AccountAuditScope.TENANT, 42L, Instant.EPOCH, "{}"); + AccountAuditReceipt receipt = + receipt(request, request.payload().toByteArray(), "COMMITTED", "ACCEPTED"); + when(repository.insertIfAbsent(eq(request), any(UUID.class))) + .thenReturn(new AccountAuditReceiptInsertResult(receipt, false)); + + var result = service.createLogEvent(request); + + assertEquals(AccountAuditReceiptStatus.COMMITTED, result.status()); + assertEquals(AccountAuditReceiptOutcome.DUPLICATE, result.outcome()); + assertEquals(42L, result.tenantId()); + assertEquals(LOG_EVENT_ID, result.logEventId()); + assertEquals(RECEIPT_ID.toString(), result.receiptId()); + } + + @Test + void changedPayloadReturnsIdempotencyConflict() { + CreateLogEventRequest original = request(AccountAuditScope.TENANT, 42L, Instant.EPOCH, "{}"); + CreateLogEventRequest changed = + request(AccountAuditScope.TENANT, 42L, Instant.EPOCH, "{\"changed\":true}"); + when(repository.insertIfAbsent(eq(changed), any(UUID.class))) + .thenReturn( + new AccountAuditReceiptInsertResult( + receipt(original, original.payload().toByteArray(), "COMMITTED", "ACCEPTED"), + false)); + + var result = service.createLogEvent(changed); + + assertEquals(AccountAuditReceiptStatus.CONFLICT, result.status()); + assertEquals(AccountAuditReceiptOutcome.IDEMPOTENCY_CONFLICT, result.outcome()); + assertEquals(LOG_EVENT_ID, result.logEventId()); + } + + @Test + void changedImmutableMetadataReturnsIdempotencyConflict() { + CreateLogEventRequest original = request(AccountAuditScope.PLATFORM, null, Instant.EPOCH, "{}"); + CreateLogEventRequest changed = + request(AccountAuditScope.PLATFORM, null, Instant.EPOCH.plusSeconds(1), "{}"); + when(repository.insertIfAbsent(eq(changed), any(UUID.class))) + .thenReturn( + new AccountAuditReceiptInsertResult( + receipt(original, original.payload().toByteArray(), "COMMITTED", "ACCEPTED"), + false)); + + var result = service.createLogEvent(changed); + + assertEquals(AccountAuditReceiptStatus.CONFLICT, result.status()); + assertEquals(AccountAuditReceiptOutcome.IDEMPOTENCY_CONFLICT, result.outcome()); + } + + @Test + void changedEventTypeWithinIdentityReturnsIdempotencyConflict() { + CreateLogEventRequest original = request(AccountAuditScope.TENANT, 42L, Instant.EPOCH, "{}"); + CreateLogEventRequest changed = + new CreateLogEventRequest( + original.scope(), + original.tenantId(), + original.auditEventId(), + original.producerService(), + "ACCOUNT_RECOVERY", + original.occurredAt(), + original.schemaVersion(), + original.payload(), + original.payloadDigestVersion(), + original.payloadDigest()); + when(repository.insertIfAbsent(eq(changed), any(UUID.class))) + .thenReturn( + new AccountAuditReceiptInsertResult( + receipt(original, original.payload().toByteArray(), "COMMITTED", "ACCEPTED"), + false)); + + var result = service.createLogEvent(changed); + + assertEquals(AccountAuditReceiptStatus.CONFLICT, result.status()); + assertEquals(AccountAuditReceiptOutcome.IDEMPOTENCY_CONFLICT, result.outcome()); + assertEquals(LOG_EVENT_ID, result.logEventId()); + } + + @Test + void minimizedRetryIsSuccessfulButNonReplayable() { + CreateLogEventRequest request = request(AccountAuditScope.PLATFORM, null, Instant.EPOCH, "{}"); + when(repository.insertIfAbsent(eq(request), any(UUID.class))) + .thenReturn( + new AccountAuditReceiptInsertResult( + receipt(request, null, "MINIMIZED", "NON_REPLAYABLE"), false)); + + var result = service.createLogEvent(request); + + assertEquals(AccountAuditReceiptStatus.MINIMIZED, result.status()); + assertEquals(AccountAuditReceiptOutcome.NON_REPLAYABLE, result.outcome()); + } + + @Test + void minimizedReadAcceptsOmittedPayloadWithMatchingIdentityMetadataAndDigest() { + CreateLogEventRequest original = + request(AccountAuditScope.PLATFORM, null, Instant.EPOCH, "{\"retained\":true}"); + CreateLogEventRequest digestOnly = withPayload(original, ByteString.EMPTY); + when(repository.findByIdentity(eq(digestOnly), eq(0L))) + .thenReturn(Optional.of(receipt(original, null, "MINIMIZED", "NON_REPLAYABLE"))); + + var result = service.readLogEventReceipt(digestOnly); + + assertEquals(AccountAuditReceiptStatus.MINIMIZED, result.status()); + assertEquals(AccountAuditReceiptOutcome.NON_REPLAYABLE, result.outcome()); + assertEquals(RECEIPT_ID.toString(), result.receiptId()); + verify(repository).findByIdentity(eq(digestOnly), eq(0L)); + } + + @Test + void minimizedReadReportsConflictForChangedDigestOrImmutableMetadata() { + CreateLogEventRequest original = + request(AccountAuditScope.TENANT, 42L, Instant.EPOCH, "{\"retained\":true}"); + CreateLogEventRequest changedDigest = + withPayloadAndDigest( + original, + ByteString.EMPTY, + digest("{\"changed\":true}".getBytes(StandardCharsets.UTF_8))); + CreateLogEventRequest changedEventType = + withEventType(withPayload(original, ByteString.EMPTY), "ACCOUNT_RECOVERY"); + AccountAuditReceipt minimized = receipt(original, null, "MINIMIZED", "NON_REPLAYABLE"); + when(repository.findByIdentity(eq(changedDigest), eq(42L))).thenReturn(Optional.of(minimized)); + when(repository.findByIdentity(eq(changedEventType), eq(42L))) + .thenReturn(Optional.of(minimized)); + + var digestResult = service.readLogEventReceipt(changedDigest); + var metadataResult = service.readLogEventReceipt(changedEventType); + + assertEquals(AccountAuditReceiptStatus.CONFLICT, digestResult.status()); + assertEquals(AccountAuditReceiptOutcome.IDEMPOTENCY_CONFLICT, digestResult.outcome()); + assertEquals(AccountAuditReceiptStatus.CONFLICT, metadataResult.status()); + assertEquals(AccountAuditReceiptOutcome.IDEMPOTENCY_CONFLICT, metadataResult.outcome()); + } + + @Test + void readRejectsMalformedDigestAndUnsupportedVersionBeforeRepositoryAccess() { + CreateLogEventRequest valid = + request(AccountAuditScope.PLATFORM, null, Instant.EPOCH, "{\"retained\":true}"); + CreateLogEventRequest malformedDigest = + withPayloadAndDigest(valid, ByteString.EMPTY, "sha256:ABC"); + CreateLogEventRequest unsupportedVersion = withPayloadDigestVersion(valid, 2); + + assertThrows( + IllegalArgumentException.class, () -> service.readLogEventReceipt(malformedDigest)); + assertThrows( + IllegalArgumentException.class, () -> service.readLogEventReceipt(unsupportedVersion)); + + verifyNoInteractions(repository); + } + + @Test + void readRejectsSuppliedPayloadWithMismatchedDigestBeforeRepositoryAccess() { + CreateLogEventRequest valid = + request(AccountAuditScope.PLATFORM, null, Instant.EPOCH, "{\"retained\":true}"); + ByteString differentPayload = ByteString.copyFromUtf8("{\"changed\":true}"); + CreateLogEventRequest mismatched = + withPayloadAndDigest(valid, differentPayload, valid.payloadDigest()); + + assertThrows(IllegalArgumentException.class, () -> service.readLogEventReceipt(mismatched)); + + verifyNoInteractions(repository); + } + + @Test + void retainedReadRequiresFullPayloadAndReturnsConflictForOmittedOrChangedPayload() { + CreateLogEventRequest original = + request(AccountAuditScope.PLATFORM, null, Instant.EPOCH, "{\"retained\":true}"); + CreateLogEventRequest omitted = withPayload(original, ByteString.EMPTY); + CreateLogEventRequest changed = + request(AccountAuditScope.PLATFORM, null, Instant.EPOCH, "{\"changed\":true}"); + AccountAuditReceipt retained = + receipt(original, original.payload().toByteArray(), "COMMITTED", "ACCEPTED"); + when(repository.findByIdentity(eq(omitted), eq(0L))).thenReturn(Optional.of(retained)); + when(repository.findByIdentity(eq(changed), eq(0L))).thenReturn(Optional.of(retained)); + + var omittedResult = service.readLogEventReceipt(omitted); + var changedResult = service.readLogEventReceipt(changed); + + assertEquals(AccountAuditReceiptStatus.CONFLICT, omittedResult.status()); + assertEquals(AccountAuditReceiptOutcome.IDEMPOTENCY_CONFLICT, omittedResult.outcome()); + assertEquals(AccountAuditReceiptStatus.CONFLICT, changedResult.status()); + assertEquals(AccountAuditReceiptOutcome.IDEMPOTENCY_CONFLICT, changedResult.outcome()); + } + + @Test + void exactEmptyPayloadReadRemainsDistinctFromDigestOnlyMinimizedRead() { + CreateLogEventRequest emptyPayload = + request(AccountAuditScope.PLATFORM, null, Instant.EPOCH, ""); + AccountAuditReceipt retained = receipt(emptyPayload, new byte[0], "COMMITTED", "ACCEPTED"); + AccountAuditReceipt minimized = receipt(emptyPayload, null, "MINIMIZED", "NON_REPLAYABLE"); + when(repository.findByIdentity(eq(emptyPayload), eq(0L))) + .thenReturn(Optional.of(retained), Optional.of(minimized)); + + var retainedResult = service.readLogEventReceipt(emptyPayload); + var minimizedResult = service.readLogEventReceipt(emptyPayload); + + assertEquals(AccountAuditReceiptStatus.COMMITTED, retainedResult.status()); + assertEquals(AccountAuditReceiptOutcome.DUPLICATE, retainedResult.outcome()); + assertEquals(AccountAuditReceiptStatus.MINIMIZED, minimizedResult.status()); + assertEquals(AccountAuditReceiptOutcome.NON_REPLAYABLE, minimizedResult.outcome()); + } + + @Test + void missingReadbackThrowsForCanonicalNotFoundMapping() { + CreateLogEventRequest request = request(AccountAuditScope.PLATFORM, null, Instant.EPOCH, "{}"); + when(repository.findByIdentity(request, 0L)).thenReturn(Optional.empty()); + + assertThrows(AuditReceiptNotFoundException.class, () -> service.readLogEventReceipt(request)); + } + + @Test + void jooqWriteFailureMapsToAuditStorageUnavailableWithCause() { + CreateLogEventRequest request = request(AccountAuditScope.PLATFORM, null, Instant.EPOCH, "{}"); + var cause = new org.jooq.exception.DataAccessException("jOOQ write failed"); + when(repository.insertIfAbsent(eq(request), any(UUID.class))).thenThrow(cause); + + var exception = + assertThrows(AuditStorageUnavailableException.class, () -> service.createLogEvent(request)); + + assertSame(cause, exception.getCause()); + } + + @Test + void springWriteFailureMapsToAuditStorageUnavailableWithCause() { + CreateLogEventRequest request = request(AccountAuditScope.PLATFORM, null, Instant.EPOCH, "{}"); + var cause = new DataAccessResourceFailureException("Spring write failed"); + when(repository.insertIfAbsent(eq(request), any(UUID.class))).thenThrow(cause); + + var exception = + assertThrows(AuditStorageUnavailableException.class, () -> service.createLogEvent(request)); + + assertSame(cause, exception.getCause()); + } + + @Test + void jooqReadFailureMapsToAuditStorageUnavailableWithCause() { + CreateLogEventRequest request = request(AccountAuditScope.PLATFORM, null, Instant.EPOCH, "{}"); + var cause = new org.jooq.exception.DataAccessException("jOOQ read failed"); + when(repository.findByIdentity(eq(request), eq(0L))).thenThrow(cause); + + var exception = + assertThrows( + AuditStorageUnavailableException.class, () -> service.readLogEventReceipt(request)); + + assertSame(cause, exception.getCause()); + } + + @Test + void springReadFailureMapsToAuditStorageUnavailableWithCause() { + CreateLogEventRequest request = request(AccountAuditScope.PLATFORM, null, Instant.EPOCH, "{}"); + var cause = new DataAccessResourceFailureException("Spring read failed"); + when(repository.findByIdentity(eq(request), eq(0L))).thenThrow(cause); + + var exception = + assertThrows( + AuditStorageUnavailableException.class, () -> service.readLogEventReceipt(request)); + + assertSame(cause, exception.getCause()); + } + + @Test + void unsupportedDigestVersionFailsBeforeRepositoryAccess() { + CreateLogEventRequest valid = request(AccountAuditScope.PLATFORM, null, Instant.EPOCH, "{}"); + CreateLogEventRequest unsupported = + new CreateLogEventRequest( + valid.scope(), + valid.tenantId(), + valid.auditEventId(), + valid.producerService(), + valid.eventType(), + valid.occurredAt(), + valid.schemaVersion(), + valid.payload(), + 2, + valid.payloadDigest()); + + assertThrows(IllegalArgumentException.class, () -> service.createLogEvent(unsupported)); + verifyNoInteractions(repository); + } + + @Test + void payloadDigestMismatchFailsBeforeRepositoryAccess() { + CreateLogEventRequest valid = request(AccountAuditScope.PLATFORM, null, Instant.EPOCH, "{}"); + CreateLogEventRequest mismatched = + new CreateLogEventRequest( + valid.scope(), + valid.tenantId(), + valid.auditEventId(), + valid.producerService(), + valid.eventType(), + valid.occurredAt(), + valid.schemaVersion(), + valid.payload(), + valid.payloadDigestVersion(), + "sha256:" + "0".repeat(64)); + + assertThrows(IllegalArgumentException.class, () -> service.createLogEvent(mismatched)); + verifyNoInteractions(repository); + } + + @Test + void invalidUtf8PayloadFailsBeforeRepositoryAccess() { + ByteString payload = ByteString.copyFrom(new byte[] {(byte) 0xff}); + CreateLogEventRequest request = + new CreateLogEventRequest( + AccountAuditScope.PLATFORM, + null, + AUDIT_EVENT_ID, + "account-service", + "ACCOUNT_REGISTERED", + Instant.EPOCH, + 1, + payload, + 1, + digest(payload.toByteArray())); + + assertThrows(IllegalArgumentException.class, () -> service.createLogEvent(request)); + verifyNoInteractions(repository); + } + + private static CreateLogEventRequest request( + AccountAuditScope scope, Long tenantId, Instant occurredAt, String payloadText) { + ByteString payload = ByteString.copyFrom(payloadText, StandardCharsets.UTF_8); + return new CreateLogEventRequest( + scope, + tenantId, + AUDIT_EVENT_ID, + "account-service", + "ACCOUNT_REGISTERED", + occurredAt, + 1, + payload, + 1, + digest(payload.toByteArray())); + } + + private static CreateLogEventRequest withPayload( + CreateLogEventRequest request, ByteString payload) { + return withPayloadAndDigest(request, payload, request.payloadDigest()); + } + + private static CreateLogEventRequest withPayloadAndDigest( + CreateLogEventRequest request, ByteString payload, String payloadDigest) { + return new CreateLogEventRequest( + request.scope(), + request.tenantId(), + request.auditEventId(), + request.producerService(), + request.eventType(), + request.occurredAt(), + request.schemaVersion(), + payload, + request.payloadDigestVersion(), + payloadDigest); + } + + private static CreateLogEventRequest withEventType( + CreateLogEventRequest request, String eventType) { + return new CreateLogEventRequest( + request.scope(), + request.tenantId(), + request.auditEventId(), + request.producerService(), + eventType, + request.occurredAt(), + request.schemaVersion(), + request.payload(), + request.payloadDigestVersion(), + request.payloadDigest()); + } + + private static CreateLogEventRequest withPayloadDigestVersion( + CreateLogEventRequest request, int payloadDigestVersion) { + return new CreateLogEventRequest( + request.scope(), + request.tenantId(), + request.auditEventId(), + request.producerService(), + request.eventType(), + request.occurredAt(), + request.schemaVersion(), + request.payload(), + payloadDigestVersion, + request.payloadDigest()); + } + + private static AccountAuditReceipt receipt( + CreateLogEventRequest request, byte[] payload, String status, String outcome) { + return new AccountAuditReceipt( + 91L, + LOG_EVENT_ID, + RECEIPT_ID, + request.scope().databaseValue(), + request.tenantId(), + request.auditEventId(), + request.producerService(), + request.eventType(), + request.occurredAt().getEpochSecond(), + request.occurredAt().getNano(), + request.schemaVersion(), + request.payloadDigestVersion(), + request.payloadDigest(), + payload, + status, + outcome); + } + + private static String digest(byte[] payload) { + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(payload)); + } catch (NoSuchAlgorithmException ex) { + throw new IllegalStateException(ex); + } + } +} diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/LoggingAdminGrpcServiceAuthTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/LoggingAdminGrpcServiceAuthTest.java index ef42ead3d8..7fc06eeada 100644 --- a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/LoggingAdminGrpcServiceAuthTest.java +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/LoggingAdminGrpcServiceAuthTest.java @@ -1,24 +1,51 @@ package net.firedevops.firemud.loggingadmin.service.impl; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; import com.google.protobuf.ByteString; import com.google.protobuf.Timestamp; +import io.grpc.Context; +import io.grpc.Metadata; +import io.grpc.MethodDescriptor; +import io.grpc.ServerCall; +import io.grpc.ServerCallHandler; import io.grpc.Status; +import io.grpc.protobuf.ProtoUtils; import io.grpc.stub.StreamObserver; import io.micrometer.core.instrument.simple.SimpleMeterRegistry; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.Instant; +import java.util.HexFormat; import java.util.List; import java.util.Map; +import java.util.Optional; +import java.util.UUID; import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.common.config.CommonSecurityAutoConfiguration; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.AuthTokenInterceptor; +import net.firedevops.firemud.common.security.GrpcAuthProperties; import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.loggingadmin.config.AccountAuditGrpcAuthConfiguration; +import net.firedevops.firemud.loggingadmin.dto.AccountAuditReceiptDto; +import net.firedevops.firemud.loggingadmin.dto.AccountAuditReceiptOutcome; +import net.firedevops.firemud.loggingadmin.dto.AccountAuditReceiptStatus; +import net.firedevops.firemud.loggingadmin.dto.AccountAuditScope; import net.firedevops.firemud.loggingadmin.dto.ModerationPolicyDecisionDto; +import net.firedevops.firemud.loggingadmin.entity.AccountAuditReceipt; +import net.firedevops.firemud.loggingadmin.repository.AccountAuditReceiptRepository; +import net.firedevops.firemud.loggingadmin.service.AuditReceiptNotFoundException; import net.firedevops.firemud.loggingadmin.service.LogEventService; import net.firedevops.firemud.loggingadmin.service.LogQueryService; import net.firedevops.firemud.loggingadmin.service.ModerationService; @@ -30,11 +57,16 @@ import net.firedevops.firemud.loggingadmin.v1.EvaluateModerationPolicyResponse; import net.firedevops.firemud.loggingadmin.v1.QueryLogsRequest; import net.firedevops.firemud.loggingadmin.v1.QueryLogsResponse; +import net.firedevops.firemud.loggingadmin.v1.ReadLogEventReceiptRequest; +import net.firedevops.firemud.loggingadmin.v1.ReadLogEventReceiptResponse; import net.firedevops.firemud.loggingadmin.v1.ToggleFeatureFlagRequest; import net.firedevops.firemud.loggingadmin.v1.ToggleFeatureFlagResponse; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; +import org.springframework.boot.autoconfigure.AutoConfigurations; +import org.springframework.boot.autoconfigure.context.ConfigurationPropertiesAutoConfiguration; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; class LoggingAdminGrpcServiceAuthTest { @AfterEach @@ -42,6 +74,45 @@ void tearDown() { SessionContext.clear(); } + @Test + void auditMethodsBypassJwtRequirementButOtherMethodsRemainProtected() { + new ApplicationContextRunner() + .withConfiguration( + AutoConfigurations.of( + ConfigurationPropertiesAutoConfiguration.class, + CommonSecurityAutoConfiguration.class)) + .withUserConfiguration(AccountAuditGrpcAuthConfiguration.class) + .withPropertyValues( + "firemud.auth.jwt-secret=testsecretkeytestsecretkeytest1234", + "firemud.auth.grpc.public-methods[0]=logging_admin.v1.LoggingAdminService/Ping", + "firemud.auth.grpc.public-methods[1]=logging_admin.v1.StartSessionReservationEvidenceService/ReadCurrentClaimEvidence") + .run( + context -> { + assertThat(context).hasSingleBean(AuthTokenInterceptor.class); + GrpcAuthProperties properties = context.getBean(GrpcAuthProperties.class); + assertThat(properties.getPublicMethods()) + .containsExactly( + "logging_admin.v1.LoggingAdminService/Ping", + "logging_admin.v1.StartSessionReservationEvidenceService/ReadCurrentClaimEvidence"); + AuthTokenInterceptor interceptor = context.getBean(AuthTokenInterceptor.class); + assertTrue( + passesWithoutBearer( + interceptor, "logging_admin.v1.LoggingAdminService/CreateLogEvent")); + assertTrue( + passesWithoutBearer( + interceptor, "logging_admin.v1.LoggingAdminService/ReadLogEventReceipt")); + assertTrue( + passesWithoutBearer(interceptor, "logging_admin.v1.LoggingAdminService/Ping")); + assertTrue( + passesWithoutBearer( + interceptor, + "logging_admin.v1.StartSessionReservationEvidenceService/ReadCurrentClaimEvidence")); + assertFalse( + passesWithoutBearer( + interceptor, "logging_admin.v1.LoggingAdminService/QueryLogs")); + }); + } + @Test void adminMethodsReturnPermissionDeniedErrorDetail() { SessionContext.setContext("1", List.of("player"), Map.of()); @@ -74,19 +145,230 @@ public void onCompleted() {} } @Test - void createLogEventReturnsUnavailableForTypedRequestWithoutDispatch() { + void exactAccountMtlsPeerGetsUnavailableWithoutJwtOrAdminRole() { + LogEventService logEventService = Mockito.mock(LogEventService.class); + LoggingAdminGrpcService service = newService(logEventService); + + AtomicReference ref = new AtomicReference<>(); + AtomicReference error = new AtomicReference<>(); + invokeWithPeer( + "account-service", + () -> service.createLogEvent(validCreateRequest(), responseObserver(ref, error))); + + assertNull(ref.get()); + assertEquals(Status.Code.UNAVAILABLE, Status.fromThrowable(error.get()).getCode()); + assertEquals( + "Account audit ingress is unavailable", Status.fromThrowable(error.get()).getDescription()); + verifyNoInteractions(logEventService); + } + + @Test + void offlineFixtureMapsAcceptedReceiptToTypedCreateResponse() { + String payload = "{\"accountId\":42}"; + String digest = digest(payload.getBytes(StandardCharsets.UTF_8)); + AccountAuditReceiptDto receipt = + new AccountAuditReceiptDto( + AccountAuditScope.PLATFORM, + null, + "d2719d4f-3b2a-4f64-a994-0f9ccdfdd2b3", + "receipt-1", + 77L, + 1, + 1, + digest, + AccountAuditReceiptStatus.COMMITTED, + AccountAuditReceiptOutcome.ACCEPTED); + + CreateLogEventResponse response = LoggingAdminGrpcService.toCreateLogEventResponse(receipt); + + assertEquals("77", response.getLogEventId()); + assertEquals( + net.firedevops.firemud.loggingadmin.v1.AccountAuditScope.ACCOUNT_AUDIT_SCOPE_PLATFORM, + response.getScope()); + assertEquals( + net.firedevops.firemud.loggingadmin.v1.AccountAuditReceiptStatus + .ACCOUNT_AUDIT_RECEIPT_STATUS_COMMITTED, + response.getStatus()); + assertEquals( + net.firedevops.firemud.loggingadmin.v1.AccountAuditReceiptOutcome + .ACCOUNT_AUDIT_RECEIPT_OUTCOME_ACCEPTED, + response.getOutcome()); + } + + @Test + void adminJwtClaimsDoNotAuthorizeAuditIngressWithoutAccountPeer() { SessionContext.setContext("1", List.of("platformAdmin"), Map.of()); LogEventService logEventService = Mockito.mock(LogEventService.class); - assertCreateLogEventUnavailable(validCreateLogEventRequest(), logEventService); + LoggingAdminGrpcService service = newService(logEventService); + AtomicReference response = new AtomicReference<>(); + AtomicReference error = new AtomicReference<>(); + + service.createLogEvent(validCreateRequest(), responseObserver(response, error)); + + assertEquals(Status.Code.PERMISSION_DENIED, Status.fromThrowable(error.get()).getCode()); + verifyNoInteractions(logEventService); } @Test - void createLogEventFailsClosedBeforeTypedRequestValidation() { + void jwtClaimNamingAccountServiceCannotOverrideWrongMtlsPeer() { + SessionContext.setContext(null, List.of(), Map.of(), true, "account-service", "instance-1"); LogEventService logEventService = Mockito.mock(LogEventService.class); - CreateLogEventRequest unsupportedDigestVersion = - validCreateLogEventRequest().toBuilder().setPayloadDigestVersion(2).build(); + LoggingAdminGrpcService service = newService(logEventService); + AtomicReference response = new AtomicReference<>(); + AtomicReference error = new AtomicReference<>(); - assertCreateLogEventUnavailable(unsupportedDigestVersion, logEventService); + invokeWithPeer( + "game-session-service", + () -> service.createLogEvent(validCreateRequest(), responseObserver(response, error))); + + assertEquals(Status.Code.PERMISSION_DENIED, Status.fromThrowable(error.get()).getCode()); + verifyNoInteractions(logEventService); + } + + @Test + void accountAuditRejectsAccountServicePeerFromOtherNamespace() { + LogEventService logEventService = Mockito.mock(LogEventService.class); + LoggingAdminGrpcService service = newService(logEventService); + AtomicReference response = new AtomicReference<>(); + AtomicReference error = new AtomicReference<>(); + + invokeWithPeer( + "other", + "account-service", + () -> service.createLogEvent(validCreateRequest(), responseObserver(response, error))); + + assertEquals(Status.Code.PERMISSION_DENIED, Status.fromThrowable(error.get()).getCode()); + verifyNoInteractions(logEventService); + } + + @Test + void receiptReadReturnsCanonicalNotFoundStatus() { + LogEventService logEventService = Mockito.mock(LogEventService.class); + when(logEventService.readLogEventReceipt(any())).thenThrow(new AuditReceiptNotFoundException()); + LoggingAdminGrpcService service = newService(logEventService); + AtomicReference response = new AtomicReference<>(); + AtomicReference error = new AtomicReference<>(); + + invokeWithPeer( + "account-service", + () -> service.readLogEventReceipt(validReadRequest(), responseObserver(response, error))); + + assertEquals(Status.Code.NOT_FOUND, Status.fromThrowable(error.get()).getCode()); + assertNull(response.get()); + } + + @Test + void accountMtlSPeerCanReadTypedReceiptWithoutJwt() { + LogEventService logEventService = Mockito.mock(LogEventService.class); + String digest = digest("{\"accountId\":42}".getBytes(StandardCharsets.UTF_8)); + when(logEventService.readLogEventReceipt(any())) + .thenReturn( + new AccountAuditReceiptDto( + AccountAuditScope.PLATFORM, + null, + "d2719d4f-3b2a-4f64-a994-0f9ccdfdd2b3", + "receipt-1", + 77L, + 1, + 1, + digest, + AccountAuditReceiptStatus.COMMITTED, + AccountAuditReceiptOutcome.DUPLICATE)); + LoggingAdminGrpcService service = newService(logEventService); + AtomicReference response = new AtomicReference<>(); + AtomicReference error = new AtomicReference<>(); + + invokeWithPeer( + "account-service", + () -> service.readLogEventReceipt(validReadRequest(), responseObserver(response, error))); + + assertNotNull(response.get()); + assertEquals("receipt-1", response.get().getReceiptId()); + assertEquals("77", response.get().getLogEventId()); + assertEquals( + net.firedevops.firemud.loggingadmin.v1.AccountAuditReceiptOutcome + .ACCOUNT_AUDIT_RECEIPT_OUTCOME_DUPLICATE, + response.get().getOutcome()); + assertNull(error.get()); + verify(logEventService).readLogEventReceipt(any()); + } + + @Test + void accountMtlsPeerCanReadMinimizedReceiptThroughActualService() { + AccountAuditReceiptRepository repository = Mockito.mock(AccountAuditReceiptRepository.class); + ReadLogEventReceiptRequest wireRequest = validReadRequest().toBuilder().clearPayload().build(); + Instant occurredAt = + Instant.ofEpochSecond( + wireRequest.getOccurredAt().getSeconds(), wireRequest.getOccurredAt().getNanos()); + net.firedevops.firemud.loggingadmin.dto.CreateLogEventRequest serviceRequest = + new net.firedevops.firemud.loggingadmin.dto.CreateLogEventRequest( + AccountAuditScope.PLATFORM, + null, + wireRequest.getAuditEventId(), + wireRequest.getProducerService(), + wireRequest.getEventType(), + occurredAt, + wireRequest.getSchemaVersion(), + wireRequest.getPayload(), + wireRequest.getPayloadDigestVersion(), + wireRequest.getPayloadDigest()); + UUID receiptId = UUID.fromString("c0c1f03b-31b7-4281-aaf8-2d66f29e8770"); + AccountAuditReceipt receipt = + new AccountAuditReceipt( + 91L, + 77L, + receiptId, + "platform", + null, + serviceRequest.auditEventId(), + serviceRequest.producerService(), + serviceRequest.eventType(), + occurredAt.getEpochSecond(), + occurredAt.getNano(), + serviceRequest.schemaVersion(), + serviceRequest.payloadDigestVersion(), + serviceRequest.payloadDigest(), + null, + "MINIMIZED", + "NON_REPLAYABLE"); + when(repository.findByIdentity(serviceRequest, 0L)).thenReturn(Optional.of(receipt)); + LoggingAdminGrpcService service = newService(new LogEventServiceImpl(repository)); + AtomicReference response = new AtomicReference<>(); + AtomicReference error = new AtomicReference<>(); + + invokeWithPeer( + "account-service", + () -> service.readLogEventReceipt(wireRequest, responseObserver(response, error))); + + assertNull(error.get()); + assertNotNull(response.get()); + assertEquals(receiptId.toString(), response.get().getReceiptId()); + assertEquals("77", response.get().getLogEventId()); + assertEquals( + net.firedevops.firemud.loggingadmin.v1.AccountAuditReceiptStatus + .ACCOUNT_AUDIT_RECEIPT_STATUS_MINIMIZED, + response.get().getStatus()); + assertEquals( + net.firedevops.firemud.loggingadmin.v1.AccountAuditReceiptOutcome + .ACCOUNT_AUDIT_RECEIPT_OUTCOME_NON_REPLAYABLE, + response.get().getOutcome()); + verify(repository).findByIdentity(serviceRequest, 0L); + } + + @Test + void receiptReadRejectsWrongMtlsPeerBeforeRepositoryLookup() { + AccountAuditReceiptRepository repository = Mockito.mock(AccountAuditReceiptRepository.class); + LoggingAdminGrpcService service = newService(new LogEventServiceImpl(repository)); + AtomicReference response = new AtomicReference<>(); + AtomicReference error = new AtomicReference<>(); + + invokeWithPeer( + "game-session-service", + () -> service.readLogEventReceipt(validReadRequest(), responseObserver(response, error))); + + assertNull(response.get()); + assertEquals(Status.Code.PERMISSION_DENIED, Status.fromThrowable(error.get()).getCode()); + verifyNoInteractions(repository); } @Test @@ -227,6 +509,56 @@ public void onCompleted() {} verifyNoInteractions(logQueryService); } + @Test + void createLogEventReturnsUnavailableBeforeEnvelopeValidation() { + LogEventService logEventService = Mockito.mock(LogEventService.class); + ModerationService moderationService = Mockito.mock(ModerationService.class); + LoggingAdminGrpcService service = + new LoggingAdminGrpcService( + Mockito.mock(LogQueryService.class), + logEventService, + moderationService, + new SimpleMeterRegistry(), + "firemud"); + + AtomicReference ref = new AtomicReference<>(); + AtomicReference error = new AtomicReference<>(); + java.util.concurrent.atomic.AtomicBoolean completed = + new java.util.concurrent.atomic.AtomicBoolean(); + CreateLogEventRequest request = + validCreateRequest().toBuilder().setPayloadDigestVersion(2).build(); + invokeWithPeer( + "account-service", + () -> + service.createLogEvent( + request, + new StreamObserver<>() { + @Override + public void onNext(CreateLogEventResponse value) { + ref.set(value); + } + + @Override + public void onError(Throwable value) { + error.set(value); + } + + @Override + public void onCompleted() { + completed.set(true); + } + })); + + assertNotNull(error.get()); + assertEquals(Status.Code.UNAVAILABLE, Status.fromThrowable(error.get()).getCode()); + assertNull(ref.get()); + String description = Status.fromThrowable(error.get()).getDescription(); + assertEquals("Account audit ingress is unavailable", description); + assertTrue(description.length() <= 128); + assertFalse(completed.get()); + verifyNoInteractions(logEventService, moderationService); + } + @Test void applyModerationActionRejectsZeroSessionIdBeforeDispatch() { SessionContext.setContext("1", List.of("platformAdmin"), Map.of()); @@ -578,64 +910,113 @@ public void onCompleted() {} verifyNoInteractions(moderationService); } - private static void assertCreateLogEventUnavailable( - CreateLogEventRequest request, LogEventService logEventService) { - ModerationService moderationService = Mockito.mock(ModerationService.class); - LoggingAdminGrpcService service = - new LoggingAdminGrpcService( - Mockito.mock(LogQueryService.class), - logEventService, - moderationService, - new SimpleMeterRegistry()); + private static LoggingAdminGrpcService newService(LogEventService logEventService) { + return new LoggingAdminGrpcService( + Mockito.mock(LogQueryService.class), + logEventService, + Mockito.mock(ModerationService.class), + new SimpleMeterRegistry(), + "firemud"); + } - AtomicReference response = new AtomicReference<>(); - AtomicReference error = new AtomicReference<>(); - java.util.concurrent.atomic.AtomicBoolean completed = - new java.util.concurrent.atomic.AtomicBoolean(); - service.createLogEvent( - request, - new StreamObserver<>() { - @Override - public void onNext(CreateLogEventResponse value) { - response.set(value); - } + private static boolean passesWithoutBearer( + AuthTokenInterceptor interceptor, String fullMethodName) { + MethodDescriptor descriptor = + MethodDescriptor.newBuilder() + .setType(MethodDescriptor.MethodType.UNARY) + .setFullMethodName(fullMethodName) + .setRequestMarshaller(ProtoUtils.marshaller(CreateLogEventRequest.getDefaultInstance())) + .setResponseMarshaller( + ProtoUtils.marshaller(CreateLogEventResponse.getDefaultInstance())) + .build(); + @SuppressWarnings("unchecked") + ServerCall serverCall = + (ServerCall) Mockito.mock(ServerCall.class); + when(serverCall.getMethodDescriptor()).thenReturn(descriptor); + AtomicReference callStarted = new AtomicReference<>(false); + ServerCallHandler next = + (call, headers) -> { + callStarted.set(true); + return new ServerCall.Listener<>() {}; + }; + + interceptor.interceptCall(serverCall, new Metadata(), next); + return callStarted.get(); + } - @Override - public void onError(Throwable throwable) { - error.set(throwable); - } + private static StreamObserver responseObserver( + AtomicReference response, AtomicReference error) { + return new StreamObserver<>() { + @Override + public void onNext(T value) { + response.set(value); + } + + @Override + public void onError(Throwable value) { + error.set(value); + } + + @Override + public void onCompleted() {} + }; + } - @Override - public void onCompleted() { - completed.set(true); - } - }); + private static void invokeWithPeer(String serviceName, Runnable invocation) { + invokeWithPeer("firemud", serviceName, invocation); + } - assertNull(response.get()); - assertNotNull(error.get()); - assertEquals(Status.Code.UNAVAILABLE, Status.fromThrowable(error.get()).getCode()); - String description = Status.fromThrowable(error.get()).getDescription(); - assertEquals( - "Typed account audit receipt receiver is unavailable in this service revision", - description); - assertTrue(description.length() <= 128); - assertFalse(completed.get()); - verifyNoInteractions(logEventService, moderationService); + private static void invokeWithPeer(String namespace, String serviceName, Runnable invocation) { + String uri = "spiffe://firemud/ns/" + namespace + "/sa/" + serviceName; + Context context = + Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, new GrpcPeerIdentity(uri, namespace, serviceName)); + Context previous = context.attach(); + try { + invocation.run(); + } finally { + context.detach(previous); + } } - private static CreateLogEventRequest validCreateLogEventRequest() { - ByteString payload = ByteString.copyFromUtf8("{}"); + private static CreateLogEventRequest validCreateRequest() { + ByteString payload = ByteString.copyFrom("{\"accountId\":42}".getBytes(StandardCharsets.UTF_8)); return CreateLogEventRequest.newBuilder() .setScope( net.firedevops.firemud.loggingadmin.v1.AccountAuditScope.ACCOUNT_AUDIT_SCOPE_PLATFORM) .setAuditEventId("d2719d4f-3b2a-4f64-a994-0f9ccdfdd2b3") .setProducerService("account-service") .setEventType("ACCOUNT_REGISTERED") - .setOccurredAt(Timestamp.newBuilder().setSeconds(1).build()) + .setOccurredAt(Timestamp.newBuilder().setSeconds(1).setNanos(234567890)) .setSchemaVersion(1) .setPayload(payload) .setPayloadDigestVersion(1) - .setPayloadDigest("sha256:44136fa355b3678a1146ad16f7e8649e94fb4fc21fe77e8310c060f61caaff8a") + .setPayloadDigest(digest(payload.toByteArray())) .build(); } + + private static ReadLogEventReceiptRequest validReadRequest() { + CreateLogEventRequest create = validCreateRequest(); + return ReadLogEventReceiptRequest.newBuilder() + .setScope(create.getScope()) + .setAuditEventId(create.getAuditEventId()) + .setProducerService(create.getProducerService()) + .setEventType(create.getEventType()) + .setOccurredAt(create.getOccurredAt()) + .setSchemaVersion(create.getSchemaVersion()) + .setPayload(create.getPayload()) + .setPayloadDigestVersion(create.getPayloadDigestVersion()) + .setPayloadDigest(create.getPayloadDigest()) + .build(); + } + + private static String digest(byte[] payload) { + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(payload)); + } catch (NoSuchAlgorithmException ex) { + throw new IllegalStateException(ex); + } + } } From 4dafc6784764d51c4a68974a847343c4c5aea819 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 1 Nov 2026 06:42:16 +1300 Subject: [PATCH 2/6] Record current Logging receipt held-smoke qualification --- .../implementation-tracking/player-access-and-session.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 f276674b1f..dd20841bf1 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -775,4 +775,4 @@ No competing target state is currently recorded. Future design discussion is req Local receiving work for #2940 preserves the original offline envelope/receipt, scope-qualified bounded projection and exact immutable-tuple/digest owner under the [Logging audit contract](../../architecture/microservices/logging-admin-service/api-contracts.md#account-audit-ingress-and-receipt). Forward Logging migrations V1004–V1007 preserve the existing StartSession and moderation migrations; the donor V2–V5 files are not substituted into current history. Both audit methods require exact same-namespace Account workload identity; `ReadLogEventReceipt` supplies the read adapter, while Create authenticates and returns `UNAVAILABLE` before storage. Account delivery remains directly fixture-callable but is not automatically scheduled. No hardcoded audit projection-version marker is imported into the canonical proto or treated as historical evidence. -R1419 passes 70 fresh selected cases (49 Logging units, fifteen application/PostgreSQL cases and six Account delivery cases), including exact retry/conflict, scope isolation, projection/receipt rollback, concurrent deduplication and retained-row forward-migration constraints. Seven additional physical loopback mTLS cases pass with the actual selected JWT interceptor and certificate-derived peer identity; their receipt owner is mocked, so they prove caller/method isolation rather than durable storage. Owning jOOQ generation, enabled main/unit/integration static analysis, full Java formatting and documentation checks pass, together with 229 authorization-matrix cases, source/image Compose mTLS and hosted-manifest contracts and scoped ShellCheck. The initial test aggregate left static tasks disabled; the subsequent `fullCheck` run executes and passes them. Fresh source-built runtime proof remains pending. Positive storage fixtures do not prove authenticated production writes, Account exact readback or guarded historical evidence recording. Live write/scheduling restoration requires the genuine producer/receiver chain and owning retention/cleanup gates; no new release, cleanup, production or registration authority is supplied. +R1419 passes 70 fresh selected cases (49 Logging units, fifteen application/PostgreSQL cases and six Account delivery cases), including exact retry/conflict, scope isolation, projection/receipt rollback, concurrent deduplication and retained-row forward-migration constraints. Seven additional physical loopback mTLS cases pass with the actual selected JWT interceptor and certificate-derived peer identity; their receipt owner is mocked, so they prove caller/method isolation rather than durable storage. Owning jOOQ generation, enabled main/unit/integration static analysis, full Java formatting and documentation checks pass, together with 229 authorization-matrix cases, source/image Compose mTLS and hosted-manifest contracts and scoped ShellCheck. The initial test aggregate left static tasks disabled; the subsequent `fullCheck` run executes and passes them. After carrying #3367 parent `0d47422f71b1ea4a405f1b58838b60cf3952557e`, fresh source-built held-admission smoke at `5f6600c3a096b36ed459f73bfec6ff747c5c34ad` passes the backend LOGIN → PLAY → LOOK flow and Gateway/Telnet denial qualification. Authenticated teardown and independent exact-project container, network and volume absence checks pass. This boots the new Logging storage/auth composition and retains the local credential fixture; audit writes remain disabled and successful public admission is not proved. Positive storage fixtures do not prove authenticated production writes, Account exact readback or guarded historical evidence recording. Live write/scheduling restoration requires the genuine producer/receiver chain and owning retention/cleanup gates; no new release, cleanup, production or registration authority is supplied. From efbce68d26cf688308ca58e877e3dc8fef98b818 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 1 Nov 2026 06:43:47 +1300 Subject: [PATCH 3/6] Record normal completion of pending CI proof attribution --- design/project-management/ai-observations.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 8d2d682b34..c506fafbe4 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -15,4 +15,4 @@ A small inbox for unresolved agent, tooling, environment, and workflow issues; s - A read-only helper correctly refused its supplied external proof directory. Root copied and hash-verified the authorized inputs inside the worktree, without changing permissions, then resumed it. The reply command help omitted the required JSON array-of-string-arrays shape, so Root read its validator to construct the response. Next: add a concise help example in the owning API wrapper; this was reported to Overseer and is not a repository runtime blocker. - `2026-11-01` (Pacific/Auckland): CI wait pending-status attribution requires separate provider reads. - - On #3365, the successful Validation CheckRun coexisted with a pending same-name status linked to a later metadata run, while the actual substantive Validation run was still active. Root incorrectly reported a barrier failure before locating that run and corrected Overseer immediately. CI wait named the conflicting status but omitted its description and target URL, requiring separate provider reads to establish attribution. Next: expose those bounded attribution fields in the owning controller diagnostic; reported to FireController Worker. Pending is not evidence that CI failed. + - On #3365, the successful Validation CheckRun coexisted with a pending same-name status linked to a later metadata run, while the actual substantive Validation run was still active. Root incorrectly reported a barrier failure before locating that run and corrected Overseer immediately. CI wait named the conflicting status but omitted its description and target URL, requiring separate provider reads to establish attribution. Next: expose those bounded attribution fields in the owning controller diagnostic; reported to FireController Worker. Pending is not evidence that CI failed. Outcome at 6:41am NZDT: the original full Validation completed and all five gates passed; the barrier cleared normally without repair or rerun. The remaining request is diagnostic attribution only. From 92c56e659e95f0fcc5c71f754d876ea34c14e47a Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 1 Nov 2026 11:06:45 +1300 Subject: [PATCH 4/6] Align audit receiving status and canonical authentication documentation --- .../microservices/logging-admin-service/configuration.md | 2 +- .../implementation-tracking/player-access-and-session.md | 2 +- .../shared-runtime-contracts-and-persistence.md | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/design/architecture/microservices/logging-admin-service/configuration.md b/design/architecture/microservices/logging-admin-service/configuration.md index 165f48910e..ebba5a40a0 100644 --- a/design/architecture/microservices/logging-admin-service/configuration.md +++ b/design/architecture/microservices/logging-admin-service/configuration.md @@ -39,7 +39,7 @@ Enabled composition requires a canonical `firemud.grpc.workload-namespace` and r This configuration creates no external operator route, trusted caller context, reservation provider, or gameplay activation. The focused configuration test uses a controlled channel factory and test-only placeholder files; it is wiring proof only, not physical mTLS, production startup, external-ingress, Game Session launch-selection, or World activation proof. -`logging_admin.v1.StartSessionReservationEvidenceService/ReadCurrentClaimEvidence` is the only method exempted from the shared Bearer-JWT interceptor. The server's required client-certificate handshake and verified TLS peer interceptor remain enabled. The receiver requires both the exact Account SPIFFE identity in `FIREMUD_GRPC_WORKLOAD_NAMESPACE` and approval of the SHA-256 fingerprint derived from the presented TLS leaf. It reads the configured file for each request; a missing path, read failure, malformed file, or unapproved leaf denies the request before reservation access. The JWT header is not an identity source for this method. +The shared Bearer-JWT interceptor exempts `logging_admin.v1.LoggingAdminService/CreateLogEvent`, `logging_admin.v1.LoggingAdminService/ReadLogEventReceipt`, and `logging_admin.v1.StartSessionReservationEvidenceService/ReadCurrentClaimEvidence`; each uses certificate-derived Account workload identity instead of JWT caller identity. The server's required client-certificate handshake and verified TLS peer interceptor remain enabled. The reservation-evidence receiver additionally requires both the exact Account SPIFFE identity in `FIREMUD_GRPC_WORKLOAD_NAMESPACE` and approval of the SHA-256 fingerprint derived from the presented TLS leaf. It reads the configured file for each request; a missing path, read failure, malformed file, or unapproved leaf denies the request before reservation access. The JWT header is not an identity source for this method. The file is a protected server-owned input mounted read-only for Logging & Admin. It contains exactly one required `active=<64 lowercase hexadecimal SHA-256>` line and may contain one `overlap=<64 lowercase hexadecimal SHA-256>;expires-at=` line after it. The entries must name distinct leaves. Blank lines, comments, extra entries, duplicate leaves, uppercase or malformed fingerprints, non-absolute paths, and malformed expiry values are rejected. The overlap leaf is accepted only before its absolute expiry time as evaluated by the Logging & Admin host clock; the two-entry limit bounds overlap to one active and one retiring leaf. Replace the file atomically to rotate or revoke approval: publish a new active leaf with the prior leaf as overlap and an explicit deadline, then replace it with the new active leaf alone; immediate revocation replaces the file without the affected fingerprint. Provisioning and custody of this file, including rotation updates, are environment responsibilities and are not supplied or proven by this code change. No production leaf approval or live rotation is claimed. 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 81ca8f7e8a..96c9847dfa 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -682,7 +682,7 @@ Equivalent HTTP, WebSocket, and gRPC failures use stable boundary semantics. The ### Logging Account audit receiving preparation -Local receiving work for #2940 preserves the original offline envelope/receipt, scope-qualified bounded projection and exact immutable-tuple/digest owner under the [Logging audit contract](../../architecture/microservices/logging-admin-service/api-contracts.md#account-audit-ingress-and-receipt). Forward Logging migrations V1004–V1007 preserve the existing StartSession and moderation migrations; the donor V2–V5 files are not substituted into current history. Both audit methods require exact same-namespace Account workload identity; `ReadLogEventReceipt` supplies the read adapter, while Create authenticates and returns `UNAVAILABLE` before storage. Account delivery remains directly fixture-callable but is not automatically scheduled. No hardcoded audit projection-version marker is imported into the canonical proto or treated as historical evidence. +Local receiving preparation for #2940 follows the [Logging audit contract](../../architecture/microservices/logging-admin-service/api-contracts.md#account-audit-ingress-and-receipt). It preserves the offline envelope/receipt, scope-qualified bounded projection and immutable tuple/digest owner. Forward Logging migrations V1004–V1007 retain existing StartSession and moderation history; donor V2–V5 files are not substituted. The read adapter is present, Create remains unavailable before storage, and Account delivery remains fixture-callable but unscheduled. No hardcoded projection-version marker is imported into the canonical proto or treated as historical evidence. R1419 passes 70 fresh selected cases (49 Logging units, fifteen application/PostgreSQL cases and six Account delivery cases), including exact retry/conflict, scope isolation, projection/receipt rollback, concurrent deduplication and retained-row forward-migration constraints. Seven additional physical loopback mTLS cases pass with the actual selected JWT interceptor and certificate-derived peer identity; their receipt owner is mocked, so they prove caller/method isolation rather than durable storage. Owning jOOQ generation, enabled main/unit/integration static analysis, full Java formatting and documentation checks pass, together with 229 authorization-matrix cases, source/image Compose mTLS and hosted-manifest contracts and scoped ShellCheck. The initial test aggregate left static tasks disabled; the subsequent `fullCheck` run executes and passes them. After carrying #3367 parent `0d47422f71b1ea4a405f1b58838b60cf3952557e`, fresh source-built held-admission smoke at `5f6600c3a096b36ed459f73bfec6ff747c5c34ad` passes the backend LOGIN → PLAY → LOOK flow and Gateway/Telnet denial qualification. Authenticated teardown and independent exact-project container, network and volume absence checks pass. This boots the new Logging storage/auth composition and retains the local credential fixture; audit writes remain disabled and successful public admission is not proved. Positive storage fixtures do not prove authenticated production writes, Account exact readback or guarded historical evidence recording. Live write/scheduling restoration requires the genuine producer/receiver chain and owning retention/cleanup gates; no new release, cleanup, production or registration authority is supplied. diff --git a/design/project-management/implementation-tracking/shared-runtime-contracts-and-persistence.md b/design/project-management/implementation-tracking/shared-runtime-contracts-and-persistence.md index dacd139eed..a82cac5726 100644 --- a/design/project-management/implementation-tracking/shared-runtime-contracts-and-persistence.md +++ b/design/project-management/implementation-tracking/shared-runtime-contracts-and-persistence.md @@ -156,7 +156,7 @@ All current SQL-backed business services have no Spring Data JPA repository surf - Game Session: **live/partial** admission pointers/audit, prepared upgrades, feature flags, manifests, game instances, and current per-instance script pin/epoch state, gameplay commands, runtime region status, tick batches/effects, and remote follow-up/result/coordinator records; **target/partial** durable pin-transition workflow record and append-only script rollout-history remain incomplete. The target `ScriptPatchPinChanged` is an advisory reread wake-up, and the target `ScriptPinConvergenceTimedOut` is a named durable producer consequence captured with the timeout transition; neither notification/event producer path nor complete workflow/history capture is currently proven. Complete cross-service tuple propagation remains incomplete. The workflow record's target/partial status is owned by [Rollout and Rollback](../../architecture/system-architecture-scripting-rollout-and-rollback.md#pin-transition-orchestration-state-machine-required). - Game Design: versions/games/templates/assets, revisions, settings overrides, remap sets/entries, publication attempts and participant digests, release bundles, launch descriptors, asset purge workflows, and plugin publication/status rows. - Entity Management: characters, items, NPCs, actor state/conditions/resources, equipment/body layouts, friends, visible-reference counters, transfer audit, item/container/stack instances, inventory/equipment/room-ground projections, crafting recipes, and mutation-effect replay state. -- Logging & Admin: **current** log events and moderation-policy reads; **target-only/unavailable** player-report persistence; **gated/unavailable** moderation actions; and **target-only** policy intent and bounded appeal case/evidence persistence with no current appeal repository, entity, or schema. Its current log-event repository and unsupported moderation/report seams use shared timestamp helpers. It is not the enforcement owner for Account, Game Session, or Social & Groups restrictions. +- Logging & Admin: **current** log events and moderation-policy reads; **partial/offline** Account audit receipt/projection storage and authenticated readback, with live audit ingress and automatic Account delivery disabled; **target-only/unavailable** player-report persistence; **gated/unavailable** moderation actions; and **target-only** policy intent and bounded appeal case/evidence persistence with no current appeal repository, entity, or schema. Its current log-event repository and unsupported moderation/report seams use shared timestamp helpers. It is not the enforcement owner for Account, Game Session, or Social & Groups restrictions. - World Management: generation rules, authored topology and exits, design scope/epoch/revision ledger, spawn bindings, runtime world/region/zone/room instances and exits, and world-event history. - Social & Groups: account-scoped friends, guilds/members/storage/alliances, chat persistence and effect-id replay lookup, and mail messages. From d6dbedf0f4bd58faac42bc811e26c5a81a519bc5 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 1 Nov 2026 12:10:54 +1300 Subject: [PATCH 5/6] test: prove audit RPC denial without workload namespace --- .../impl/LoggingAdminGrpcServiceAuthTest.java | 34 +++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/LoggingAdminGrpcServiceAuthTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/LoggingAdminGrpcServiceAuthTest.java index 7fc06eeada..f41f8635aa 100644 --- a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/LoggingAdminGrpcServiceAuthTest.java +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/LoggingAdminGrpcServiceAuthTest.java @@ -241,6 +241,40 @@ void accountAuditRejectsAccountServicePeerFromOtherNamespace() { verifyNoInteractions(logEventService); } + @Test + void accountAuditDeniesBothMethodsWhenWorkloadNamespaceIsNullOrBlank() { + for (String namespace : new String[] {null, "", " "}) { + LogEventService logEventService = Mockito.mock(LogEventService.class); + LoggingAdminGrpcService service = + new LoggingAdminGrpcService( + Mockito.mock(LogQueryService.class), + logEventService, + Mockito.mock(ModerationService.class), + new SimpleMeterRegistry(), + namespace); + AtomicReference createResponse = new AtomicReference<>(); + AtomicReference createError = new AtomicReference<>(); + AtomicReference readResponse = new AtomicReference<>(); + AtomicReference readError = new AtomicReference<>(); + + invokeWithPeer( + "account-service", + () -> { + service.createLogEvent( + validCreateRequest(), responseObserver(createResponse, createError)); + service.readLogEventReceipt( + validReadRequest(), responseObserver(readResponse, readError)); + }); + + assertEquals( + Status.Code.PERMISSION_DENIED, Status.fromThrowable(createError.get()).getCode()); + assertEquals(Status.Code.PERMISSION_DENIED, Status.fromThrowable(readError.get()).getCode()); + assertNull(createResponse.get()); + assertNull(readResponse.get()); + verifyNoInteractions(logEventService); + } + } + @Test void receiptReadReturnsCanonicalNotFoundStatus() { LogEventService logEventService = Mockito.mock(LogEventService.class); From 1454cb4c206a8fd5cc6324b7baa1447f4f7ce092 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 1 Nov 2026 13:16:28 +1300 Subject: [PATCH 6/6] Document audit projection migration lock lifetime --- .../microservices/logging-admin-service/runtime-and-data.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/design/architecture/microservices/logging-admin-service/runtime-and-data.md b/design/architecture/microservices/logging-admin-service/runtime-and-data.md index 738f60ea65..bbf21fa335 100644 --- a/design/architecture/microservices/logging-admin-service/runtime-and-data.md +++ b/design/architecture/microservices/logging-admin-service/runtime-and-data.md @@ -12,6 +12,8 @@ Logging & Admin is the operator-facing policy, audit, and observability coordina Local receipt/projection storage preparation and authenticated readback are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#logging-account-audit-receiving-preparation). The live Create RPC remains unavailable before storage, Account delivery is not automatically scheduled, and this preparation supplies no retention cleanup, historical provenance upgrade or Account recovery authority. +Migration `V1005` validates its constraints, builds an ordinary unique index, and backfills the audit projection in one Flyway transaction; acquired table locks remain held until commit. The current migration proof uses quiescent fixtures and does not establish an online-rollout guarantee. + ### Audit envelope and receipt retention The Account audit envelope/receipt is a Logging & Admin-owned **retry and idempotency receipt** plus **purpose-bound audit evidence** family under [ADR 0163](../../decisions/adr-0163-service-owned-retention-classes-with-cross-service-safety.md). The full retry-equivalence tuple and exact payload bytes remain durable through the longest applicable producer retry, receiver readback, duplicate-delivery, and reconciliation horizon, using existing canonical/configured horizons and the applicable legal-hold and erasure-owner links; this service does not invent a duplicate duration. After the producer safe watermark proves that horizon has ended and no legal hold or unresolved reconciliation reference remains, the payload may be minimized or removed, but the receipt retains `scope`, the applicable `tenantId`, `auditEventId`, `producerService`, `eventType`, `occurredAt`, `schemaVersion`, `payloadDigestVersion`, `payloadDigest`, `receiptId`, `logEventId`, terminal `status`/`outcome`, and the source/lineage identifiers needed for later exact proof. A late `CreateLogEvent` retry or `ReadLogEventReceipt` request after minimization is an explicit terminal non-replayable result, never an accepted duplicate or an exact successful readback; the retained digest and receipt metadata must not be presented as proof of exact payload equality. Garbage collection requires terminality, the safe watermark, no pending or ambiguous delivery/readback reference, and no legal hold; age alone is never sufficient. Missing, stale, conflicting, or unavailable evidence while any of those gates may still apply fails closed and cannot authorize deletion or a new event under the old identity.