From 2c132503e2d9b55fb93a4458443ed4fbbfeeb7b6 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 7 Oct 2026 05:48:27 +1300 Subject: [PATCH 1/9] feat(account): preserve tenant authority source and entitlement receipts --- .../account-service/runtime-and-data.md | 2 + .../player-access-and-session.md | 6 + .../DemoTenantEntitlementEventV1Codec.java | 435 +++++++++++++ .../dto/DemoTenantEntitlementRequest.java | 121 ++++ .../dto/DemoTenantEntitlementSnapshot.java | 87 +++ .../dto/TenantAuthorityEventV1Codec.java | 427 +++++++++++++ ...ccountDemoTenantEntitlementRepository.java | 542 ++++++++++++++++ ...AccountTenantAuthorityEventRepository.java | 576 ++++++++++++++++++ ...ountTenantEntitlementOutboxRepository.java | 207 +++++++ .../DemoTenantEntitlementException.java | 31 + ...3__account_protected_demo_entitlements.sql | 427 +++++++++++++ ...account_tenant_authority_source_bridge.sql | 471 ++++++++++++++ ...EntitlementPersistenceIntegrationTest.java | 551 +++++++++++++++++ .../dto/DemoTenantEntitlementCodecTest.java | 207 +++++++ .../dto/TenantAuthorityEventV1CodecTest.java | 88 +++ 15 files changed, 4178 insertions(+) create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/DemoTenantEntitlementEventV1Codec.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/DemoTenantEntitlementRequest.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/DemoTenantEntitlementSnapshot.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/TenantAuthorityEventV1Codec.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementRepository.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepository.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantEntitlementOutboxRepository.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/DemoTenantEntitlementException.java create mode 100644 services/account-service/src/main/resources/db/migration/V53__account_protected_demo_entitlements.sql create mode 100644 services/account-service/src/main/resources/db/migration/V73__account_tenant_authority_source_bridge.sql create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementPersistenceIntegrationTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/DemoTenantEntitlementCodecTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/TenantAuthorityEventV1CodecTest.java diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index 9e8bf02bec..4336430cb0 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -8,6 +8,8 @@ Account owns platform identity, hosted Creator Party/operator and terms currentn ## Implementation Status +The source-only tenant-authority foundation adds Account-local non-paid entitlement storage, its immutable billing outbox, and typed tenant-authority source/current-checkpoint owners. It imports no public provisioning facade, operational activation, credential release, or gameplay admission. Physical PostgreSQL and runtime proof remain pending; see the [tenant-authority source foundation status](../../../project-management/implementation-tracking/player-access-and-session.md#account-tenant-authority-source-foundation). + Account V40 adds owner-proven sequence-zero source baselines to the inherited V30–V39 authority-storage and retention-safety foundation. New repository-created Accounts and a genuinely new issuer receive these baselines; retained rows are not backfilled. Exact security-relevant Account updates compose source generation, issuance fence, canonical event, and current readback in their owner transaction. The owner-local first-JOIN producer/coordinator retains membership, pair/event, audit, and terminal-operation evidence. These persistence primitives do not provide public JOIN, target-currentness protection, or runtime wiring. Reconciled V40/source-currentness/coordinator proof remains pending; see the [Player Access and Session implementation tracker](../../../project-management/implementation-tracking/player-access-and-session.md#current-status). Hard deletion remains denied, revoked grants remain tombstones, and this stage does not enable signer provisioning, LOGIN, PLAY, or activation. Account V29 persists immutable, unique, non-nil `account_uuid` values with provenance and the unchanged numeric source-row id. Registration REST/gRPC and the Account component of the current Account/profile-local and legacy tenant exports expose that persisted UUID through `AccountDto.id`; the mapper requires a non-nil UUID, provenance, and an exact positive source-row match. Repository insert/readback checks remain the persistence boundary, and new registration audit payloads use the same UUID. Profile and tenant DTO identifiers, authentication results, JWT subjects, and downstream consumers remain unchanged; the current export is still partial Account/profile-local data, not the canonical portable export. The Account-local UUID-to-row resolver also remains confined to Account. The closed consumer boundary is incomplete: shared `SessionContext.currentAccountIdOrNull()` still requires numeric claims and is used by `GrpcClientAuth`, Logging & Admin `SessionActorReaders`, Automation Scripting `ScriptEventIngressServiceImpl`, and Social & Groups current-account authorization; Game Session control-plane owner authorization also compares numeric owner IDs. These consumers are outside this Account-owned slice, so no UUID-authentication or downstream-consumer proof is claimed. Focused repository and retained-row migration integration cases are present, but local PostgreSQL execution is unavailable while Docker is disabled; [ADR 0020](../../decisions/adr-0020-scoped-domain-and-operational-identifiers.md) remains the identifier authority. 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 8b8f9f1bdc..6a941177ec 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -29,6 +29,12 @@ Smoke identity consequence: the current demo-credential `LOGIN -> PLAY -> LOOK` SEC-04 does not move player session ownership into Logging & Admin. Game Session `/sessions*` lifecycle routes remain current owner-local hooks with direct owner edge exposure denied; the target external operator path forwards from Logging & Admin to Game Session after Account issues the authorization reference and the receiving Game Session redeems that same reference. That target lifecycle family, and other operator mutation families gated by action schemas, shared `mutationDigest/v1` vectors, and the authorization-reference flow, are not currently available to players or operators. +## Account Tenant Authority Source Foundation + +The Account-local tenant-source prerequisite consists of V53's explicit non-paid entitlement operation/current-head and immutable billing outbox storage, V73's typed head over the existing authority outbox, the corresponding source repositories and closed codecs, and focused codec/PostgreSQL source tests. It reuses the inherited fresh-tenant association, canonical tenant claim, authority generation/outbox, V40 provenance, and run-owned PostgreSQL fixture owners. Retained tenant rows are not assigned fabricated initialization provenance; complete billing and authority receipts remain correlated by the existing SQL guards. This is a persistence/source prerequisite for later selected-authority projection, not public entitlement provisioning or an admission decision; canonical local ownership remains in [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md). + +The 13 implementation/test files are transferred unchanged from the composed Account source work. Independent Gradle proof on this extracted prerequisite passed Java compilation, jOOQ schema interpretation, five codec unit cases with zero failures/errors/skips, integration-source compilation, the Account boot JAR, and documentation checks. Physical PostgreSQL migration, retained-data, restart, and owner-read proof are not claimed: local Docker and the remote fixture are unavailable under the current environment authorization. No public route, provisioning service/configuration, LOGIN/PLAY activation, credential release, or cross-service currentness-through-effect proof is included, and tracked player-admission capability is unchanged. + ## Packet 4 Status and Proof Gaps - `AA-2.1` / `AA-2.2` / `AA-3.3`: [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md) remains the canonical target link for stable namespace-aware selection, admission, reconnect, and runtime replacement; [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md) owns namespace-scoped controller identity, uniqueness, takeover, and binding-generation fencing. Existing account/session and realm-routing evidence remains partial and does not prove namespace-aware atomic takeover, replacement, or cleanup behavior. diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/DemoTenantEntitlementEventV1Codec.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/DemoTenantEntitlementEventV1Codec.java new file mode 100644 index 0000000000..e5a77be1b4 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/DemoTenantEntitlementEventV1Codec.java @@ -0,0 +1,435 @@ +package net.firedevops.firemud.accountservice.dto; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.accountservice.repository.AccountTenantEntitlementOutboxRepository; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.core.type.TypeReference; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.json.JsonMapper; + +/** Closed canonical Account event encoding for explicit non-paid demo entitlements. */ +public final class DemoTenantEntitlementEventV1Codec { + public static final String SCHEMA_VERSION = "account-tenant-entitlement-event/v1"; + public static final String EVENT_TYPE = "TENANT_ENTITLEMENT_CHANGED"; + + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final Set EVENT_FIELDS = + Set.of( + "schemaVersion", + "eventType", + "eventId", + "requestId", + "requestDigest", + "outboxStreamKey", + "tenantId", + "tenantBillingSequence", + "tenantAuthorityGeneration", + "tenantAuthoritySourceVersion", + "entitlementVersion", + "entitlementKind", + "status", + "subscriptionStatus", + "paid", + "gameplayAvailable", + "allowPublicJoin", + "allowNewGameplayBindings", + "allowNewInstanceStarts", + "quotas", + "sourceEvidence", + "eventDigest"); + private static final Set QUOTA_FIELDS = + Set.of("maxActiveSessions", "maxConcurrentGameInstances", "maxStorageBytes"); + private static final java.util.regex.Pattern DIGEST = + java.util.regex.Pattern.compile("sha256:[0-9a-f]{64}"); + private static final Pattern POSITIVE_DECIMAL = Pattern.compile("[1-9][0-9]{0,18}"); + private static final Pattern NONNEGATIVE_DECIMAL = Pattern.compile("(?:0|[1-9][0-9]{0,18})"); + private static final Set SOURCE_FIELDS = + Set.of( + "schemaVersion", + "targetNamespace", + "creationRequestId", + "operationId", + "requestDigest", + "canonicalTenantId", + "sourceGameRowId", + "sourceGameTenantKey", + "provenanceKind", + "evidenceDigest"); + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + private DemoTenantEntitlementEventV1Codec() {} + + public static Event seal( + DemoTenantEntitlementRequest request, + FreshTenantCreationEvidence source, + long entitlementVersion, + long tenantAuthorityGeneration, + long tenantAuthoritySourceVersion, + long tenantBillingSequence) { + if (request == null || source == null) { + throw new IllegalArgumentException( + "Demo entitlement request and source evidence are required"); + } + if (!request.canonicalTenantId().equals(source.canonicalTenantId()) + || !request.tenantCreationRequestId().equals(source.creationRequestId()) + || !request.tenantCreationRequestDigest().equals(source.requestDigest())) { + throw new IllegalArgumentException( + "Demo entitlement event source differs from exact request"); + } + UUID eventId = eventId(request.requestId()); + String streamKey = + AccountTenantEntitlementOutboxRepository.streamKey(request.canonicalTenantId()); + Map preimage = + eventFields( + request, + source, + entitlementVersion, + tenantAuthorityGeneration, + tenantAuthoritySourceVersion, + tenantBillingSequence, + eventId, + streamKey); + String digest = digest(canonical(preimage)); + Map wire = new LinkedHashMap<>(preimage); + wire.put("eventDigest", digest); + byte[] payload = canonical(wire); + return new Event( + request.requestId(), + request.requestDigest(), + request.canonicalTenantId(), + source, + entitlementVersion, + tenantAuthorityGeneration, + tenantAuthoritySourceVersion, + tenantBillingSequence, + request.gameplayAvailable(), + request.allowPublicJoin(), + request.allowNewGameplayBindings(), + request.allowNewInstanceStarts(), + request.quotas(), + eventId, + streamKey, + digest, + payload); + } + + /** Parses and verifies the exact canonical event payload stored in Account's outbox. */ + public static Event verify(byte[] payload) { + if (payload == null || payload.length == 0 || payload.length > 32 * 1024) { + throw new IllegalArgumentException("Demo entitlement event payload is absent or oversized"); + } + final Map wire; + try { + wire = JSON.readValue(payload, new TypeReference<>() {}); + } catch (RuntimeException exception) { + throw new IllegalArgumentException("Demo entitlement event payload is malformed", exception); + } + if (!wire.keySet().equals(EVENT_FIELDS)) { + throw new IllegalArgumentException("Demo entitlement event fields are incomplete or unknown"); + } + String claimedDigest = text(wire.get("eventDigest"), "eventDigest"); + Map preimage = new LinkedHashMap<>(wire); + preimage.remove("eventDigest"); + byte[] canonicalPreimage = canonical(preimage); + if (!claimedDigest.equals(digest(canonicalPreimage))) { + throw new IllegalArgumentException( + "Demo entitlement event digest does not match its payload"); + } + if (!java.util.Arrays.equals(payload, canonical(wire))) { + throw new IllegalArgumentException("Demo entitlement event payload is not canonical JSON"); + } + + UUID tenantId = uuid(wire.get("tenantId"), "tenantId"); + UUID requestId = uuid(wire.get("requestId"), "requestId"); + UUID actualEventId = uuid(wire.get("eventId"), "eventId"); + String streamKey = text(wire.get("outboxStreamKey"), "outboxStreamKey"); + if (!SCHEMA_VERSION.equals(wire.get("schemaVersion")) + || !EVENT_TYPE.equals(wire.get("eventType")) + || !"NON_PAID_DEMO".equals(wire.get("entitlementKind")) + || !"ACTIVE".equals(wire.get("status")) + || wire.get("subscriptionStatus") != null + || !Boolean.FALSE.equals(wire.get("paid")) + || !DIGEST.matcher(text(wire.get("requestDigest"), "requestDigest")).matches() + || !eventId(requestId).equals(actualEventId) + || !AccountTenantEntitlementOutboxRepository.streamKey(tenantId).equals(streamKey)) { + throw new IllegalArgumentException( + "Demo entitlement event identity or non-paid state is invalid"); + } + + Map sourceMap = object(wire.get("sourceEvidence"), "sourceEvidence"); + if (!sourceMap.keySet().equals(SOURCE_FIELDS)) { + throw new IllegalArgumentException("Demo entitlement source evidence fields are incomplete"); + } + FreshTenantCreationEvidence source = + new FreshTenantCreationEvidence( + integer(sourceMap.get("schemaVersion"), "source schemaVersion"), + text(sourceMap.get("targetNamespace"), "source targetNamespace"), + uuid(sourceMap.get("creationRequestId"), "source creationRequestId"), + uuid(sourceMap.get("operationId"), "source operationId"), + text(sourceMap.get("requestDigest"), "source requestDigest"), + uuid(sourceMap.get("canonicalTenantId"), "source canonicalTenantId"), + positiveDecimal(sourceMap.get("sourceGameRowId"), "source sourceGameRowId"), + text(sourceMap.get("sourceGameTenantKey"), "source sourceGameTenantKey"), + text(sourceMap.get("provenanceKind"), "source provenanceKind"), + text(sourceMap.get("evidenceDigest"), "source evidenceDigest")); + if (!tenantId.equals(source.canonicalTenantId())) { + throw new IllegalArgumentException("Demo entitlement event source targets another tenant"); + } + + Map quotaMap = object(wire.get("quotas"), "quotas"); + if (!quotaMap.keySet().equals(QUOTA_FIELDS)) { + throw new IllegalArgumentException("Demo entitlement event quota fields are incomplete"); + } + DemoTenantEntitlementRequest.Quotas quotas = + new DemoTenantEntitlementRequest.Quotas( + nonnegativeDecimal(quotaMap.get("maxActiveSessions"), "maxActiveSessions"), + nonnegativeDecimal( + quotaMap.get("maxConcurrentGameInstances"), "maxConcurrentGameInstances"), + nonnegativeDecimal(quotaMap.get("maxStorageBytes"), "maxStorageBytes")); + + return new Event( + requestId, + text(wire.get("requestDigest"), "requestDigest"), + tenantId, + source, + positiveDecimal(wire.get("entitlementVersion"), "entitlementVersion"), + positiveDecimal(wire.get("tenantAuthorityGeneration"), "tenantAuthorityGeneration"), + positiveDecimal(wire.get("tenantAuthoritySourceVersion"), "tenantAuthoritySourceVersion"), + positiveDecimal(wire.get("tenantBillingSequence"), "tenantBillingSequence"), + bool(wire.get("gameplayAvailable"), "gameplayAvailable"), + bool(wire.get("allowPublicJoin"), "allowPublicJoin"), + bool(wire.get("allowNewGameplayBindings"), "allowNewGameplayBindings"), + bool(wire.get("allowNewInstanceStarts"), "allowNewInstanceStarts"), + quotas, + actualEventId, + streamKey, + claimedDigest, + payload); + } + + public static UUID eventId(UUID requestId) { + if (requestId == null || NIL_UUID.equals(requestId)) { + throw new IllegalArgumentException("Demo entitlement request ID is required"); + } + return UUID.nameUUIDFromBytes( + (SCHEMA_VERSION + ":" + requestId).getBytes(StandardCharsets.UTF_8)); + } + + private static Map eventFields( + DemoTenantEntitlementRequest request, + FreshTenantCreationEvidence source, + long entitlementVersion, + long tenantAuthorityGeneration, + long tenantAuthoritySourceVersion, + long tenantBillingSequence, + UUID eventId, + String streamKey) { + if (entitlementVersion <= 0 + || tenantAuthorityGeneration <= 0 + || tenantAuthoritySourceVersion <= 0 + || tenantBillingSequence <= 0) { + throw new IllegalArgumentException("Demo entitlement event versions must be positive"); + } + Map fields = new LinkedHashMap<>(); + fields.put("schemaVersion", SCHEMA_VERSION); + fields.put("eventType", EVENT_TYPE); + fields.put("eventId", eventId.toString()); + fields.put("requestId", request.requestId().toString()); + fields.put("requestDigest", request.requestDigest()); + fields.put("outboxStreamKey", streamKey); + fields.put("tenantId", request.canonicalTenantId().toString()); + fields.put("tenantBillingSequence", Long.toString(tenantBillingSequence)); + fields.put("tenantAuthorityGeneration", Long.toString(tenantAuthorityGeneration)); + fields.put("tenantAuthoritySourceVersion", Long.toString(tenantAuthoritySourceVersion)); + fields.put("entitlementVersion", Long.toString(entitlementVersion)); + fields.put("entitlementKind", "NON_PAID_DEMO"); + fields.put("status", "ACTIVE"); + fields.put("subscriptionStatus", null); + fields.put("paid", false); + fields.put("gameplayAvailable", request.gameplayAvailable()); + fields.put("allowPublicJoin", request.allowPublicJoin()); + fields.put("allowNewGameplayBindings", request.allowNewGameplayBindings()); + fields.put("allowNewInstanceStarts", request.allowNewInstanceStarts()); + fields.put("quotas", quotaFields(request.quotas())); + fields.put("sourceEvidence", sourceFields(source)); + return fields; + } + + private static Map sourceFields(FreshTenantCreationEvidence source) { + Map fields = new LinkedHashMap<>(); + fields.put("schemaVersion", source.schemaVersion()); + fields.put("targetNamespace", source.targetNamespace()); + fields.put("creationRequestId", source.creationRequestId().toString()); + fields.put("operationId", source.operationId().toString()); + fields.put("requestDigest", source.requestDigest()); + fields.put("canonicalTenantId", source.canonicalTenantId().toString()); + fields.put("sourceGameRowId", Long.toString(source.sourceGameRowId())); + fields.put("sourceGameTenantKey", source.sourceGameTenantKey()); + fields.put("provenanceKind", source.provenanceKind()); + fields.put("evidenceDigest", source.evidenceDigest()); + return fields; + } + + private static byte[] canonical(Object value) { + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } catch (IOException | RuntimeException exception) { + throw new IllegalStateException( + "Demo entitlement event could not be canonicalized", exception); + } + } + + private static String digest(byte[] value) { + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value)); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + @SuppressWarnings("unchecked") + private static Map object(Object value, String field) { + if (!(value instanceof Map raw)) { + throw new IllegalArgumentException("Demo entitlement event " + field + " must be an object"); + } + for (Object key : raw.keySet()) { + if (!(key instanceof String)) { + throw new IllegalArgumentException("Demo entitlement event " + field + " has invalid keys"); + } + } + return (Map) raw; + } + + private static String text(Object value, String field) { + if (!(value instanceof String text) || text.isBlank()) { + throw new IllegalArgumentException("Demo entitlement event " + field + " is invalid"); + } + return text; + } + + private static UUID uuid(Object value, String field) { + String text = text(value, field); + UUID uuid; + try { + uuid = UUID.fromString(text); + } catch (IllegalArgumentException exception) { + throw new IllegalArgumentException( + "Demo entitlement event " + field + " is not a UUID", exception); + } + if (NIL_UUID.equals(uuid) || !uuid.toString().equals(text)) { + throw new IllegalArgumentException("Demo entitlement event " + field + " is not canonical"); + } + return uuid; + } + + private static int integer(Object value, String field) { + if (!(value instanceof Number number)) { + throw new IllegalArgumentException( + "Demo entitlement event " + field + " must be a JSON integer"); + } + String encoded = number.toString(); + if (!POSITIVE_DECIMAL.matcher(encoded).matches()) { + throw new IllegalArgumentException( + "Demo entitlement event " + field + " must be a positive JSON integer"); + } + try { + return Integer.parseInt(encoded); + } catch (NumberFormatException exception) { + throw new IllegalArgumentException( + "Demo entitlement event " + field + " is too large", exception); + } + } + + private static long positiveDecimal(Object value, String field) { + String encoded = decimalText(value, field, POSITIVE_DECIMAL, "positive"); + try { + return Long.parseLong(encoded); + } catch (NumberFormatException exception) { + throw new IllegalArgumentException( + "Demo entitlement event " + field + " is outside the supported owner range", exception); + } + } + + private static long nonnegativeDecimal(Object value, String field) { + String encoded = decimalText(value, field, NONNEGATIVE_DECIMAL, "non-negative"); + try { + return Long.parseLong(encoded); + } catch (NumberFormatException exception) { + throw new IllegalArgumentException( + "Demo entitlement event " + field + " is outside the supported owner range", exception); + } + } + + private static String decimalText( + Object value, String field, Pattern grammar, String description) { + if (!(value instanceof String encoded) || !grammar.matcher(encoded).matches()) { + throw new IllegalArgumentException( + "Demo entitlement event " + + field + + " must be a canonical " + + description + + " decimal string"); + } + return encoded; + } + + private static Map quotaFields(DemoTenantEntitlementRequest.Quotas quotas) { + Map fields = new LinkedHashMap<>(); + fields.put("maxActiveSessions", Long.toString(quotas.maxActiveSessions())); + fields.put("maxConcurrentGameInstances", Long.toString(quotas.maxConcurrentGameInstances())); + fields.put("maxStorageBytes", Long.toString(quotas.maxStorageBytes())); + return fields; + } + + private static boolean bool(Object value, String field) { + if (!(value instanceof Boolean result)) { + throw new IllegalArgumentException("Demo entitlement event " + field + " is not boolean"); + } + return result; + } + + /** Exact closed event evidence stored in the Account entitlement outbox. */ + public record Event( + UUID requestId, + String requestDigest, + UUID canonicalTenantId, + FreshTenantCreationEvidence sourceEvidence, + long entitlementVersion, + long tenantAuthorityGeneration, + long tenantAuthoritySourceVersion, + long tenantBillingSequence, + boolean gameplayAvailable, + boolean allowPublicJoin, + boolean allowNewGameplayBindings, + boolean allowNewInstanceStarts, + DemoTenantEntitlementRequest.Quotas quotas, + UUID eventId, + String outboxStreamKey, + String eventDigest, + byte[] payload) { + public Event { + payload = payload.clone(); + } + + @Override + public byte[] payload() { + return payload.clone(); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/DemoTenantEntitlementRequest.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/DemoTenantEntitlementRequest.java new file mode 100644 index 0000000000..e6f8a3b16a --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/DemoTenantEntitlementRequest.java @@ -0,0 +1,121 @@ +package net.firedevops.firemud.accountservice.dto; + +import java.io.IOException; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import tools.jackson.databind.json.JsonMapper; + +/** Explicit Account-owned non-paid demo entitlement mutation from a protected local fixture. */ +public record DemoTenantEntitlementRequest( + UUID requestId, + UUID canonicalTenantId, + UUID tenantCreationRequestId, + String tenantCreationRequestDigest, + Long expectedEntitlementVersion, + Long expectedTenantAuthorityGeneration, + Long expectedTenantAuthoritySourceVersion, + boolean gameplayAvailable, + boolean allowPublicJoin, + boolean allowNewGameplayBindings, + boolean allowNewInstanceStarts, + Quotas quotas) { + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final Pattern DIGEST = Pattern.compile("sha256:[0-9a-f]{64}"); + private static final JsonMapper JSON = JsonMapper.builder().build(); + + public DemoTenantEntitlementRequest { + requireNonNil(requestId, "Demo entitlement request ID"); + requireNonNil(canonicalTenantId, "Canonical tenant UUID"); + requireNonNil(tenantCreationRequestId, "Fresh tenant creation request ID"); + if (tenantCreationRequestDigest == null + || !DIGEST.matcher(tenantCreationRequestDigest).matches()) { + throw new IllegalArgumentException("Fresh tenant creation request digest is invalid"); + } + boolean creating = expectedEntitlementVersion == null; + if (creating != (expectedTenantAuthorityGeneration == null) + || creating != (expectedTenantAuthoritySourceVersion == null)) { + throw new IllegalArgumentException( + "Demo entitlement create or update fence fields must be supplied together"); + } + if (!creating + && (expectedEntitlementVersion <= 0 + || expectedTenantAuthorityGeneration <= 0 + || expectedTenantAuthoritySourceVersion <= 0)) { + throw new IllegalArgumentException("Expected demo entitlement fences must be positive"); + } + Objects.requireNonNull(quotas, "Explicit demo entitlement quotas are required"); + } + + /** Stable normalized request digest; the request ID remains the operation identity. */ + public String requestDigest() { + Map normalized = new LinkedHashMap<>(); + normalized.put("schemaVersion", "account-demo-entitlement-request/v1"); + normalized.put("canonicalTenantId", canonicalTenantId.toString()); + normalized.put("tenantCreationRequestId", tenantCreationRequestId.toString()); + normalized.put("tenantCreationRequestDigest", tenantCreationRequestDigest); + normalized.put("expectedEntitlementVersion", decimal(expectedEntitlementVersion)); + normalized.put("expectedTenantAuthorityGeneration", decimal(expectedTenantAuthorityGeneration)); + normalized.put( + "expectedTenantAuthoritySourceVersion", decimal(expectedTenantAuthoritySourceVersion)); + normalized.put("entitlementKind", "NON_PAID_DEMO"); + normalized.put("subscriptionStatus", null); + normalized.put("paid", false); + normalized.put("status", "ACTIVE"); + normalized.put("gameplayAvailable", gameplayAvailable); + normalized.put("allowPublicJoin", allowPublicJoin); + normalized.put("allowNewGameplayBindings", allowNewGameplayBindings); + normalized.put("allowNewInstanceStarts", allowNewInstanceStarts); + normalized.put("quotas", quotaFields(quotas)); + try { + byte[] canonical = Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(normalized)); + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(canonical)); + } catch (IOException | NoSuchAlgorithmException | RuntimeException exception) { + throw new IllegalStateException( + "Demo entitlement request digest could not be computed", exception); + } + } + + private static void requireNonNil(UUID value, String field) { + if (value == null || NIL_UUID.equals(value)) { + throw new IllegalArgumentException(field + " must be a canonical non-nil UUID"); + } + } + + private static String decimal(Long value) { + return value == null ? null : Long.toString(value); + } + + private static Map quotaFields(Quotas quotas) { + Map fields = new LinkedHashMap<>(); + fields.put("maxActiveSessions", Long.toString(quotas.maxActiveSessions())); + fields.put("maxConcurrentGameInstances", Long.toString(quotas.maxConcurrentGameInstances())); + fields.put("maxStorageBytes", Long.toString(quotas.maxStorageBytes())); + return fields; + } + + /** Quotas are explicit demo values and never copied from a paid plan or subscription. */ + public record Quotas( + long maxActiveSessions, long maxConcurrentGameInstances, long maxStorageBytes) { + public Quotas { + if (maxActiveSessions < 0 || maxConcurrentGameInstances < 0 || maxStorageBytes < 0) { + throw new IllegalArgumentException("Demo entitlement quotas cannot be negative"); + } + } + + public Map asMap() { + Map values = new LinkedHashMap<>(); + values.put("maxActiveSessions", maxActiveSessions); + values.put("maxConcurrentGameInstances", maxConcurrentGameInstances); + values.put("maxStorageBytes", maxStorageBytes); + return values; + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/DemoTenantEntitlementSnapshot.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/DemoTenantEntitlementSnapshot.java new file mode 100644 index 0000000000..1fbf5cac8f --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/DemoTenantEntitlementSnapshot.java @@ -0,0 +1,87 @@ +package net.firedevops.firemud.accountservice.dto; + +import java.util.Objects; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.accountservice.repository.AccountTenantEntitlementOutboxRepository; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; + +/** Exact committed demo entitlement and its current Account tenant-generation/outbox evidence. */ +public record DemoTenantEntitlementSnapshot( + UUID canonicalTenantId, + FreshTenantCreationEvidence sourceEvidence, + String entitlementKind, + String status, + String subscriptionStatus, + boolean paid, + boolean gameplayAvailable, + boolean allowPublicJoin, + boolean allowNewGameplayBindings, + boolean allowNewInstanceStarts, + DemoTenantEntitlementRequest.Quotas quotas, + long entitlementVersion, + long tenantAuthorityGeneration, + long tenantAuthoritySourceVersion, + String outboxStreamKey, + long tenantBillingSequence, + UUID eventId, + String eventDigest, + String snapshotIdentity, + String tenantAuthorityOutboxStreamKey, + long tenantAuthorityOutboxSequence, + UUID tenantAuthorityEventId, + String tenantAuthorityEventDigest) { + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final Pattern EVENT_DIGEST = Pattern.compile("sha256:[0-9a-f]{64}"); + + public DemoTenantEntitlementSnapshot { + if (canonicalTenantId == null || NIL_UUID.equals(canonicalTenantId)) { + throw new IllegalArgumentException("Canonical tenant UUID is required"); + } + Objects.requireNonNull( + sourceEvidence, "Authenticated fresh tenant source evidence is required"); + if (!canonicalTenantId.equals(sourceEvidence.canonicalTenantId())) { + throw new IllegalArgumentException("Demo entitlement source evidence targets another tenant"); + } + if (!"NON_PAID_DEMO".equals(entitlementKind) + || !"ACTIVE".equals(status) + || subscriptionStatus != null + || paid) { + throw new IllegalArgumentException("Demo entitlement must remain explicitly non-paid"); + } + Objects.requireNonNull(quotas, "Demo entitlement quotas are required"); + if (entitlementVersion <= 0 + || tenantAuthorityGeneration <= 0 + || tenantAuthoritySourceVersion <= 0 + || tenantBillingSequence <= 0) { + throw new IllegalArgumentException("Demo entitlement currentness values must be positive"); + } + String expectedStream = AccountTenantEntitlementOutboxRepository.streamKey(canonicalTenantId); + if (!expectedStream.equals(outboxStreamKey)) { + throw new IllegalArgumentException( + "Demo entitlement outbox scope differs from its tenant UUID"); + } + if (eventId == null || NIL_UUID.equals(eventId)) { + throw new IllegalArgumentException("Demo entitlement event ID is required"); + } + if (eventDigest == null || !EVENT_DIGEST.matcher(eventDigest).matches()) { + throw new IllegalArgumentException("Demo entitlement event digest is invalid"); + } + if (!eventDigest.equals(snapshotIdentity)) { + throw new IllegalArgumentException( + "Demo entitlement snapshot identity differs from its event"); + } + if (!TenantAuthorityEventV1Codec.streamKey(canonicalTenantId) + .equals(tenantAuthorityOutboxStreamKey)) { + throw new IllegalArgumentException( + "Demo entitlement authority stream differs from its tenant UUID"); + } + if (tenantAuthorityOutboxSequence <= 0L + || tenantAuthorityEventId == null + || NIL_UUID.equals(tenantAuthorityEventId) + || tenantAuthorityEventDigest == null + || !EVENT_DIGEST.matcher(tenantAuthorityEventDigest).matches()) { + throw new IllegalArgumentException("Demo entitlement authority event evidence is invalid"); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/TenantAuthorityEventV1Codec.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/TenantAuthorityEventV1Codec.java new file mode 100644 index 0000000000..2ec896e75a --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/TenantAuthorityEventV1Codec.java @@ -0,0 +1,427 @@ +package net.firedevops.firemud.accountservice.dto; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Arrays; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.accountservice.repository.AccountTenantEntitlementOutboxRepository; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.core.type.TypeReference; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.json.JsonMapper; + +/** + * Closed canonical event encoding for Account's independently sequenced tenant authority stream. + */ +public final class TenantAuthorityEventV1Codec { + public static final String SCHEMA_VERSION = "account-tenant-authority-event/v1"; + public static final String EVENT_TYPE = "TENANT_AUTHORITY_CHANGED"; + + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final String STREAM_PREFIX = "account:auth-authority:v1:tenant/"; + private static final Pattern DIGEST = Pattern.compile("sha256:[0-9a-f]{64}"); + private static final Pattern POSITIVE_DECIMAL = Pattern.compile("[1-9][0-9]{0,18}"); + private static final Set EVENT_FIELDS = + Set.of( + "schemaVersion", + "eventType", + "eventId", + "requestId", + "requestDigest", + "tenantId", + "tenantAuthorityGeneration", + "tenantAuthoritySourceVersion", + "outboxStreamKey", + "outboxSequence", + "tenantBillingReceipt", + "sourceEvidence", + "eventDigest"); + private static final Set BILLING_FIELDS = + Set.of("outboxStreamKey", "tenantBillingSequence", "eventId", "eventDigest"); + private static final Set SOURCE_FIELDS = + Set.of( + "schemaVersion", + "targetNamespace", + "creationRequestId", + "operationId", + "requestDigest", + "canonicalTenantId", + "sourceGameRowId", + "sourceGameTenantKey", + "provenanceKind", + "evidenceDigest"); + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + private TenantAuthorityEventV1Codec() {} + + public static String streamKey(UUID tenantId) { + requireUuid(tenantId, "tenant UUID"); + return STREAM_PREFIX + tenantId; + } + + public static Event seal( + DemoTenantEntitlementRequest request, + FreshTenantCreationEvidence source, + long tenantAuthorityGeneration, + long tenantAuthoritySourceVersion, + long outboxSequence, + DemoTenantEntitlementEventV1Codec.Event billingEvent) { + if (request == null || source == null || billingEvent == null) { + throw new IllegalArgumentException( + "Tenant authority request, source, and committed billing event are required"); + } + if (!request.canonicalTenantId().equals(source.canonicalTenantId()) + || !request.tenantCreationRequestId().equals(source.creationRequestId()) + || !request.tenantCreationRequestDigest().equals(source.requestDigest()) + || !"NEW_GAME_ROW".equals(source.provenanceKind()) + || !request.requestId().equals(billingEvent.requestId()) + || !request.requestDigest().equals(billingEvent.requestDigest()) + || !request.canonicalTenantId().equals(billingEvent.canonicalTenantId())) { + throw new IllegalArgumentException( + "Tenant authority event differs from its exact source or billing request"); + } + requirePositive(tenantAuthorityGeneration, "tenant authority generation"); + requirePositive(tenantAuthoritySourceVersion, "tenant authority source version"); + requirePositive(outboxSequence, "authority outbox sequence"); + UUID eventId = eventId(request.requestId()); + String streamKey = streamKey(request.canonicalTenantId()); + Map preimage = + fields( + request.requestId(), + request.requestDigest(), + request.canonicalTenantId(), + tenantAuthorityGeneration, + tenantAuthoritySourceVersion, + streamKey, + outboxSequence, + eventId, + billingEvent, + source); + String digest = digest(canonical(preimage)); + Map wire = new LinkedHashMap<>(preimage); + wire.put("eventDigest", digest); + byte[] payload = canonical(wire); + return new Event( + request.requestId(), + request.requestDigest(), + request.canonicalTenantId(), + tenantAuthorityGeneration, + tenantAuthoritySourceVersion, + streamKey, + outboxSequence, + eventId, + billingEvent.outboxStreamKey(), + billingEvent.tenantBillingSequence(), + billingEvent.eventId(), + billingEvent.eventDigest(), + source, + digest, + payload); + } + + /** Parses and verifies the exact canonical Account authority event bytes. */ + public static Event verify(byte[] payload) { + if (payload == null || payload.length == 0 || payload.length > 32 * 1024) { + throw new IllegalArgumentException("Tenant authority event payload is absent or oversized"); + } + final Map wire; + try { + wire = JSON.readValue(payload, new TypeReference<>() {}); + } catch (RuntimeException exception) { + throw new IllegalArgumentException("Tenant authority event payload is malformed", exception); + } + if (!wire.keySet().equals(EVENT_FIELDS)) { + throw new IllegalArgumentException("Tenant authority event fields are incomplete or unknown"); + } + String claimedDigest = text(wire.get("eventDigest"), "eventDigest"); + Map preimage = new LinkedHashMap<>(wire); + preimage.remove("eventDigest"); + if (!claimedDigest.equals(digest(canonical(preimage))) + || !Arrays.equals(payload, canonical(wire))) { + throw new IllegalArgumentException("Tenant authority event digest or canonical bytes differ"); + } + String schemaVersion = text(wire.get("schemaVersion"), "schemaVersion"); + String eventType = text(wire.get("eventType"), "eventType"); + UUID tenantId = uuid(wire.get("tenantId"), "tenantId"); + UUID requestId = uuid(wire.get("requestId"), "requestId"); + UUID eventId = uuid(wire.get("eventId"), "eventId"); + String requestDigest = digestText(wire.get("requestDigest"), "requestDigest"); + String streamKey = text(wire.get("outboxStreamKey"), "outboxStreamKey"); + long authorityGeneration = + positiveDecimal(wire.get("tenantAuthorityGeneration"), "tenantAuthorityGeneration"); + long sourceVersion = + positiveDecimal(wire.get("tenantAuthoritySourceVersion"), "tenantAuthoritySourceVersion"); + long sequence = positiveDecimal(wire.get("outboxSequence"), "outboxSequence"); + if (!SCHEMA_VERSION.equals(schemaVersion) + || !EVENT_TYPE.equals(eventType) + || !streamKey(tenantId).equals(streamKey) + || !eventId(requestId).equals(eventId)) { + throw new IllegalArgumentException("Tenant authority event scope or identity is invalid"); + } + + Map billing = object(wire.get("tenantBillingReceipt"), "tenantBillingReceipt"); + if (!billing.keySet().equals(BILLING_FIELDS)) { + throw new IllegalArgumentException("Tenant billing receipt fields are incomplete"); + } + String billingStream = text(billing.get("outboxStreamKey"), "billing outboxStreamKey"); + long billingSequence = + positiveDecimal(billing.get("tenantBillingSequence"), "tenantBillingSequence"); + UUID billingEventId = uuid(billing.get("eventId"), "billing eventId"); + String billingDigest = digestText(billing.get("eventDigest"), "billing eventDigest"); + if (!AccountTenantEntitlementOutboxRepository.streamKey(tenantId).equals(billingStream)) { + throw new IllegalArgumentException("Tenant billing receipt has another tenant scope"); + } + if (!DemoTenantEntitlementEventV1Codec.eventId(requestId).equals(billingEventId)) { + throw new IllegalArgumentException("Tenant billing receipt has another request identity"); + } + + Map sourceMap = object(wire.get("sourceEvidence"), "sourceEvidence"); + if (!sourceMap.keySet().equals(SOURCE_FIELDS)) { + throw new IllegalArgumentException("Tenant source evidence fields are incomplete"); + } + FreshTenantCreationEvidence source = + new FreshTenantCreationEvidence( + integer(sourceMap.get("schemaVersion"), "source schemaVersion"), + text(sourceMap.get("targetNamespace"), "source targetNamespace"), + uuid(sourceMap.get("creationRequestId"), "source creationRequestId"), + uuid(sourceMap.get("operationId"), "source operationId"), + digestText(sourceMap.get("requestDigest"), "source requestDigest"), + uuid(sourceMap.get("canonicalTenantId"), "source canonicalTenantId"), + positiveDecimal(sourceMap.get("sourceGameRowId"), "source sourceGameRowId"), + text(sourceMap.get("sourceGameTenantKey"), "source sourceGameTenantKey"), + text(sourceMap.get("provenanceKind"), "source provenanceKind"), + digestText(sourceMap.get("evidenceDigest"), "source evidenceDigest")); + if (!tenantId.equals(source.canonicalTenantId()) + || !"NEW_GAME_ROW".equals(source.provenanceKind())) { + throw new IllegalArgumentException("Tenant authority source evidence targets another tenant"); + } + return new Event( + requestId, + requestDigest, + tenantId, + authorityGeneration, + sourceVersion, + streamKey, + sequence, + eventId, + billingStream, + billingSequence, + billingEventId, + billingDigest, + source, + claimedDigest, + payload); + } + + public static UUID eventId(UUID requestId) { + requireUuid(requestId, "request ID"); + return UUID.nameUUIDFromBytes( + (SCHEMA_VERSION + ":" + requestId).getBytes(StandardCharsets.UTF_8)); + } + + private static Map fields( + UUID requestId, + String requestDigest, + UUID tenantId, + long authorityGeneration, + long sourceVersion, + String streamKey, + long sequence, + UUID eventId, + DemoTenantEntitlementEventV1Codec.Event billingEvent, + FreshTenantCreationEvidence source) { + Map values = new LinkedHashMap<>(); + values.put("schemaVersion", SCHEMA_VERSION); + values.put("eventType", EVENT_TYPE); + values.put("eventId", eventId.toString()); + values.put("requestId", requestId.toString()); + values.put("requestDigest", requestDigest); + values.put("tenantId", tenantId.toString()); + values.put("tenantAuthorityGeneration", Long.toString(authorityGeneration)); + values.put("tenantAuthoritySourceVersion", Long.toString(sourceVersion)); + values.put("outboxStreamKey", streamKey); + values.put("outboxSequence", Long.toString(sequence)); + Map billing = new LinkedHashMap<>(); + billing.put("outboxStreamKey", billingEvent.outboxStreamKey()); + billing.put("tenantBillingSequence", Long.toString(billingEvent.tenantBillingSequence())); + billing.put("eventId", billingEvent.eventId().toString()); + billing.put("eventDigest", billingEvent.eventDigest()); + values.put("tenantBillingReceipt", billing); + values.put("sourceEvidence", sourceFields(source)); + return values; + } + + private static Map sourceFields(FreshTenantCreationEvidence source) { + Map values = new LinkedHashMap<>(); + values.put("schemaVersion", source.schemaVersion()); + values.put("targetNamespace", source.targetNamespace()); + values.put("creationRequestId", source.creationRequestId().toString()); + values.put("operationId", source.operationId().toString()); + values.put("requestDigest", source.requestDigest()); + values.put("canonicalTenantId", source.canonicalTenantId().toString()); + values.put("sourceGameRowId", Long.toString(source.sourceGameRowId())); + values.put("sourceGameTenantKey", source.sourceGameTenantKey()); + values.put("provenanceKind", source.provenanceKind()); + values.put("evidenceDigest", source.evidenceDigest()); + return values; + } + + private static byte[] canonical(Map value) { + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } catch (IOException | RuntimeException exception) { + throw new IllegalStateException( + "Tenant authority event could not be canonicalized", exception); + } + } + + private static String digest(byte[] bytes) { + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + private static Map object(Object value, String field) { + if (!(value instanceof Map raw)) { + throw new IllegalArgumentException("Tenant authority event " + field + " is not an object"); + } + Map result = new LinkedHashMap<>(); + raw.forEach( + (key, fieldValue) -> { + if (!(key instanceof String textKey)) { + throw new IllegalArgumentException( + "Tenant authority event " + field + " has a bad key"); + } + result.put(textKey, fieldValue); + }); + return result; + } + + private static String text(Object value, String field) { + if (!(value instanceof String text) || text.isBlank() || !text.equals(text.strip())) { + throw new IllegalArgumentException("Tenant authority event " + field + " is invalid"); + } + return text; + } + + private static String digestText(Object value, String field) { + String text = text(value, field); + if (!DIGEST.matcher(text).matches()) { + throw new IllegalArgumentException("Tenant authority event " + field + " is invalid"); + } + return text; + } + + private static UUID uuid(Object value, String field) { + try { + String text = text(value, field); + UUID uuid = UUID.fromString(text); + requireUuid(uuid, field); + if (!uuid.toString().equals(text)) { + throw new IllegalArgumentException("Tenant authority event " + field + " is not canonical"); + } + return uuid; + } catch (RuntimeException exception) { + throw new IllegalArgumentException( + "Tenant authority event " + field + " is invalid", exception); + } + } + + private static int integer(Object value, String field) { + if (!(value instanceof Integer) || ((Integer) value) <= 0) { + throw new IllegalArgumentException("Tenant authority event " + field + " is invalid"); + } + return (Integer) value; + } + + private static long positiveDecimal(Object value, String field) { + String text = text(value, field); + if (!POSITIVE_DECIMAL.matcher(text).matches()) { + throw new IllegalArgumentException("Tenant authority event " + field + " is invalid"); + } + try { + return Long.parseLong(text); + } catch (NumberFormatException exception) { + throw new IllegalArgumentException( + "Tenant authority event " + field + " is out of range", exception); + } + } + + private static void requirePositive(long value, String field) { + if (value <= 0L) { + throw new IllegalArgumentException("Tenant authority event " + field + " must be positive"); + } + } + + private static void requireUuid(UUID value, String field) { + if (value == null || NIL_UUID.equals(value)) { + throw new IllegalArgumentException("Tenant authority event " + field + " is required"); + } + } + + /** Exact authority event plus its independent tenant-billing and fresh-source linkage. */ + public record Event( + UUID requestId, + String requestDigest, + UUID tenantId, + long tenantAuthorityGeneration, + long tenantAuthoritySourceVersion, + String outboxStreamKey, + long outboxSequence, + UUID eventId, + String tenantBillingStreamKey, + long tenantBillingSequence, + UUID tenantBillingEventId, + String tenantBillingEventDigest, + FreshTenantCreationEvidence sourceEvidence, + String eventDigest, + byte[] payload) { + public Event { + payload = payload == null ? null : payload.clone(); + requireUuid(requestId, "request ID"); + requireUuid(tenantId, "tenant UUID"); + requireUuid(eventId, "event ID"); + requireUuid(tenantBillingEventId, "billing event ID"); + if (requestDigest == null + || !DIGEST.matcher(requestDigest).matches() + || eventDigest == null + || !DIGEST.matcher(eventDigest).matches() + || tenantBillingEventDigest == null + || !DIGEST.matcher(tenantBillingEventDigest).matches() + || !streamKey(tenantId).equals(outboxStreamKey) + || !AccountTenantEntitlementOutboxRepository.streamKey(tenantId) + .equals(tenantBillingStreamKey) + || tenantAuthorityGeneration <= 0L + || tenantAuthoritySourceVersion <= 0L + || outboxSequence <= 0L + || tenantBillingSequence <= 0L + || sourceEvidence == null + || !tenantId.equals(sourceEvidence.canonicalTenantId()) + || payload == null + || payload.length == 0) { + throw new IllegalArgumentException("Tenant authority event evidence is incomplete"); + } + } + + @Override + public byte[] payload() { + return payload.clone(); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementRepository.java new file mode 100644 index 0000000000..5aaff4ba72 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementRepository.java @@ -0,0 +1,542 @@ +package net.firedevops.firemud.accountservice.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementEventV1Codec; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementEventV1Codec.Event; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementRequest; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementSnapshot; +import net.firedevops.firemud.accountservice.dto.TenantAuthorityEventV1Codec; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeState; +import net.firedevops.firemud.accountservice.service.DemoTenantEntitlementException; +import net.firedevops.firemud.accountservice.service.DemoTenantEntitlementException.Code; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Account's exact-UUID demo entitlement source, commit, lookup, and currentness fence. */ +@Repository +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Injected repositories and DSLContext are private transaction collaborators.") +public class AccountDemoTenantEntitlementRepository { + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private final DSLContext dsl; + private final FreshTenantIdentityAssociationRepository tenantIdentityRepository; + private final AccountAuthorityGenerationRepository authorityGenerationRepository; + private final AccountTenantEntitlementOutboxRepository outboxRepository; + private final AccountTenantAuthorityEventRepository tenantAuthorityEvents; + + public AccountDemoTenantEntitlementRepository( + DSLContext dsl, + FreshTenantIdentityAssociationRepository tenantIdentityRepository, + AccountAuthorityGenerationRepository authorityGenerationRepository, + AccountTenantEntitlementOutboxRepository outboxRepository, + AccountTenantAuthorityEventRepository tenantAuthorityEvents) { + this.dsl = Objects.requireNonNull(dsl); + this.tenantIdentityRepository = Objects.requireNonNull(tenantIdentityRepository); + this.authorityGenerationRepository = Objects.requireNonNull(authorityGenerationRepository); + this.outboxRepository = Objects.requireNonNull(outboxRepository); + this.tenantAuthorityEvents = Objects.requireNonNull(tenantAuthorityEvents); + } + + /** Commits one protected-fixture mutation with source readback, shared generation, and outbox. */ + @Transactional(propagation = Propagation.MANDATORY) + public DemoTenantEntitlementSnapshot provision( + DemoTenantEntitlementRequest request, FreshTenantCreationEvidence authenticatedSource) { + requireTransaction(); + Objects.requireNonNull(request, "Demo entitlement request is required"); + requireExactSource(request, authenticatedSource); + FreshTenantCreationEvidence currentSource = + tenantIdentityRepository + .read(request.canonicalTenantId()) + .orElseThrow( + () -> + new DemoTenantEntitlementException( + Code.SOURCE_EVIDENCE_INVALID, + "Exact fresh Game Design source evidence is absent at Account commit")); + if (!authenticatedSource.equals(currentSource)) { + throw new DemoTenantEntitlementException( + Code.SOURCE_EVIDENCE_INVALID, + "Authenticated source evidence differs from exact Account UUID readback at commit"); + } + + int reserved = + dsl.execute( + "INSERT INTO account_demo_tenant_entitlement_operations (request_id, tenant_uuid, " + + "request_digest, source_creation_request_id, source_request_digest, " + + "source_operation_id, source_evidence_digest, status) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, 'PENDING') ON CONFLICT (request_id) DO NOTHING", + request.requestId(), + request.canonicalTenantId(), + request.requestDigest(), + authenticatedSource.creationRequestId(), + authenticatedSource.requestDigest(), + authenticatedSource.operationId(), + authenticatedSource.evidenceDigest()); + if (reserved == 0) { + return replay(request, authenticatedSource); + } + if (reserved != 1) { + throw new IllegalStateException("Demo entitlement request reservation was ambiguous"); + } + + ScopeState oldAuthority = + authorityGenerationRepository.read(AuthorityScope.tenant(request.canonicalTenantId())); + Record oldEntitlement = readCurrentRow(request.canonicalTenantId(), true); + if (oldEntitlement == null) { + tenantAuthorityEvents.establishFirstEventSource( + request.canonicalTenantId(), request.requestId(), authenticatedSource, oldAuthority); + } + long nextEntitlementVersion; + if (oldEntitlement == null) { + if (request.expectedEntitlementVersion() != null) { + throw new DemoTenantEntitlementException( + Code.ENTITLEMENT_VERSION_CONFLICT, + "Demo entitlement create request supplied an update fence"); + } + nextEntitlementVersion = 1L; + } else { + if (request.expectedEntitlementVersion() == null + || request.expectedEntitlementVersion() != value(oldEntitlement, "entitlement_version") + || request.expectedTenantAuthorityGeneration() != oldAuthority.generation() + || request.expectedTenantAuthoritySourceVersion() != oldAuthority.sourceVersion()) { + throw new DemoTenantEntitlementException( + Code.TENANT_AUTHORITY_STALE, + "Demo entitlement update does not match the exact current entitlement and tenant authority"); + } + nextEntitlementVersion = increment(value(oldEntitlement, "entitlement_version")); + } + ScopeState nextAuthority = authorityGenerationRepository.advance(oldAuthority, null); + final long committedEntitlementVersion = nextEntitlementVersion; + Event committedEvent = + outboxRepository.append( + request.canonicalTenantId(), + request.requestId(), + sequence -> + DemoTenantEntitlementEventV1Codec.seal( + request, + authenticatedSource, + committedEntitlementVersion, + nextAuthority.generation(), + nextAuthority.sourceVersion(), + sequence)); + + TenantAuthorityEventV1Codec.Event authorityEvent = + tenantAuthorityEvents.append(request, authenticatedSource, nextAuthority, committedEvent); + + writeCurrent( + request, authenticatedSource, committedEvent, authorityEvent, oldEntitlement == null); + int committed = + dsl.execute( + "UPDATE account_demo_tenant_entitlement_operations SET status = 'COMMITTED', " + + "tenant_billing_sequence = ?, event_id = ?, event_digest = ?, " + + "entitlement_version = ?, tenant_authority_generation = ?, " + + "tenant_authority_source_version = ?, tenant_authority_outbox_stream_key = ?, " + + "tenant_authority_outbox_sequence = ?, tenant_authority_event_id = ?, " + + "tenant_authority_event_digest = ?, committed_at = CURRENT_TIMESTAMP " + + "WHERE request_id = ? AND status = 'PENDING'", + committedEvent.tenantBillingSequence(), + committedEvent.eventId(), + committedEvent.eventDigest(), + committedEvent.entitlementVersion(), + committedEvent.tenantAuthorityGeneration(), + committedEvent.tenantAuthoritySourceVersion(), + authorityEvent.outboxStreamKey(), + authorityEvent.outboxSequence(), + authorityEvent.eventId().toString(), + authorityEvent.eventDigest(), + request.requestId()); + if (committed != 1) { + throw new IllegalStateException("Demo entitlement operation receipt was not committed"); + } + return snapshot(committedEvent, authorityEvent); + } + + /** Reads one exact current snapshot and denies stale or incomplete Account/source state. */ + @Transactional(propagation = Propagation.MANDATORY, readOnly = true) + public DemoTenantEntitlementSnapshot readCurrent(UUID canonicalTenantId) { + requireTenantUuid(canonicalTenantId); + Optional evidence = + tenantIdentityRepository.read(canonicalTenantId); + FreshTenantCreationEvidence source = + evidence.orElseThrow( + () -> + new DemoTenantEntitlementException( + Code.SOURCE_EVIDENCE_INVALID, + "No exact fresh Game Design source evidence exists for this tenant UUID")); + ScopeState authority = + authorityGenerationRepository.read(AuthorityScope.tenant(canonicalTenantId)); + Record row = readCurrentRow(canonicalTenantId, false); + if (row == null) { + throw new DemoTenantEntitlementException( + Code.ENTITLEMENT_UNAVAILABLE, "No Account demo entitlement exists for this tenant UUID"); + } + CurrentEvents current = currentEvents(row, source, authority); + return snapshot(current.billingEvent(), current.authorityEvent()); + } + + /** Re-reads all source, generation, version, and outbox evidence at the final admission fence. */ + @Transactional(propagation = Propagation.MANDATORY, readOnly = true) + public DemoTenantEntitlementSnapshot revalidate(DemoTenantEntitlementSnapshot evaluated) { + Objects.requireNonNull(evaluated, "Complete evaluated entitlement evidence is required"); + DemoTenantEntitlementSnapshot current = readCurrent(evaluated.canonicalTenantId()); + if (!current.equals(evaluated)) { + throw new DemoTenantEntitlementException( + Code.STALE_ADMISSION_EVIDENCE, + "Account demo entitlement changed after its complete evaluation snapshot"); + } + return current; + } + + private DemoTenantEntitlementSnapshot replay( + DemoTenantEntitlementRequest request, FreshTenantCreationEvidence authenticatedSource) { + Record operation = + dsl.fetchOne( + "SELECT tenant_uuid, request_digest, source_creation_request_id, " + + "source_request_digest, source_operation_id, source_evidence_digest, status, " + + "tenant_billing_sequence, event_id, event_digest, " + + "tenant_authority_outbox_stream_key, tenant_authority_outbox_sequence, " + + "tenant_authority_event_id, tenant_authority_event_digest " + + "FROM account_demo_tenant_entitlement_operations WHERE request_id = ? FOR UPDATE", + request.requestId()); + if (operation == null + || !request.canonicalTenantId().equals(get(operation, "tenant_uuid", UUID.class)) + || !request.requestDigest().equals(get(operation, "request_digest", String.class)) + || !authenticatedSource + .creationRequestId() + .equals(get(operation, "source_creation_request_id", UUID.class)) + || !authenticatedSource + .requestDigest() + .equals(get(operation, "source_request_digest", String.class)) + || !authenticatedSource + .operationId() + .equals(get(operation, "source_operation_id", UUID.class)) + || !authenticatedSource + .evidenceDigest() + .equals(get(operation, "source_evidence_digest", String.class))) { + throw new DemoTenantEntitlementException( + Code.IDEMPOTENCY_CONFLICT, + "Demo entitlement request ID was reused for a different tenant or payload"); + } + if (!"COMMITTED".equals(get(operation, "status", String.class))) { + throw new IllegalStateException("Committed Account contains an unfinished demo operation"); + } + long sequence = value(operation, "tenant_billing_sequence"); + Event event = + outboxRepository + .readEvent(request.canonicalTenantId(), sequence) + .orElseThrow( + () -> + new IllegalStateException("Committed demo entitlement operation has no event")); + if (!request.requestId().equals(event.requestId()) + || !request.requestDigest().equals(event.requestDigest()) + || !event.eventId().equals(get(operation, "event_id", UUID.class)) + || !event.eventDigest().equals(get(operation, "event_digest", String.class)) + || !authenticatedSource.equals(event.sourceEvidence())) { + throw new IllegalStateException("Committed demo entitlement receipt differs from its event"); + } + var authorityEvent = + tenantAuthorityEvents.readCommittedReceipt( + request.canonicalTenantId(), + request.requestId(), + request.requestDigest(), + authenticatedSource, + event.tenantBillingSequence(), + event.eventId(), + event.eventDigest(), + value(operation, "tenant_authority_outbox_sequence"), + get(operation, "tenant_authority_event_id", String.class), + get(operation, "tenant_authority_event_digest", String.class)); + if (!authorityEvent + .outboxStreamKey() + .equals(get(operation, "tenant_authority_outbox_stream_key", String.class)) + || authorityEvent.tenantAuthorityGeneration() != event.tenantAuthorityGeneration() + || authorityEvent.tenantAuthoritySourceVersion() != event.tenantAuthoritySourceVersion()) { + throw new IllegalStateException( + "Committed demo entitlement receipt differs from its tenant authority event"); + } + return snapshot(event, authorityEvent); + } + + private CurrentEvents currentEvents( + Record row, FreshTenantCreationEvidence source, ScopeState authority) { + long storedGeneration = value(row, "tenant_authority_generation"); + long storedSourceVersion = value(row, "tenant_authority_source_version"); + if (storedGeneration != authority.generation() + || storedSourceVersion != authority.sourceVersion()) { + throw new DemoTenantEntitlementException( + Code.TENANT_AUTHORITY_STALE, + "Stored demo entitlement is stale against Account's shared tenant authority generation"); + } + if (source.schemaVersion() != get(row, "source_schema_version", Integer.class) + || !source.targetNamespace().equals(get(row, "source_target_namespace", String.class)) + || !source.creationRequestId().equals(get(row, "source_creation_request_id", UUID.class)) + || !source.operationId().equals(get(row, "source_operation_id", UUID.class)) + || !source.requestDigest().equals(get(row, "source_request_digest", String.class)) + || source.sourceGameRowId() != value(row, "source_game_row_id") + || !source.sourceGameTenantKey().equals(get(row, "source_game_tenant_key", String.class)) + || !source.provenanceKind().equals(get(row, "source_provenance_kind", String.class)) + || !source.evidenceDigest().equals(get(row, "source_evidence_digest", String.class))) { + throw new DemoTenantEntitlementException( + Code.SOURCE_EVIDENCE_INVALID, + "Stored demo entitlement source tuple differs from current authenticated Account source evidence"); + } + long sequence = value(row, "tenant_billing_sequence"); + var checkpoint = + outboxRepository + .readCheckpoint(source.canonicalTenantId()) + .orElseThrow( + () -> + new IllegalStateException("Current demo entitlement has no outbox checkpoint")); + if (checkpoint.sequence() != sequence + || !checkpoint.eventId().equals(get(row, "event_id", UUID.class)) + || !checkpoint.eventDigest().equals(get(row, "event_digest", String.class))) { + throw new DemoTenantEntitlementException( + Code.TENANT_AUTHORITY_STALE, + "Current demo entitlement does not match the exact tenant entitlement outbox head"); + } + Event event = + outboxRepository + .readEvent(source.canonicalTenantId(), sequence) + .orElseThrow( + () -> new IllegalStateException("Current demo entitlement event is absent")); + if (!source.equals(event.sourceEvidence()) + || event.entitlementVersion() != value(row, "entitlement_version") + || event.tenantAuthorityGeneration() != storedGeneration + || event.tenantAuthoritySourceVersion() != storedSourceVersion + || !event.requestId().equals(get(row, "last_request_id", UUID.class)) + || !event.requestDigest().equals(get(row, "last_request_digest", String.class)) + || !event.eventId().equals(get(row, "event_id", UUID.class)) + || !event.eventDigest().equals(get(row, "event_digest", String.class)) + || event.gameplayAvailable() != get(row, "gameplay_available", Boolean.class) + || event.allowPublicJoin() != get(row, "allow_public_join", Boolean.class) + || event.allowNewGameplayBindings() + != get(row, "allow_new_gameplay_bindings", Boolean.class) + || event.allowNewInstanceStarts() != get(row, "allow_new_instance_starts", Boolean.class) + || !event + .quotas() + .equals( + new DemoTenantEntitlementRequest.Quotas( + value(row, "max_active_sessions"), + value(row, "max_concurrent_game_instances"), + value(row, "max_storage_bytes")))) { + throw new IllegalStateException("Current demo entitlement projection differs from its event"); + } + TenantAuthorityEventV1Codec.Event authorityEvent = + tenantAuthorityEvents.readCurrentCheckpoint( + source.canonicalTenantId(), + source, + authority, + event.requestId(), + event.requestDigest(), + sequence, + event.eventId(), + event.eventDigest()); + if (authorityEvent.tenantAuthorityGeneration() != storedGeneration + || authorityEvent.tenantAuthoritySourceVersion() != storedSourceVersion) { + throw new IllegalStateException( + "Current tenant authority event differs from Account's actual generation"); + } + return new CurrentEvents(event, authorityEvent); + } + + private void writeCurrent( + DemoTenantEntitlementRequest request, + FreshTenantCreationEvidence source, + Event event, + TenantAuthorityEventV1Codec.Event authorityEvent, + boolean insert) { + String sql = + insert + ? "INSERT INTO account_demo_tenant_entitlements (tenant_uuid, source_schema_version, " + + "source_target_namespace, source_creation_request_id, source_operation_id, " + + "source_request_digest, source_game_row_id, source_game_tenant_key, " + + "source_provenance_kind, source_evidence_digest, entitlement_kind, status, " + + "subscription_status, paid, gameplay_available, allow_public_join, " + + "allow_new_gameplay_bindings, allow_new_instance_starts, max_active_sessions, " + + "max_concurrent_game_instances, max_storage_bytes, entitlement_version, " + + "tenant_authority_generation, tenant_authority_source_version, " + + "tenant_billing_sequence, event_id, event_digest, last_request_id, last_request_digest, " + + "tenant_authority_outbox_stream_key, tenant_authority_outbox_sequence, " + + "tenant_authority_event_id, tenant_authority_event_digest) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'NON_PAID_DEMO', 'ACTIVE', NULL, FALSE, " + + "?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)" + : "UPDATE account_demo_tenant_entitlements SET gameplay_available = ?, " + + "allow_public_join = ?, allow_new_gameplay_bindings = ?, allow_new_instance_starts = ?, " + + "max_active_sessions = ?, max_concurrent_game_instances = ?, max_storage_bytes = ?, " + + "entitlement_version = ?, tenant_authority_generation = ?, " + + "tenant_authority_source_version = ?, tenant_billing_sequence = ?, event_id = ?, " + + "event_digest = ?, last_request_id = ?, last_request_digest = ?, " + + "tenant_authority_outbox_stream_key = ?, tenant_authority_outbox_sequence = ?, " + + "tenant_authority_event_id = ?, tenant_authority_event_digest = ? " + + "WHERE tenant_uuid = ?"; + Object[] values = + insert + ? new Object[] { + request.canonicalTenantId(), + source.schemaVersion(), + source.targetNamespace(), + source.creationRequestId(), + source.operationId(), + source.requestDigest(), + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind(), + source.evidenceDigest(), + request.gameplayAvailable(), + request.allowPublicJoin(), + request.allowNewGameplayBindings(), + request.allowNewInstanceStarts(), + request.quotas().maxActiveSessions(), + request.quotas().maxConcurrentGameInstances(), + request.quotas().maxStorageBytes(), + event.entitlementVersion(), + event.tenantAuthorityGeneration(), + event.tenantAuthoritySourceVersion(), + event.tenantBillingSequence(), + event.eventId(), + event.eventDigest(), + request.requestId(), + request.requestDigest(), + authorityEvent.outboxStreamKey(), + authorityEvent.outboxSequence(), + authorityEvent.eventId().toString(), + authorityEvent.eventDigest() + } + : new Object[] { + request.gameplayAvailable(), + request.allowPublicJoin(), + request.allowNewGameplayBindings(), + request.allowNewInstanceStarts(), + request.quotas().maxActiveSessions(), + request.quotas().maxConcurrentGameInstances(), + request.quotas().maxStorageBytes(), + event.entitlementVersion(), + event.tenantAuthorityGeneration(), + event.tenantAuthoritySourceVersion(), + event.tenantBillingSequence(), + event.eventId(), + event.eventDigest(), + request.requestId(), + request.requestDigest(), + authorityEvent.outboxStreamKey(), + authorityEvent.outboxSequence(), + authorityEvent.eventId().toString(), + authorityEvent.eventDigest(), + request.canonicalTenantId() + }; + int changed = dsl.execute(sql, values); + if (changed != 1) { + throw new IllegalStateException( + "Demo entitlement current state was not committed exactly once"); + } + } + + private Record readCurrentRow(UUID tenantId, boolean forUpdate) { + return dsl.fetchOne( + "SELECT source_schema_version, source_target_namespace, source_creation_request_id, " + + "source_operation_id, source_request_digest, source_game_row_id, " + + "source_game_tenant_key, source_provenance_kind, source_evidence_digest, " + + "entitlement_version, gameplay_available, allow_public_join, " + + "allow_new_gameplay_bindings, allow_new_instance_starts, max_active_sessions, " + + "max_concurrent_game_instances, max_storage_bytes, tenant_authority_generation, " + + "tenant_authority_source_version, tenant_billing_sequence, event_id, event_digest, " + + "last_request_id, last_request_digest, tenant_authority_outbox_stream_key, " + + "tenant_authority_outbox_sequence, tenant_authority_event_id, " + + "tenant_authority_event_digest FROM account_demo_tenant_entitlements " + + "WHERE tenant_uuid = ?" + + (forUpdate ? " FOR UPDATE" : " FOR SHARE"), + tenantId); + } + + private static DemoTenantEntitlementSnapshot snapshot( + Event event, TenantAuthorityEventV1Codec.Event authorityEvent) { + return new DemoTenantEntitlementSnapshot( + event.canonicalTenantId(), + event.sourceEvidence(), + "NON_PAID_DEMO", + "ACTIVE", + null, + false, + event.gameplayAvailable(), + event.allowPublicJoin(), + event.allowNewGameplayBindings(), + event.allowNewInstanceStarts(), + event.quotas(), + event.entitlementVersion(), + event.tenantAuthorityGeneration(), + event.tenantAuthoritySourceVersion(), + event.outboxStreamKey(), + event.tenantBillingSequence(), + event.eventId(), + event.eventDigest(), + event.eventDigest(), + authorityEvent.outboxStreamKey(), + authorityEvent.outboxSequence(), + authorityEvent.eventId(), + authorityEvent.eventDigest()); + } + + private record CurrentEvents( + Event billingEvent, TenantAuthorityEventV1Codec.Event authorityEvent) {} + + private static void requireExactSource( + DemoTenantEntitlementRequest request, FreshTenantCreationEvidence source) { + if (source == null + || !request.canonicalTenantId().equals(source.canonicalTenantId()) + || !request.tenantCreationRequestId().equals(source.creationRequestId()) + || !request.tenantCreationRequestDigest().equals(source.requestDigest()) + || !"NEW_GAME_ROW".equals(source.provenanceKind())) { + throw new DemoTenantEntitlementException( + Code.SOURCE_EVIDENCE_INVALID, + "Only exact authenticated fresh Game Design tenant creation evidence can receive a demo entitlement"); + } + } + + private static void requireTenantUuid(UUID tenantId) { + if (tenantId == null || NIL_UUID.equals(tenantId)) { + throw new DemoTenantEntitlementException( + Code.ENTITLEMENT_UNAVAILABLE, "Exact non-nil canonical tenant UUID is required"); + } + } + + private static void requireTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Account demo entitlement operation requires one owner transaction"); + } + } + + private static long value(Record row, String column) { + Long value = row.get(column, Long.class); + if (value == null || value < 0) { + throw new IllegalStateException("Account demo entitlement " + column + " is malformed"); + } + return value; + } + + private static long increment(long current) { + try { + return Math.addExact(current, 1L); + } catch (ArithmeticException overflow) { + throw new IllegalStateException("Account demo entitlement version is exhausted", overflow); + } + } + + private static T get(Record row, String column, Class type) { + T result = row.get(column, type); + if (result == null) { + throw new IllegalStateException("Account demo entitlement " + column + " is absent"); + } + return result; + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepository.java new file mode 100644 index 0000000000..f66e3c5d48 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepository.java @@ -0,0 +1,576 @@ +package net.firedevops.firemud.accountservice.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementEventV1Codec; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementRequest; +import net.firedevops.firemud.accountservice.dto.TenantAuthorityEventV1Codec; +import net.firedevops.firemud.accountservice.dto.TenantAuthorityEventV1Codec.Event; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeState; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Typed tenant-authority source, outbox, receipt, and current-checkpoint readback. */ +@Repository +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = + "Injected Account repositories and DSLContext are private transaction collaborators.") +public class AccountTenantAuthorityEventRepository { + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private final DSLContext dsl; + private final AccountAuthorityOutboxRepository authorityOutbox; + private final AccountTenantEntitlementOutboxRepository billingOutbox; + private final FreshTenantIdentityAssociationRepository tenantIdentity; + private final AccountAuthorityGenerationRepository generations; + + public AccountTenantAuthorityEventRepository( + DSLContext dsl, + AccountAuthorityOutboxRepository authorityOutbox, + AccountTenantEntitlementOutboxRepository billingOutbox, + FreshTenantIdentityAssociationRepository tenantIdentity, + AccountAuthorityGenerationRepository generations) { + this.dsl = Objects.requireNonNull(dsl); + this.authorityOutbox = Objects.requireNonNull(authorityOutbox); + this.billingOutbox = Objects.requireNonNull(billingOutbox); + this.tenantIdentity = Objects.requireNonNull(tenantIdentity); + this.generations = Objects.requireNonNull(generations); + } + + /** Establishes sequence zero only from the same Account transaction that enrolled the tenant. */ + @Transactional(propagation = Propagation.MANDATORY) + public void establishFirstEventSource( + UUID tenantId, UUID requestId, FreshTenantCreationEvidence source, ScopeState authority) { + requireTransaction(); + requireExactTenant(tenantId, source, authority); + if (authority.generation() != 1L || authority.sourceVersion() != 1L) { + throw new IllegalStateException( + "Tenant authority has advanced without canonical source-event evidence"); + } + + String streamKey = TenantAuthorityEventV1Codec.streamKey(tenantId); + Record existingSource = + dsl.fetchOne( + "SELECT last_outbox_sequence FROM account_tenant_authority_source_records " + + "WHERE outbox_stream_key = ? FOR UPDATE", + streamKey); + if (existingSource != null) { + throw new IllegalStateException( + "Tenant authority source already exists without its current entitlement row"); + } + + Record stream = + dsl.fetchOne( + "SELECT last_sequence FROM account_authority_outbox_streams " + + "WHERE outbox_stream_key = ? FOR UPDATE", + streamKey); + if (stream != null) { + throw new IllegalStateException( + "Tenant authority stream exists without Account source initialization proof"); + } + + Record sourceInitialization = + dsl.fetchOne( + "SELECT fresh.authority_source_transaction_id, generation.created_transaction_id, " + + "generation.generation, generation.source_version " + + "FROM account_fresh_tenant_identity_associations fresh " + + "JOIN account_canonical_tenant_identity_claims claim " + + "ON claim.canonical_tenant_id = fresh.canonical_tenant_id " + + "AND claim.identity_kind = 'FRESH_GAME_DESIGN' " + + "AND claim.source_operation_id = fresh.operation_id " + + "AND claim.source_creation_request_id = fresh.creation_request_id " + + "AND claim.source_request_digest = fresh.request_digest " + + "AND claim.source_game_row_id = fresh.source_game_row_id " + + "AND claim.source_game_tenant_key = fresh.source_game_tenant_key " + + "AND claim.source_provenance_kind = fresh.provenance_kind " + + "AND claim.source_evidence_digest = fresh.evidence_digest " + + "JOIN account_authority_generations generation " + + "ON generation.scope_kind = 'TENANT' " + + "AND generation.tenant_uuid = fresh.canonical_tenant_id " + + "WHERE fresh.canonical_tenant_id = ?", + tenantId); + if (sourceInitialization == null + || sourceInitialization.get("authority_source_transaction_id", Long.class) == null + || !Objects.equals( + sourceInitialization.get("authority_source_transaction_id", Long.class), + sourceInitialization.get("created_transaction_id", Long.class)) + || !Long.valueOf(1L).equals(sourceInitialization.get("generation", Long.class)) + || !Long.valueOf(1L).equals(sourceInitialization.get("source_version", Long.class))) { + throw new IllegalStateException( + "Fresh tenant source and Account generation lack one owner initialization proof"); + } + + Record billingStream = + dsl.fetchOne( + "SELECT last_sequence FROM account_tenant_entitlement_outbox_streams " + + "WHERE tenant_uuid = ? FOR SHARE", + tenantId); + Record priorOperation = + dsl.fetchOne( + "SELECT request_id FROM account_demo_tenant_entitlement_operations " + + "WHERE tenant_uuid = ? AND request_id <> ? LIMIT 1", + tenantId, + requestId); + if (billingStream != null || priorOperation != null) { + throw new IllegalStateException( + "Tenant has retained billing history without canonical authority source evidence"); + } + + int streamInserted = + dsl.execute( + "INSERT INTO account_authority_outbox_streams (outbox_stream_key, last_sequence) " + + "VALUES (?, 0) ON CONFLICT (outbox_stream_key) DO NOTHING", + streamKey); + if (streamInserted != 1) { + throw new IllegalStateException( + "Tenant authority stream changed before Account source enrollment"); + } + long initializationTransactionId = + sourceInitialization.get("created_transaction_id", Long.class); + int sourceInserted = + dsl.execute( + "INSERT INTO account_tenant_authority_source_records (outbox_stream_key, tenant_uuid, " + + "initialization_transaction_id, baseline_generation, baseline_source_version, " + + "current_generation, current_source_version, last_outbox_sequence) " + + "VALUES (?, ?, ?, 1, 1, 1, 1, 0)", + streamKey, + tenantId, + initializationTransactionId); + if (sourceInserted != 1) { + throw new IllegalStateException("Tenant authority source baseline was not enrolled"); + } + } + + /** Appends one tenant-scoped event after the owner has advanced the exact generation row. */ + @Transactional(propagation = Propagation.MANDATORY) + public Event append( + DemoTenantEntitlementRequest request, + FreshTenantCreationEvidence source, + ScopeState nextAuthority, + DemoTenantEntitlementEventV1Codec.Event billingEvent) { + requireTransaction(); + if (request == null || billingEvent == null) { + throw new IllegalArgumentException("Tenant authority request and billing event are required"); + } + requireExactTenant(request.canonicalTenantId(), source, nextAuthority); + String streamKey = TenantAuthorityEventV1Codec.streamKey(request.canonicalTenantId()); + Record sourceHead = + dsl.fetchOne( + "SELECT current_generation, current_source_version, last_outbox_sequence " + + "FROM account_tenant_authority_source_records WHERE outbox_stream_key = ? FOR UPDATE", + streamKey); + if (sourceHead == null || nonnegative(sourceHead, "last_outbox_sequence") < 0L) { + throw new IllegalStateException( + "Tenant authority source head does not match the actual prior generation"); + } + if (increment(positive(sourceHead, "current_generation"), "generation") + != nextAuthority.generation() + || increment(positive(sourceHead, "current_source_version"), "source version") + != nextAuthority.sourceVersion()) { + throw new IllegalStateException( + "Tenant authority source head does not match the actual prior generation"); + } + AccountAuthorityOutboxRepository.Event committed = + authorityOutbox.append( + streamKey, + request.requestId().toString(), + sequence -> + evidence( + TenantAuthorityEventV1Codec.seal( + request, + source, + nextAuthority.generation(), + nextAuthority.sourceVersion(), + sequence, + billingEvent))); + TenantAuthorityEventV1Codec.Event typed = + TenantAuthorityEventV1Codec.verify(committed.payload()); + if (!committed.outboxStreamKey().equals(streamKey) + || !committed.requestId().equals(request.requestId().toString()) + || typed.outboxSequence() != committed.outboxSequence() + || !typed.eventId().toString().equals(committed.eventId()) + || !typed.eventDigest().equals(committed.eventDigest()) + || !request.requestId().equals(typed.requestId()) + || !request.requestDigest().equals(typed.requestDigest()) + || !source.equals(typed.sourceEvidence()) + || typed.tenantAuthorityGeneration() != nextAuthority.generation() + || typed.tenantAuthoritySourceVersion() != nextAuthority.sourceVersion() + || typed.tenantBillingSequence() != billingEvent.tenantBillingSequence() + || !typed.tenantBillingEventId().equals(billingEvent.eventId()) + || !typed.tenantBillingEventDigest().equals(billingEvent.eventDigest())) { + throw new IllegalStateException( + "Committed tenant authority outbox event differs from its exact Account source"); + } + int updated = + dsl.execute( + "UPDATE account_tenant_authority_source_records SET current_generation = ?, " + + "current_source_version = ?, last_outbox_sequence = ?, last_request_id = ?, " + + "last_request_digest = ?, last_event_id = ?, last_event_digest = ?, " + + "tenant_billing_sequence = ?, tenant_billing_event_id = ?, " + + "tenant_billing_event_digest = ? WHERE outbox_stream_key = ? " + + "AND current_generation = ? AND current_source_version = ? " + + "AND last_outbox_sequence = ?", + typed.tenantAuthorityGeneration(), + typed.tenantAuthoritySourceVersion(), + typed.outboxSequence(), + typed.requestId(), + typed.requestDigest(), + typed.eventId().toString(), + typed.eventDigest(), + typed.tenantBillingSequence(), + typed.tenantBillingEventId().toString(), + typed.tenantBillingEventDigest(), + streamKey, + typed.tenantAuthorityGeneration() - 1L, + typed.tenantAuthoritySourceVersion() - 1L, + typed.outboxSequence() - 1L); + if (updated != 1) { + throw new IllegalStateException("Tenant authority source checkpoint was not advanced once"); + } + return typed; + } + + /** + * Verifies the exact event and owning committed receipt, without requiring it to remain latest. + */ + @Transactional(propagation = Propagation.MANDATORY, readOnly = true) + public Event readCommittedReceipt( + UUID tenantId, + UUID requestId, + String requestDigest, + FreshTenantCreationEvidence source, + long billingSequence, + UUID billingEventId, + String billingEventDigest, + long authoritySequence, + String authorityEventId, + String authorityEventDigest) { + requireTransaction(); + requireTenant(tenantId); + Record operation = + dsl.fetchOne( + "SELECT tenant_uuid, request_digest, source_creation_request_id, source_request_digest, " + + "source_operation_id, source_evidence_digest, status, tenant_billing_sequence, " + + "event_id, event_digest, tenant_authority_outbox_stream_key, " + + "tenant_authority_outbox_sequence, tenant_authority_event_id, " + + "tenant_authority_event_digest FROM account_demo_tenant_entitlement_operations " + + "WHERE request_id = ?", + requestId); + String streamKey = TenantAuthorityEventV1Codec.streamKey(tenantId); + if (operation == null + || !tenantId.equals(operation.get("tenant_uuid", UUID.class)) + || !requestDigest.equals(operation.get("request_digest", String.class)) + || !"COMMITTED".equals(operation.get("status", String.class)) + || !source + .creationRequestId() + .equals(operation.get("source_creation_request_id", UUID.class)) + || !source.requestDigest().equals(operation.get("source_request_digest", String.class)) + || !source.operationId().equals(operation.get("source_operation_id", UUID.class)) + || !source.evidenceDigest().equals(operation.get("source_evidence_digest", String.class)) + || billingSequence != positive(operation, "tenant_billing_sequence") + || !billingEventId.equals(operation.get("event_id", UUID.class)) + || !billingEventDigest.equals(operation.get("event_digest", String.class)) + || !streamKey.equals(operation.get("tenant_authority_outbox_stream_key", String.class)) + || authoritySequence != positive(operation, "tenant_authority_outbox_sequence") + || !authorityEventId.equals(operation.get("tenant_authority_event_id", String.class)) + || !authorityEventDigest.equals( + operation.get("tenant_authority_event_digest", String.class))) { + throw new IllegalStateException( + "Tenant authority readback has no exact owning committed entitlement receipt"); + } + AccountAuthorityOutboxRepository.Event stored = + authorityOutbox + .findEvent(streamKey, authoritySequence) + .orElseThrow( + () -> new IllegalStateException("Tenant authority event is absent at its receipt")); + Event event = TenantAuthorityEventV1Codec.verify(stored.payload()); + if (!stored.eventId().equals(event.eventId().toString()) + || !stored.eventDigest().equals(event.eventDigest()) + || !stored.requestId().equals(requestId.toString()) + || !event.requestDigest().equals(requestDigest) + || !event.tenantId().equals(tenantId) + || !source.equals(event.sourceEvidence()) + || event.tenantBillingSequence() != billingSequence + || !event.tenantBillingEventId().equals(billingEventId) + || !event.tenantBillingEventDigest().equals(billingEventDigest)) { + throw new IllegalStateException( + "Tenant authority event differs from its exact entitlement receipt or source"); + } + DemoTenantEntitlementEventV1Codec.Event billing = + billingOutbox + .readEvent(tenantId, billingSequence) + .orElseThrow( + () -> new IllegalStateException("Tenant billing event is absent at its receipt")); + if (!billing.eventId().equals(billingEventId) + || !billing.eventDigest().equals(billingEventDigest) + || !requestId.equals(billing.requestId()) + || !requestDigest.equals(billing.requestDigest()) + || !source.equals(billing.sourceEvidence())) { + throw new IllegalStateException( + "Tenant authority event does not link to the exact original billing event"); + } + return event; + } + + /** Verifies that a current Account generation is represented by the exact latest source event. */ + @Transactional(propagation = Propagation.MANDATORY, readOnly = true) + public Event readCurrentCheckpoint( + UUID tenantId, + FreshTenantCreationEvidence source, + ScopeState authority, + UUID requestId, + String requestDigest, + long billingSequence, + UUID billingEventId, + String billingEventDigest) { + requireTransaction(); + requireExactTenant(tenantId, source, authority); + String streamKey = TenantAuthorityEventV1Codec.streamKey(tenantId); + Record head = + dsl.fetchOne( + "SELECT current_generation, current_source_version, last_outbox_sequence, " + + "last_event_id, last_event_digest, last_request_id, last_request_digest, " + + "tenant_billing_sequence, tenant_billing_event_id, tenant_billing_event_digest " + + "FROM account_tenant_authority_source_records WHERE outbox_stream_key = ?", + streamKey); + if (head == null + || positive(head, "current_generation") != authority.generation() + || positive(head, "current_source_version") != authority.sourceVersion() + || !requestId.equals(head.get("last_request_id", UUID.class)) + || !requestDigest.equals(head.get("last_request_digest", String.class)) + || billingSequence != positive(head, "tenant_billing_sequence") + || !billingEventId.equals(head.get("tenant_billing_event_id", UUID.class)) + || !billingEventDigest.equals(head.get("tenant_billing_event_digest", String.class))) { + throw new IllegalStateException( + "Tenant authority source checkpoint is absent, stale, or differs from Account current state"); + } + long sequence = positive(head, "last_outbox_sequence"); + String eventId = requiredText(head, "last_event_id"); + String eventDigest = requiredText(head, "last_event_digest"); + AccountAuthorityOutboxRepository.Checkpoint checkpoint = + authorityOutbox + .readCheckpoint(streamKey) + .orElseThrow( + () -> new IllegalStateException("Tenant authority outbox checkpoint is absent")); + if (checkpoint.outboxSequence() != sequence + || !checkpoint.sourceEventId().equals(eventId) + || !checkpoint.sourceEventDigest().equals(eventDigest)) { + throw new IllegalStateException( + "Tenant authority source checkpoint differs from its canonical outbox head"); + } + return readCommittedReceipt( + tenantId, + requestId, + requestDigest, + source, + billingSequence, + billingEventId, + billingEventDigest, + sequence, + eventId, + eventDigest); + } + + /** Resolves current Account owner state itself; callers cannot supply a receipt or checkpoint. */ + @Transactional(propagation = Propagation.MANDATORY, readOnly = true) + public Event readCurrentByTenant(UUID tenantId) { + requireTransaction(); + requireTenant(tenantId); + Record freshIdentity = + dsl.fetchOne( + "SELECT canonical_tenant_id FROM account_fresh_tenant_identity_associations " + + "WHERE canonical_tenant_id = ? FOR SHARE", + tenantId); + if (freshIdentity == null + || !tenantId.equals(freshIdentity.get("canonical_tenant_id", UUID.class))) { + throw new IllegalStateException( + "Exact fresh Account tenant source association is unavailable"); + } + FreshTenantCreationEvidence source = + tenantIdentity + .read(tenantId) + .orElseThrow( + () -> + new IllegalStateException( + "Exact fresh Account tenant source evidence is unavailable")); + ScopeState authority = + generations.read(AccountAuthorityGenerationRepository.AuthorityScope.tenant(tenantId)); + Record current = + dsl.fetchOne( + "SELECT source_schema_version, source_target_namespace, source_creation_request_id, " + + "source_operation_id, source_request_digest, source_game_row_id, " + + "source_game_tenant_key, source_provenance_kind, source_evidence_digest, " + + "entitlement_kind, status, subscription_status, paid, gameplay_available, " + + "allow_public_join, allow_new_gameplay_bindings, allow_new_instance_starts, " + + "max_active_sessions, max_concurrent_game_instances, max_storage_bytes, " + + "entitlement_version, " + + "tenant_authority_generation, tenant_authority_source_version, " + + "tenant_authority_outbox_stream_key, tenant_authority_outbox_sequence, " + + "tenant_authority_event_id, tenant_authority_event_digest, " + + "tenant_billing_sequence, event_id, event_digest, last_request_id, last_request_digest " + + "FROM account_demo_tenant_entitlements WHERE tenant_uuid = ? FOR SHARE", + tenantId); + if (current == null + || !source.equals(sourceFromCurrent(tenantId, current)) + || positive(current, "tenant_authority_generation") != authority.generation() + || positive(current, "tenant_authority_source_version") != authority.sourceVersion() + || !TenantAuthorityEventV1Codec.streamKey(tenantId) + .equals(current.get("tenant_authority_outbox_stream_key", String.class))) { + throw new IllegalStateException( + "Account current tenant entitlement lacks matching fresh source and authority generation"); + } + long billingSequence = positive(current, "tenant_billing_sequence"); + UUID billingEventId = requiredUuid(current, "event_id"); + String billingEventDigest = requiredText(current, "event_digest"); + UUID requestId = requiredUuid(current, "last_request_id"); + String requestDigest = requiredText(current, "last_request_digest"); + long authoritySequence = positive(current, "tenant_authority_outbox_sequence"); + String authorityEventId = requiredText(current, "tenant_authority_event_id"); + String authorityEventDigest = requiredText(current, "tenant_authority_event_digest"); + Event event = + readCurrentCheckpoint( + tenantId, + source, + authority, + requestId, + requestDigest, + billingSequence, + billingEventId, + billingEventDigest); + if (event.outboxSequence() != authoritySequence + || !event.eventId().toString().equals(authorityEventId) + || !event.eventDigest().equals(authorityEventDigest) + || event.tenantAuthorityGeneration() != authority.generation() + || event.tenantAuthoritySourceVersion() != authority.sourceVersion()) { + throw new IllegalStateException( + "Account current tenant row differs from its exact typed authority event"); + } + DemoTenantEntitlementEventV1Codec.Event billingEvent = + billingOutbox + .readEvent(tenantId, billingSequence) + .orElseThrow(() -> new IllegalStateException("Current tenant billing event is absent")); + if (!billingEvent.eventId().equals(billingEventId) + || !billingEvent.eventDigest().equals(billingEventDigest) + || !billingEvent.requestId().equals(requestId) + || !billingEvent.requestDigest().equals(requestDigest) + || !source.equals(billingEvent.sourceEvidence()) + || billingEvent.tenantAuthorityGeneration() != authority.generation() + || billingEvent.tenantAuthoritySourceVersion() != authority.sourceVersion() + || !"NON_PAID_DEMO".equals(current.get("entitlement_kind", String.class)) + || !"ACTIVE".equals(current.get("status", String.class)) + || current.get("subscription_status", String.class) != null + || !Boolean.FALSE.equals(current.get("paid", Boolean.class)) + || positive(current, "entitlement_version") != billingEvent.entitlementVersion() + || !Objects.equals( + current.get("gameplay_available", Boolean.class), billingEvent.gameplayAvailable()) + || !Objects.equals( + current.get("allow_public_join", Boolean.class), billingEvent.allowPublicJoin()) + || !Objects.equals( + current.get("allow_new_gameplay_bindings", Boolean.class), + billingEvent.allowNewGameplayBindings()) + || !Objects.equals( + current.get("allow_new_instance_starts", Boolean.class), + billingEvent.allowNewInstanceStarts()) + || nonnegative(current, "max_active_sessions") != billingEvent.quotas().maxActiveSessions() + || nonnegative(current, "max_concurrent_game_instances") + != billingEvent.quotas().maxConcurrentGameInstances() + || nonnegative(current, "max_storage_bytes") != billingEvent.quotas().maxStorageBytes()) { + throw new IllegalStateException( + "Current tenant entitlement row differs from its exact committed billing event"); + } + return event; + } + + private static FreshTenantCreationEvidence sourceFromCurrent(UUID tenantId, Record current) { + return new FreshTenantCreationEvidence( + current.get("source_schema_version", Integer.class), + requiredText(current, "source_target_namespace"), + requiredUuid(current, "source_creation_request_id"), + requiredUuid(current, "source_operation_id"), + requiredText(current, "source_request_digest"), + tenantId, + positive(current, "source_game_row_id"), + requiredText(current, "source_game_tenant_key"), + requiredText(current, "source_provenance_kind"), + requiredText(current, "source_evidence_digest")); + } + + private static AccountAuthorityOutboxRepository.EventEvidence evidence(Event event) { + return new AccountAuthorityOutboxRepository.EventEvidence( + event.eventId().toString(), event.eventDigest(), event.payload()); + } + + private static void requireExactTenant( + UUID tenantId, FreshTenantCreationEvidence source, ScopeState authority) { + requireTenant(tenantId); + if (source == null + || authority == null + || !tenantId.equals(source.canonicalTenantId()) + || !AccountAuthorityGenerationRepository.AuthorityScope.tenant(tenantId) + .equals(authority.scope()) + || authority.generation() <= 0L + || authority.sourceVersion() <= 0L) { + throw new IllegalArgumentException("Exact fresh tenant authority evidence is required"); + } + } + + private static void requireTenant(UUID tenantId) { + if (tenantId == null || NIL_UUID.equals(tenantId)) { + throw new IllegalArgumentException("Exact tenant UUID is required"); + } + } + + private static void requireTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Tenant authority event operation requires the Account owner transaction"); + } + } + + private static long positive(Record row, String field) { + Long value = row.get(field, Long.class); + if (value == null || value <= 0L) { + throw new IllegalStateException("Tenant authority " + field + " is absent or malformed"); + } + return value; + } + + private static long nonnegative(Record row, String field) { + Long value = row.get(field, Long.class); + if (value == null || value < 0L) { + throw new IllegalStateException("Tenant authority " + field + " is absent or malformed"); + } + return value; + } + + private static long increment(long value, String field) { + try { + return Math.addExact(value, 1L); + } catch (ArithmeticException overflow) { + throw new IllegalStateException("Tenant authority " + field + " is exhausted", overflow); + } + } + + private static String requiredText(Record row, String field) { + String value = row.get(field, String.class); + if (value == null || value.isBlank()) { + throw new IllegalStateException("Tenant authority " + field + " is absent or malformed"); + } + return value; + } + + private static UUID requiredUuid(Record row, String field) { + UUID value = row.get(field, UUID.class); + if (value == null || NIL_UUID.equals(value)) { + throw new IllegalStateException("Tenant authority " + field + " is absent or malformed"); + } + return value; + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantEntitlementOutboxRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantEntitlementOutboxRepository.java new file mode 100644 index 0000000000..e2fe64018a --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantEntitlementOutboxRepository.java @@ -0,0 +1,207 @@ +package net.firedevops.firemud.accountservice.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import java.util.function.LongFunction; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementEventV1Codec; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementEventV1Codec.Event; +import net.firedevops.firemud.accountservice.service.DemoTenantEntitlementException; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Account-owned per-tenant billing/entitlement event stream for demo entitlement currentness. */ +@Repository +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Injected DSLContext is an internal Account transaction collaborator.") +public class AccountTenantEntitlementOutboxRepository { + private static final UUID NIL_UUID = new UUID(0L, 0L); + private final DSLContext dsl; + + public AccountTenantEntitlementOutboxRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl); + } + + public static String streamKey(UUID canonicalTenantId) { + if (canonicalTenantId == null || NIL_UUID.equals(canonicalTenantId)) { + throw new IllegalArgumentException( + "Canonical tenant UUID is required for entitlement stream"); + } + return "account:tenant-entitlement:v1:tenant/" + canonicalTenantId; + } + + /** Appends one event or returns only an exact request and payload replay. */ + @Transactional(propagation = Propagation.MANDATORY) + public Event append(UUID tenantId, UUID requestId, LongFunction eventFactory) { + requireTransaction(); + streamKey(tenantId); + if (requestId == null || NIL_UUID.equals(requestId) || eventFactory == null) { + throw new IllegalArgumentException( + "Exact entitlement request identity and event are required"); + } + String key = streamKey(tenantId); + dsl.execute( + "INSERT INTO account_tenant_entitlement_outbox_streams (tenant_uuid, last_sequence) " + + "VALUES (?, 0) ON CONFLICT (tenant_uuid) DO NOTHING", + tenantId); + Record stream = + dsl.fetchOne( + "SELECT last_sequence FROM account_tenant_entitlement_outbox_streams " + + "WHERE tenant_uuid = ? FOR UPDATE", + tenantId); + long currentSequence = nonnegative(stream, "last_sequence"); + Record priorRequest = + dsl.fetchOne( + "SELECT tenant_billing_sequence, event_id, event_digest, payload " + + "FROM account_tenant_entitlement_outbox_events " + + "WHERE tenant_uuid = ? AND request_id = ?", + tenantId, + requestId); + if (priorRequest != null) { + Event committed = event(tenantId, priorRequest); + Event candidate = + Objects.requireNonNull(eventFactory.apply(committed.tenantBillingSequence())); + if (!matches(committed, candidate) || currentSequence < committed.tenantBillingSequence()) { + throw new DemoTenantEntitlementException( + DemoTenantEntitlementException.Code.IDEMPOTENCY_CONFLICT, + "Tenant entitlement outbox request was reused with different event evidence"); + } + return committed; + } + + long nextSequence; + try { + nextSequence = Math.addExact(currentSequence, 1L); + } catch (ArithmeticException overflow) { + throw new IllegalStateException("Tenant entitlement event sequence is exhausted", overflow); + } + Event candidate = Objects.requireNonNull(eventFactory.apply(nextSequence)); + if (!tenantId.equals(candidate.canonicalTenantId()) + || !requestId.equals(candidate.requestId()) + || !key.equals(candidate.outboxStreamKey()) + || candidate.tenantBillingSequence() != nextSequence) { + throw new IllegalArgumentException("Tenant entitlement event differs from its exact stream"); + } + Record advanced = + dsl.fetchOne( + "UPDATE account_tenant_entitlement_outbox_streams SET last_sequence = ? " + + "WHERE tenant_uuid = ? AND last_sequence = ? RETURNING last_sequence", + nextSequence, + tenantId, + currentSequence); + if (advanced == null) { + throw new IllegalStateException("Tenant entitlement outbox stream changed concurrently"); + } + int inserted = + dsl.execute( + "INSERT INTO account_tenant_entitlement_outbox_events " + + "(tenant_uuid, tenant_billing_sequence, request_id, event_id, event_digest, payload) " + + "VALUES (?, ?, ?, ?, ?, ?)", + tenantId, + nextSequence, + requestId, + candidate.eventId(), + candidate.eventDigest(), + candidate.payload()); + if (inserted != 1) { + throw new IllegalStateException("Tenant entitlement outbox event was not appended"); + } + return candidate; + } + + @Transactional(propagation = Propagation.MANDATORY) + public Optional readCheckpoint(UUID tenantId) { + requireTransaction(); + Record stream = + dsl.fetchOne( + "SELECT last_sequence FROM account_tenant_entitlement_outbox_streams " + + "WHERE tenant_uuid = ? FOR SHARE", + tenantId); + if (stream == null || nonnegative(stream, "last_sequence") == 0L) { + return Optional.empty(); + } + long sequence = positive(stream, "last_sequence"); + Event event = + readEvent(tenantId, sequence) + .orElseThrow( + () -> new IllegalStateException("Tenant entitlement checkpoint has no event")); + return Optional.of( + new Checkpoint( + streamKey(tenantId), + event.tenantBillingSequence(), + event.eventId(), + event.eventDigest())); + } + + @Transactional(propagation = Propagation.MANDATORY) + public Optional readEvent(UUID tenantId, long sequence) { + requireTransaction(); + if (sequence <= 0L) { + throw new IllegalArgumentException("Tenant entitlement event sequence must be positive"); + } + Record row = + dsl.fetchOne( + "SELECT tenant_billing_sequence, request_id, event_id, event_digest, payload " + + "FROM account_tenant_entitlement_outbox_events " + + "WHERE tenant_uuid = ? AND tenant_billing_sequence = ?", + tenantId, + sequence); + return row == null ? Optional.empty() : Optional.of(event(tenantId, row)); + } + + private Event event(UUID tenantId, Record row) { + byte[] payload = row.get("payload", byte[].class); + Event event = DemoTenantEntitlementEventV1Codec.verify(payload); + if (!tenantId.equals(event.canonicalTenantId()) + || row.get("tenant_billing_sequence", Long.class) != event.tenantBillingSequence() + || !row.get("event_id", UUID.class).equals(event.eventId()) + || !row.get("event_digest", String.class).equals(event.eventDigest()) + || !row.get("request_id", UUID.class).equals(event.requestId())) { + throw new IllegalStateException("Stored tenant entitlement event differs from its payload"); + } + return event; + } + + private static boolean matches(Event left, Event right) { + return left.eventId().equals(right.eventId()) + && left.eventDigest().equals(right.eventDigest()) + && java.util.Arrays.equals(left.payload(), right.payload()); + } + + private static long positive(Record row, String field) { + Long value = row == null ? null : row.get(field, Long.class); + if (value == null || value <= 0L) { + throw new IllegalStateException("Tenant entitlement outbox " + field + " is malformed"); + } + return value; + } + + private static long nonnegative(Record row, String field) { + Long value = row == null ? null : row.get(field, Long.class); + if (value == null || value < 0L) { + throw new IllegalStateException("Tenant entitlement outbox " + field + " is malformed"); + } + return value; + } + + private static void requireTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException("Tenant entitlement outbox requires an owner transaction"); + } + } + + public record Checkpoint( + String outboxStreamKey, long sequence, UUID eventId, String eventDigest) { + public Checkpoint { + if (outboxStreamKey == null || sequence <= 0L || eventId == null || eventDigest == null) { + throw new IllegalArgumentException("Complete tenant entitlement checkpoint is required"); + } + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/DemoTenantEntitlementException.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/DemoTenantEntitlementException.java new file mode 100644 index 0000000000..f0950da2b1 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/DemoTenantEntitlementException.java @@ -0,0 +1,31 @@ +package net.firedevops.firemud.accountservice.service; + +/** Typed fail-closed outcomes for Account's protected non-paid demo entitlement slice. */ +public final class DemoTenantEntitlementException extends IllegalStateException { + private final Code code; + + public DemoTenantEntitlementException(Code code, String message) { + super(message); + this.code = code; + } + + public DemoTenantEntitlementException(Code code, String message, Throwable cause) { + super(message, cause); + this.code = code; + } + + public Code code() { + return code; + } + + public enum Code { + FIXTURE_DISABLED, + ENVIRONMENT_DENIED, + SOURCE_EVIDENCE_INVALID, + IDEMPOTENCY_CONFLICT, + ENTITLEMENT_VERSION_CONFLICT, + TENANT_AUTHORITY_STALE, + ENTITLEMENT_UNAVAILABLE, + STALE_ADMISSION_EVIDENCE + } +} diff --git a/services/account-service/src/main/resources/db/migration/V53__account_protected_demo_entitlements.sql b/services/account-service/src/main/resources/db/migration/V53__account_protected_demo_entitlements.sql new file mode 100644 index 0000000000..3c9fdf95bb --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V53__account_protected_demo_entitlements.sql @@ -0,0 +1,427 @@ +-- Explicit, protected-fixture-only non-paid entitlement state. Tenant identity is UUID-native; +-- source row IDs are retained solely as authenticated provenance. +CREATE TABLE account_tenant_entitlement_outbox_streams ( + tenant_uuid UUID PRIMARY KEY + REFERENCES account_fresh_tenant_identity_associations (canonical_tenant_id) ON DELETE RESTRICT, + last_sequence BIGINT NOT NULL DEFAULT 0 CHECK (last_sequence >= 0), + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP +); + +CREATE TABLE account_tenant_entitlement_outbox_events ( + tenant_uuid UUID NOT NULL, + tenant_billing_sequence BIGINT NOT NULL CHECK (tenant_billing_sequence > 0), + request_id UUID NOT NULL CHECK (request_id <> '00000000-0000-0000-0000-000000000000'::UUID), + event_id UUID NOT NULL UNIQUE CHECK (event_id <> '00000000-0000-0000-0000-000000000000'::UUID), + event_digest VARCHAR(71) NOT NULL CHECK (event_digest ~ '^sha256:[0-9a-f]{64}$'), + payload BYTEA NOT NULL CHECK (octet_length(payload) BETWEEN 1 AND 32768), + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (tenant_uuid, tenant_billing_sequence), + UNIQUE (tenant_uuid, request_id), + UNIQUE (tenant_uuid, tenant_billing_sequence, event_id, event_digest), + FOREIGN KEY (tenant_uuid) REFERENCES account_tenant_entitlement_outbox_streams (tenant_uuid) + ON DELETE RESTRICT DEFERRABLE INITIALLY DEFERRED +); + +CREATE TABLE account_demo_tenant_entitlement_operations ( + request_id UUID PRIMARY KEY CHECK (request_id <> '00000000-0000-0000-0000-000000000000'::UUID), + tenant_uuid UUID NOT NULL + REFERENCES account_fresh_tenant_identity_associations (canonical_tenant_id) ON DELETE RESTRICT, + request_digest VARCHAR(71) NOT NULL CHECK (request_digest ~ '^sha256:[0-9a-f]{64}$'), + source_creation_request_id UUID NOT NULL, + source_request_digest VARCHAR(71) NOT NULL CHECK (source_request_digest ~ '^sha256:[0-9a-f]{64}$'), + source_operation_id UUID NOT NULL, + source_evidence_digest VARCHAR(71) NOT NULL CHECK (source_evidence_digest ~ '^sha256:[0-9a-f]{64}$'), + status VARCHAR(16) NOT NULL CHECK (status IN ('PENDING', 'COMMITTED')), + tenant_billing_sequence BIGINT, + event_id UUID, + event_digest VARCHAR(71), + entitlement_version BIGINT, + tenant_authority_generation BIGINT, + tenant_authority_source_version BIGINT, + committed_at TIMESTAMPTZ, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT account_demo_entitlement_operation_receipt_shape CHECK ( + (status = 'PENDING' AND tenant_billing_sequence IS NULL AND event_id IS NULL + AND event_digest IS NULL AND entitlement_version IS NULL + AND tenant_authority_generation IS NULL AND tenant_authority_source_version IS NULL + AND committed_at IS NULL) + OR + (status = 'COMMITTED' AND tenant_billing_sequence IS NOT NULL AND tenant_billing_sequence > 0 + AND event_id IS NOT NULL + AND event_digest IS NOT NULL AND event_digest ~ '^sha256:[0-9a-f]{64}$' + AND entitlement_version IS NOT NULL AND entitlement_version > 0 + AND tenant_authority_generation IS NOT NULL AND tenant_authority_generation > 0 + AND tenant_authority_source_version IS NOT NULL AND tenant_authority_source_version > 0 + AND committed_at IS NOT NULL) + ), + UNIQUE (tenant_uuid, request_id), + FOREIGN KEY (tenant_uuid, tenant_billing_sequence, event_id, event_digest) + REFERENCES account_tenant_entitlement_outbox_events + (tenant_uuid, tenant_billing_sequence, event_id, event_digest) + DEFERRABLE INITIALLY DEFERRED +); + +CREATE TABLE account_demo_tenant_entitlements ( + tenant_uuid UUID PRIMARY KEY + REFERENCES account_fresh_tenant_identity_associations (canonical_tenant_id) ON DELETE RESTRICT, + source_schema_version INTEGER NOT NULL CHECK (source_schema_version = 1), + source_target_namespace VARCHAR(128) NOT NULL + CHECK (source_target_namespace ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$'), + source_creation_request_id UUID NOT NULL, + source_operation_id UUID NOT NULL, + source_request_digest VARCHAR(71) NOT NULL CHECK (source_request_digest ~ '^sha256:[0-9a-f]{64}$'), + source_game_row_id BIGINT NOT NULL CHECK (source_game_row_id > 0), + source_game_tenant_key VARCHAR(36) NOT NULL CHECK (char_length(source_game_tenant_key) BETWEEN 1 AND 36), + source_provenance_kind VARCHAR(32) NOT NULL CHECK (source_provenance_kind = 'NEW_GAME_ROW'), + source_evidence_digest VARCHAR(71) NOT NULL CHECK (source_evidence_digest ~ '^sha256:[0-9a-f]{64}$'), + entitlement_kind VARCHAR(32) NOT NULL DEFAULT 'NON_PAID_DEMO' CHECK (entitlement_kind = 'NON_PAID_DEMO'), + status VARCHAR(16) NOT NULL DEFAULT 'ACTIVE' CHECK (status = 'ACTIVE'), + subscription_status VARCHAR(32) CHECK (subscription_status IS NULL), + paid BOOLEAN NOT NULL DEFAULT FALSE CHECK (paid = FALSE), + gameplay_available BOOLEAN NOT NULL, + allow_public_join BOOLEAN NOT NULL, + allow_new_gameplay_bindings BOOLEAN NOT NULL, + allow_new_instance_starts BOOLEAN NOT NULL, + max_active_sessions BIGINT NOT NULL CHECK (max_active_sessions >= 0), + max_concurrent_game_instances BIGINT NOT NULL CHECK (max_concurrent_game_instances >= 0), + max_storage_bytes BIGINT NOT NULL CHECK (max_storage_bytes >= 0), + entitlement_version BIGINT NOT NULL CHECK (entitlement_version > 0), + tenant_authority_generation BIGINT NOT NULL CHECK (tenant_authority_generation > 0), + tenant_authority_source_version BIGINT NOT NULL CHECK (tenant_authority_source_version > 0), + tenant_billing_sequence BIGINT NOT NULL CHECK (tenant_billing_sequence > 0), + event_id UUID NOT NULL, + event_digest VARCHAR(71) NOT NULL CHECK (event_digest ~ '^sha256:[0-9a-f]{64}$'), + last_request_id UUID NOT NULL, + last_request_digest VARCHAR(71) NOT NULL CHECK (last_request_digest ~ '^sha256:[0-9a-f]{64}$'), + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + FOREIGN KEY (tenant_uuid, tenant_billing_sequence, event_id, event_digest) + REFERENCES account_tenant_entitlement_outbox_events + (tenant_uuid, tenant_billing_sequence, event_id, event_digest) + DEFERRABLE INITIALLY DEFERRED, + FOREIGN KEY (tenant_uuid, last_request_id) + REFERENCES account_demo_tenant_entitlement_operations (tenant_uuid, request_id) + DEFERRABLE INITIALLY DEFERRED +); + +-- [jooq ignore start] +CREATE FUNCTION account_tenant_entitlement_stream_guard() RETURNS trigger AS $$ +BEGIN + IF TG_OP = 'INSERT' THEN + IF NEW.last_sequence <> 0 THEN + RAISE EXCEPTION 'Tenant entitlement stream must begin at sequence zero' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; + END IF; + IF TG_OP <> 'UPDATE' + OR NEW.tenant_uuid IS DISTINCT FROM OLD.tenant_uuid + OR NEW.last_sequence <> OLD.last_sequence + 1 THEN + RAISE EXCEPTION 'Tenant entitlement stream is immutable and advances by exactly one' + USING ERRCODE = '23514'; + END IF; + NEW.updated_at = CURRENT_TIMESTAMP; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE FUNCTION account_tenant_entitlement_outbox_event_guard() RETURNS trigger AS $$ +DECLARE + current_sequence BIGINT; +BEGIN + IF TG_OP <> 'INSERT' THEN + RAISE EXCEPTION 'Tenant entitlement outbox events are immutable' + USING ERRCODE = '23514'; + END IF; + SELECT last_sequence INTO current_sequence FROM account_tenant_entitlement_outbox_streams + WHERE tenant_uuid = NEW.tenant_uuid; + IF current_sequence IS DISTINCT FROM NEW.tenant_billing_sequence THEN + RAISE EXCEPTION 'Tenant entitlement event does not match its stream checkpoint' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE FUNCTION account_tenant_entitlement_stream_consistency() RETURNS trigger AS $$ +DECLARE + stream_tenant UUID; + stream_sequence BIGINT; + max_sequence BIGINT; + event_count BIGINT; +BEGIN + stream_tenant := COALESCE(NEW.tenant_uuid, OLD.tenant_uuid); + SELECT last_sequence INTO stream_sequence FROM account_tenant_entitlement_outbox_streams + WHERE tenant_uuid = stream_tenant; + SELECT COALESCE(MAX(tenant_billing_sequence), 0), COUNT(*) + INTO max_sequence, event_count FROM account_tenant_entitlement_outbox_events + WHERE tenant_uuid = stream_tenant; + IF stream_sequence IS NULL OR stream_sequence <> max_sequence OR stream_sequence <> event_count THEN + RAISE EXCEPTION 'Tenant entitlement outbox stream and events are inconsistent' + USING ERRCODE = '23514'; + END IF; + RETURN NULL; +END; +$$ LANGUAGE plpgsql; + +CREATE FUNCTION account_demo_entitlement_operation_guard() RETURNS trigger AS $$ +BEGIN + IF TG_OP = 'INSERT' THEN + IF NEW.status <> 'PENDING' THEN + RAISE EXCEPTION 'Demo entitlement operation must start pending' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; + END IF; + IF TG_OP <> 'UPDATE' OR OLD.status <> 'PENDING' OR NEW.status <> 'COMMITTED' + OR NEW.request_id IS DISTINCT FROM OLD.request_id + OR NEW.tenant_uuid IS DISTINCT FROM OLD.tenant_uuid + OR NEW.request_digest IS DISTINCT FROM OLD.request_digest + OR NEW.source_creation_request_id IS DISTINCT FROM OLD.source_creation_request_id + OR NEW.source_request_digest IS DISTINCT FROM OLD.source_request_digest + OR NEW.source_operation_id IS DISTINCT FROM OLD.source_operation_id + OR NEW.source_evidence_digest IS DISTINCT FROM OLD.source_evidence_digest THEN + RAISE EXCEPTION 'Demo entitlement operation identity is immutable' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE FUNCTION account_demo_entitlement_current_guard() RETURNS trigger AS $$ +DECLARE + authority_generation BIGINT; + authority_source_version BIGINT; + source_matches BOOLEAN; +BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'Demo entitlement state cannot be deleted' + USING ERRCODE = '23514'; + END IF; + IF TG_OP = 'UPDATE' THEN + IF NEW.tenant_uuid IS DISTINCT FROM OLD.tenant_uuid + OR NEW.source_schema_version IS DISTINCT FROM OLD.source_schema_version + OR NEW.source_target_namespace IS DISTINCT FROM OLD.source_target_namespace + OR NEW.source_creation_request_id IS DISTINCT FROM OLD.source_creation_request_id + OR NEW.source_operation_id IS DISTINCT FROM OLD.source_operation_id + OR NEW.source_request_digest IS DISTINCT FROM OLD.source_request_digest + OR NEW.source_game_row_id IS DISTINCT FROM OLD.source_game_row_id + OR NEW.source_game_tenant_key IS DISTINCT FROM OLD.source_game_tenant_key + OR NEW.source_provenance_kind IS DISTINCT FROM OLD.source_provenance_kind + OR NEW.source_evidence_digest IS DISTINCT FROM OLD.source_evidence_digest + OR NEW.entitlement_version <> OLD.entitlement_version + 1 THEN + RAISE EXCEPTION 'Demo entitlement identity is immutable and version advances by one' + USING ERRCODE = '23514'; + END IF; + NEW.updated_at = CURRENT_TIMESTAMP; + ELSIF NEW.entitlement_version <> 1 THEN + RAISE EXCEPTION 'Demo entitlement must begin at version one' + USING ERRCODE = '23514'; + END IF; + SELECT generation, source_version INTO authority_generation, authority_source_version + FROM account_authority_generations + WHERE scope_kind = 'TENANT' AND tenant_uuid = NEW.tenant_uuid; + IF authority_generation IS DISTINCT FROM NEW.tenant_authority_generation + OR authority_source_version IS DISTINCT FROM NEW.tenant_authority_source_version THEN + RAISE EXCEPTION 'Demo entitlement is not fenced by current tenant authority' + USING ERRCODE = '23514'; + END IF; + SELECT EXISTS ( + SELECT 1 FROM account_fresh_tenant_identity_associations fresh + WHERE fresh.canonical_tenant_id = NEW.tenant_uuid + AND fresh.schema_version = NEW.source_schema_version + AND fresh.target_namespace = NEW.source_target_namespace + AND fresh.creation_request_id = NEW.source_creation_request_id + AND fresh.operation_id = NEW.source_operation_id + AND fresh.request_digest = NEW.source_request_digest + AND fresh.source_game_row_id = NEW.source_game_row_id + AND fresh.source_game_tenant_key = NEW.source_game_tenant_key + AND fresh.provenance_kind = NEW.source_provenance_kind + AND fresh.evidence_digest = NEW.source_evidence_digest + ) INTO source_matches; + IF NOT source_matches THEN + RAISE EXCEPTION 'Demo entitlement requires exact fresh Game Design source evidence' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE FUNCTION account_demo_entitlement_operation_terminal_guard() RETURNS trigger AS $$ +DECLARE + operation_status VARCHAR(16); + operation_tenant UUID; + operation_sequence BIGINT; + operation_event_id UUID; + operation_event_digest VARCHAR(71); + operation_request_digest VARCHAR(71); + operation_entitlement_version BIGINT; + operation_authority_generation BIGINT; + operation_authority_source_version BIGINT; + operation_source_creation_request_id UUID; + operation_source_request_digest VARCHAR(71); + operation_source_operation_id UUID; + operation_source_evidence_digest VARCHAR(71); + event_payload JSONB; +BEGIN + SELECT status, tenant_uuid, tenant_billing_sequence, event_id, event_digest, request_digest, + entitlement_version, tenant_authority_generation, tenant_authority_source_version, + source_creation_request_id, source_request_digest, source_operation_id, + source_evidence_digest + INTO operation_status, operation_tenant, operation_sequence, operation_event_id, + operation_event_digest, operation_request_digest, operation_entitlement_version, + operation_authority_generation, operation_authority_source_version, + operation_source_creation_request_id, operation_source_request_digest, + operation_source_operation_id, operation_source_evidence_digest + FROM account_demo_tenant_entitlement_operations + WHERE request_id = NEW.request_id; + IF operation_status IS DISTINCT FROM 'COMMITTED' THEN + RAISE EXCEPTION 'Demo entitlement operation cannot commit pending' + USING ERRCODE = '23514'; + END IF; + SELECT convert_from(event.payload, 'UTF8')::JSONB INTO event_payload + FROM account_tenant_entitlement_outbox_events event + WHERE event.tenant_uuid = operation_tenant + AND event.tenant_billing_sequence = operation_sequence + AND event.event_id = operation_event_id + AND event.event_digest = operation_event_digest; + IF event_payload IS NULL + OR event_payload->>'requestId' IS DISTINCT FROM NEW.request_id::TEXT + OR event_payload->>'requestDigest' IS DISTINCT FROM operation_request_digest + OR event_payload->>'tenantId' IS DISTINCT FROM operation_tenant::TEXT + OR event_payload->>'tenantBillingSequence' IS DISTINCT FROM operation_sequence::TEXT + OR event_payload->>'eventId' IS DISTINCT FROM operation_event_id::TEXT + OR event_payload->>'eventDigest' IS DISTINCT FROM operation_event_digest + OR event_payload->>'entitlementVersion' IS DISTINCT FROM operation_entitlement_version::TEXT + OR event_payload->>'tenantAuthorityGeneration' + IS DISTINCT FROM operation_authority_generation::TEXT + OR event_payload->>'tenantAuthoritySourceVersion' + IS DISTINCT FROM operation_authority_source_version::TEXT + OR event_payload->'sourceEvidence'->>'creationRequestId' + IS DISTINCT FROM operation_source_creation_request_id::TEXT + OR event_payload->'sourceEvidence'->>'requestDigest' + IS DISTINCT FROM operation_source_request_digest + OR event_payload->'sourceEvidence'->>'operationId' + IS DISTINCT FROM operation_source_operation_id::TEXT + OR event_payload->'sourceEvidence'->>'evidenceDigest' + IS DISTINCT FROM operation_source_evidence_digest THEN + RAISE EXCEPTION 'Demo entitlement operation receipt differs from its exact event' + USING ERRCODE = '23514'; + END IF; + IF NOT EXISTS ( + SELECT 1 FROM account_fresh_tenant_identity_associations fresh + WHERE fresh.canonical_tenant_id = operation_tenant + AND fresh.creation_request_id = operation_source_creation_request_id + AND fresh.request_digest = operation_source_request_digest + AND fresh.operation_id = operation_source_operation_id + AND fresh.evidence_digest = operation_source_evidence_digest + AND fresh.provenance_kind = 'NEW_GAME_ROW' + ) THEN + RAISE EXCEPTION 'Demo entitlement operation has no exact fresh tenant source' + USING ERRCODE = '23514'; + END IF; + RETURN NULL; +END; +$$ LANGUAGE plpgsql; + +CREATE FUNCTION account_demo_entitlement_current_event_guard() RETURNS trigger AS $$ +DECLARE + payload JSONB; +BEGIN + SELECT convert_from(event.payload, 'UTF8')::JSONB INTO payload + FROM account_tenant_entitlement_outbox_events event + WHERE event.tenant_uuid = NEW.tenant_uuid + AND event.tenant_billing_sequence = NEW.tenant_billing_sequence + AND event.event_id = NEW.event_id + AND event.event_digest = NEW.event_digest; + IF payload IS NULL + OR payload->>'schemaVersion' IS DISTINCT FROM 'account-tenant-entitlement-event/v1' + OR payload->>'eventType' IS DISTINCT FROM 'TENANT_ENTITLEMENT_CHANGED' + OR payload->>'outboxStreamKey' IS DISTINCT FROM + ('account:tenant-entitlement:v1:tenant/' || NEW.tenant_uuid::TEXT) + OR payload->>'tenantId' IS DISTINCT FROM NEW.tenant_uuid::TEXT + OR payload->>'tenantBillingSequence' IS DISTINCT FROM NEW.tenant_billing_sequence::TEXT + OR payload->>'eventId' IS DISTINCT FROM NEW.event_id::TEXT + OR payload->>'eventDigest' IS DISTINCT FROM NEW.event_digest + OR payload->>'requestId' IS DISTINCT FROM NEW.last_request_id::TEXT + OR payload->>'requestDigest' IS DISTINCT FROM NEW.last_request_digest + OR payload->>'entitlementVersion' IS DISTINCT FROM NEW.entitlement_version::TEXT + OR payload->>'tenantAuthorityGeneration' IS DISTINCT FROM NEW.tenant_authority_generation::TEXT + OR payload->>'tenantAuthoritySourceVersion' IS DISTINCT FROM NEW.tenant_authority_source_version::TEXT + OR payload->>'entitlementKind' IS DISTINCT FROM NEW.entitlement_kind + OR payload->>'status' IS DISTINCT FROM NEW.status + OR payload->>'paid' IS DISTINCT FROM 'false' + OR payload->>'gameplayAvailable' IS DISTINCT FROM NEW.gameplay_available::TEXT + OR payload->>'allowPublicJoin' IS DISTINCT FROM NEW.allow_public_join::TEXT + OR payload->>'allowNewGameplayBindings' IS DISTINCT FROM NEW.allow_new_gameplay_bindings::TEXT + OR payload->>'allowNewInstanceStarts' IS DISTINCT FROM NEW.allow_new_instance_starts::TEXT + OR payload->'quotas'->>'maxActiveSessions' IS DISTINCT FROM NEW.max_active_sessions::TEXT + OR payload->'quotas'->>'maxConcurrentGameInstances' IS DISTINCT FROM NEW.max_concurrent_game_instances::TEXT + OR payload->'quotas'->>'maxStorageBytes' IS DISTINCT FROM NEW.max_storage_bytes::TEXT + OR payload->'sourceEvidence'->>'schemaVersion' IS DISTINCT FROM NEW.source_schema_version::TEXT + OR payload->'sourceEvidence'->>'targetNamespace' IS DISTINCT FROM NEW.source_target_namespace + OR payload->'sourceEvidence'->>'creationRequestId' IS DISTINCT FROM NEW.source_creation_request_id::TEXT + OR payload->'sourceEvidence'->>'operationId' IS DISTINCT FROM NEW.source_operation_id::TEXT + OR payload->'sourceEvidence'->>'requestDigest' IS DISTINCT FROM NEW.source_request_digest + OR payload->'sourceEvidence'->>'canonicalTenantId' IS DISTINCT FROM NEW.tenant_uuid::TEXT + OR payload->'sourceEvidence'->>'sourceGameRowId' IS DISTINCT FROM NEW.source_game_row_id::TEXT + OR payload->'sourceEvidence'->>'sourceGameTenantKey' IS DISTINCT FROM NEW.source_game_tenant_key + OR payload->'sourceEvidence'->>'provenanceKind' IS DISTINCT FROM NEW.source_provenance_kind + OR payload->'sourceEvidence'->>'evidenceDigest' IS DISTINCT FROM NEW.source_evidence_digest THEN + RAISE EXCEPTION 'Demo entitlement state differs from its canonical outbox event' + USING ERRCODE = '23514'; + END IF; + RETURN NULL; +END; +$$ LANGUAGE plpgsql; + +CREATE FUNCTION account_demo_entitlement_reject_truncate() RETURNS trigger AS $$ +BEGIN + RAISE EXCEPTION 'Account demo entitlement history cannot be truncated' + USING ERRCODE = '23514'; + RETURN NULL; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER account_tenant_entitlement_stream_guard + BEFORE INSERT OR UPDATE OR DELETE ON account_tenant_entitlement_outbox_streams + FOR EACH ROW EXECUTE FUNCTION account_tenant_entitlement_stream_guard(); +CREATE TRIGGER account_tenant_entitlement_stream_no_truncate + BEFORE TRUNCATE ON account_tenant_entitlement_outbox_streams + FOR EACH STATEMENT EXECUTE FUNCTION account_demo_entitlement_reject_truncate(); +CREATE TRIGGER account_tenant_entitlement_event_guard + BEFORE INSERT OR UPDATE OR DELETE ON account_tenant_entitlement_outbox_events + FOR EACH ROW EXECUTE FUNCTION account_tenant_entitlement_outbox_event_guard(); +CREATE TRIGGER account_tenant_entitlement_event_no_truncate + BEFORE TRUNCATE ON account_tenant_entitlement_outbox_events + FOR EACH STATEMENT EXECUTE FUNCTION account_demo_entitlement_reject_truncate(); +CREATE CONSTRAINT TRIGGER account_tenant_entitlement_stream_consistency_stream + AFTER INSERT OR UPDATE ON account_tenant_entitlement_outbox_streams + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW + EXECUTE FUNCTION account_tenant_entitlement_stream_consistency(); +CREATE CONSTRAINT TRIGGER account_tenant_entitlement_stream_consistency_event + AFTER INSERT ON account_tenant_entitlement_outbox_events + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW + EXECUTE FUNCTION account_tenant_entitlement_stream_consistency(); +CREATE TRIGGER account_demo_entitlement_operation_guard + BEFORE INSERT OR UPDATE OR DELETE ON account_demo_tenant_entitlement_operations + FOR EACH ROW EXECUTE FUNCTION account_demo_entitlement_operation_guard(); +CREATE TRIGGER account_demo_entitlement_operation_no_truncate + BEFORE TRUNCATE ON account_demo_tenant_entitlement_operations + FOR EACH STATEMENT EXECUTE FUNCTION account_demo_entitlement_reject_truncate(); +CREATE CONSTRAINT TRIGGER account_demo_entitlement_operation_terminal + AFTER INSERT OR UPDATE ON account_demo_tenant_entitlement_operations + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW + EXECUTE FUNCTION account_demo_entitlement_operation_terminal_guard(); +CREATE TRIGGER account_demo_entitlement_current_guard + BEFORE INSERT OR UPDATE OR DELETE ON account_demo_tenant_entitlements + FOR EACH ROW EXECUTE FUNCTION account_demo_entitlement_current_guard(); +CREATE TRIGGER account_demo_entitlement_current_no_truncate + BEFORE TRUNCATE ON account_demo_tenant_entitlements + FOR EACH STATEMENT EXECUTE FUNCTION account_demo_entitlement_reject_truncate(); +CREATE CONSTRAINT TRIGGER account_demo_entitlement_current_event + AFTER INSERT OR UPDATE ON account_demo_tenant_entitlements + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW + EXECUTE FUNCTION account_demo_entitlement_current_event_guard(); +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V73__account_tenant_authority_source_bridge.sql b/services/account-service/src/main/resources/db/migration/V73__account_tenant_authority_source_bridge.sql new file mode 100644 index 0000000000..8b4bdc5fdd --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V73__account_tenant_authority_source_bridge.sql @@ -0,0 +1,471 @@ +-- Preserve source-owner initialization provenance for future exact tenant-authority enrollment. +-- Existing rows remain NULL and are deliberately not assigned a synthetic generation-one proof. +ALTER TABLE account_fresh_tenant_identity_associations + ADD COLUMN authority_source_transaction_id BIGINT; +ALTER TABLE account_fresh_tenant_identity_associations + ADD CONSTRAINT account_fresh_tenant_authority_source_transaction_check + CHECK (authority_source_transaction_id IS NULL OR authority_source_transaction_id > 0); + +-- This is an Account-owned typed head over the generic authority outbox, not a second event log. +-- A sequence-zero row exists only inside the first authority transaction and cannot commit. +CREATE TABLE account_tenant_authority_source_records ( + outbox_stream_key VARCHAR(2048) PRIMARY KEY + REFERENCES account_authority_outbox_streams (outbox_stream_key) ON DELETE RESTRICT, + tenant_uuid UUID NOT NULL UNIQUE + REFERENCES account_fresh_tenant_identity_associations (canonical_tenant_id) ON DELETE RESTRICT, + initialization_transaction_id BIGINT NOT NULL CHECK (initialization_transaction_id > 0), + baseline_generation BIGINT NOT NULL DEFAULT 1 CHECK (baseline_generation = 1), + baseline_source_version BIGINT NOT NULL DEFAULT 1 CHECK (baseline_source_version = 1), + current_generation BIGINT NOT NULL CHECK (current_generation > 0), + current_source_version BIGINT NOT NULL CHECK (current_source_version > 0), + last_outbox_sequence BIGINT NOT NULL DEFAULT 0 CHECK (last_outbox_sequence >= 0), + last_request_id UUID, + last_request_digest VARCHAR(71), + last_event_id VARCHAR(512), + last_event_digest VARCHAR(71), + tenant_billing_sequence BIGINT, + tenant_billing_event_id UUID, + tenant_billing_event_digest VARCHAR(71), + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT account_tenant_authority_source_key_check CHECK ( + outbox_stream_key = 'account:auth-authority:v1:tenant/' || tenant_uuid::TEXT), + CONSTRAINT account_tenant_authority_source_version_check CHECK ( + current_generation = baseline_generation + last_outbox_sequence + AND current_source_version = baseline_source_version + last_outbox_sequence), + CONSTRAINT account_tenant_authority_source_head_check CHECK ( + (last_outbox_sequence = 0 AND last_request_id IS NULL AND last_request_digest IS NULL + AND last_event_id IS NULL AND last_event_digest IS NULL + AND tenant_billing_sequence IS NULL AND tenant_billing_event_id IS NULL + AND tenant_billing_event_digest IS NULL) + OR (last_outbox_sequence > 0 AND last_request_id IS NOT NULL + AND last_request_digest ~ '^sha256:[0-9a-f]{64}$' + AND last_event_id IS NOT NULL AND length(btrim(last_event_id)) > 0 + AND last_event_digest ~ '^sha256:[0-9a-f]{64}$' + AND tenant_billing_sequence > 0 AND tenant_billing_event_id IS NOT NULL + AND tenant_billing_event_digest ~ '^sha256:[0-9a-f]{64}$')) +); + +ALTER TABLE account_demo_tenant_entitlement_operations + ADD COLUMN tenant_authority_outbox_stream_key VARCHAR(2048), + ADD COLUMN tenant_authority_outbox_sequence BIGINT, + ADD COLUMN tenant_authority_event_id VARCHAR(512), + ADD COLUMN tenant_authority_event_digest VARCHAR(71); +-- [jooq ignore start] +-- PostgreSQL retains historical rows without validating this new source receipt constraint. +ALTER TABLE account_demo_tenant_entitlement_operations + ADD CONSTRAINT account_demo_entitlement_authority_receipt_shape CHECK ( + (status = 'PENDING' AND tenant_authority_outbox_stream_key IS NULL + AND tenant_authority_outbox_sequence IS NULL AND tenant_authority_event_id IS NULL + AND tenant_authority_event_digest IS NULL) + OR (status = 'COMMITTED' AND tenant_authority_outbox_stream_key IS NOT NULL + AND tenant_authority_outbox_sequence > 0 + AND tenant_authority_event_id IS NOT NULL + AND tenant_authority_event_digest ~ '^sha256:[0-9a-f]{64}$')) NOT VALID; +-- [jooq ignore stop] +ALTER TABLE account_demo_tenant_entitlement_operations + ADD CONSTRAINT account_demo_tenant_entitlement_operations_authority_event_fk + FOREIGN KEY (tenant_authority_outbox_stream_key, tenant_authority_outbox_sequence) + REFERENCES account_authority_outbox_events (outbox_stream_key, outbox_sequence) + ON DELETE RESTRICT DEFERRABLE INITIALLY DEFERRED; + +ALTER TABLE account_demo_tenant_entitlements + ADD COLUMN tenant_authority_outbox_stream_key VARCHAR(2048), + ADD COLUMN tenant_authority_outbox_sequence BIGINT, + ADD COLUMN tenant_authority_event_id VARCHAR(512), + ADD COLUMN tenant_authority_event_digest VARCHAR(71); +-- [jooq ignore start] +-- PostgreSQL retains historical rows without validating this new source head constraint. +ALTER TABLE account_demo_tenant_entitlements + ADD CONSTRAINT account_demo_entitlement_authority_head_shape CHECK ( + (tenant_authority_outbox_stream_key IS NULL AND tenant_authority_outbox_sequence IS NULL + AND tenant_authority_event_id IS NULL AND tenant_authority_event_digest IS NULL) + OR (tenant_authority_outbox_stream_key IS NOT NULL + AND tenant_authority_outbox_sequence > 0 AND tenant_authority_event_id IS NOT NULL + AND tenant_authority_event_digest ~ '^sha256:[0-9a-f]{64}$')) NOT VALID; +-- [jooq ignore stop] +ALTER TABLE account_demo_tenant_entitlements + ADD CONSTRAINT account_demo_tenant_entitlements_authority_event_fk + FOREIGN KEY (tenant_authority_outbox_stream_key, tenant_authority_outbox_sequence) + REFERENCES account_authority_outbox_events (outbox_stream_key, outbox_sequence) + ON DELETE RESTRICT DEFERRABLE INITIALLY DEFERRED; + +-- Only Account's fresh tenant import path stamps this transaction ID. Retained rows are untouched. +-- [jooq ignore start] +CREATE FUNCTION account_fresh_tenant_authority_source_transaction_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + NEW.authority_source_transaction_id := txid_current(); + RETURN NEW; +END; +$$; + +CREATE TRIGGER account_fresh_tenant_authority_source_transaction + BEFORE INSERT ON account_fresh_tenant_identity_associations + FOR EACH ROW EXECUTE FUNCTION account_fresh_tenant_authority_source_transaction_guard(); + +CREATE FUNCTION account_tenant_authority_source_insert_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + fresh_row RECORD; + generation_row RECORD; + stream_sequence BIGINT; +BEGIN + SELECT authority_source_transaction_id, provenance_kind INTO fresh_row + FROM account_fresh_tenant_identity_associations + WHERE canonical_tenant_id = NEW.tenant_uuid; + SELECT generation, source_version, created_transaction_id INTO generation_row + FROM account_authority_generations + WHERE scope_kind = 'TENANT' AND tenant_uuid = NEW.tenant_uuid; + SELECT last_sequence INTO stream_sequence FROM account_authority_outbox_streams + WHERE outbox_stream_key = NEW.outbox_stream_key; + IF NEW.outbox_stream_key <> 'account:auth-authority:v1:tenant/' || NEW.tenant_uuid::TEXT + OR NEW.initialization_transaction_id IS NULL + OR fresh_row.authority_source_transaction_id IS DISTINCT FROM NEW.initialization_transaction_id + OR fresh_row.provenance_kind IS DISTINCT FROM 'NEW_GAME_ROW' + OR generation_row.created_transaction_id IS DISTINCT FROM NEW.initialization_transaction_id + OR generation_row.generation IS DISTINCT FROM 1 + OR generation_row.source_version IS DISTINCT FROM 1 + OR stream_sequence IS DISTINCT FROM 0 + OR NEW.baseline_generation IS DISTINCT FROM 1 + OR NEW.baseline_source_version IS DISTINCT FROM 1 + OR NEW.current_generation IS DISTINCT FROM 1 + OR NEW.current_source_version IS DISTINCT FROM 1 + OR NEW.last_outbox_sequence IS DISTINCT FROM 0 + OR NEW.last_event_id IS NOT NULL OR NEW.last_event_digest IS NOT NULL + OR EXISTS (SELECT 1 FROM account_authority_outbox_events + WHERE outbox_stream_key = NEW.outbox_stream_key) THEN + RAISE EXCEPTION 'Tenant authority baseline lacks fresh Account source initialization proof' + USING ERRCODE = '23514', CONSTRAINT = 'account_tenant_authority_source_baseline'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_tenant_authority_source_update_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + authority_event RECORD; + payload JSONB; + billing_event RECORD; + fresh_row RECORD; +BEGIN + IF NEW.outbox_stream_key IS DISTINCT FROM OLD.outbox_stream_key + OR NEW.tenant_uuid IS DISTINCT FROM OLD.tenant_uuid + OR NEW.initialization_transaction_id IS DISTINCT FROM OLD.initialization_transaction_id + OR NEW.baseline_generation IS DISTINCT FROM OLD.baseline_generation + OR NEW.baseline_source_version IS DISTINCT FROM OLD.baseline_source_version + OR NEW.last_outbox_sequence <> OLD.last_outbox_sequence + 1 + OR NEW.current_generation <> OLD.current_generation + 1 + OR NEW.current_source_version <> OLD.current_source_version + 1 + OR NEW.current_generation <> NEW.baseline_generation + NEW.last_outbox_sequence + OR NEW.current_source_version <> NEW.baseline_source_version + NEW.last_outbox_sequence + OR NEW.last_request_id IS NULL OR NEW.last_request_digest !~ '^sha256:[0-9a-f]{64}$' + OR NEW.last_event_id IS NULL OR NEW.last_event_digest !~ '^sha256:[0-9a-f]{64}$' + OR NEW.tenant_billing_sequence IS NULL OR NEW.tenant_billing_sequence <= 0 + OR NEW.tenant_billing_event_id IS NULL + OR NEW.tenant_billing_event_digest !~ '^sha256:[0-9a-f]{64}$' THEN + RAISE EXCEPTION 'Tenant authority source must advance one exact immutable event' + USING ERRCODE = '23514', CONSTRAINT = 'account_tenant_authority_source_monotonic'; + END IF; + SELECT event_id, event_digest, payload INTO authority_event + FROM account_authority_outbox_events + WHERE outbox_stream_key = NEW.outbox_stream_key + AND outbox_sequence = NEW.last_outbox_sequence; + IF authority_event.event_id IS DISTINCT FROM NEW.last_event_id + OR authority_event.event_digest IS DISTINCT FROM NEW.last_event_digest THEN + RAISE EXCEPTION 'Tenant authority source head differs from its exact event' + USING ERRCODE = '23514', CONSTRAINT = 'account_tenant_authority_source_event_link'; + END IF; + payload := convert_from(authority_event.payload, 'UTF8')::JSONB; + IF payload->>'schemaVersion' IS DISTINCT FROM 'account-tenant-authority-event/v1' + OR payload->>'eventType' IS DISTINCT FROM 'TENANT_AUTHORITY_CHANGED' + OR payload->>'tenantId' IS DISTINCT FROM NEW.tenant_uuid::TEXT + OR payload->>'outboxStreamKey' IS DISTINCT FROM NEW.outbox_stream_key + OR payload->>'outboxSequence' IS DISTINCT FROM NEW.last_outbox_sequence::TEXT + OR payload->>'eventId' IS DISTINCT FROM NEW.last_event_id + OR payload->>'eventDigest' IS DISTINCT FROM NEW.last_event_digest + OR payload->>'requestId' IS DISTINCT FROM NEW.last_request_id::TEXT + OR payload->>'requestDigest' IS DISTINCT FROM NEW.last_request_digest + OR payload->>'tenantAuthorityGeneration' IS DISTINCT FROM NEW.current_generation::TEXT + OR payload->>'tenantAuthoritySourceVersion' IS DISTINCT FROM NEW.current_source_version::TEXT + OR payload#>>'{tenantBillingReceipt,outboxStreamKey}' + IS DISTINCT FROM ('account:tenant-entitlement:v1:tenant/' || NEW.tenant_uuid::TEXT) + OR payload#>>'{tenantBillingReceipt,tenantBillingSequence}' + IS DISTINCT FROM NEW.tenant_billing_sequence::TEXT + OR payload#>>'{tenantBillingReceipt,eventId}' IS DISTINCT FROM NEW.tenant_billing_event_id::TEXT + OR payload#>>'{tenantBillingReceipt,eventDigest}' IS DISTINCT FROM NEW.tenant_billing_event_digest THEN + RAISE EXCEPTION 'Tenant authority source event does not match its exact checkpoint' + USING ERRCODE = '23514', CONSTRAINT = 'account_tenant_authority_source_event_values'; + END IF; + SELECT schema_version, target_namespace, creation_request_id, operation_id, request_digest, + source_game_row_id, source_game_tenant_key, provenance_kind, evidence_digest + INTO fresh_row FROM account_fresh_tenant_identity_associations + WHERE canonical_tenant_id = NEW.tenant_uuid; + IF payload#>>'{sourceEvidence,schemaVersion}' IS DISTINCT FROM fresh_row.schema_version::TEXT + OR payload#>>'{sourceEvidence,targetNamespace}' IS DISTINCT FROM fresh_row.target_namespace + OR payload#>>'{sourceEvidence,creationRequestId}' IS DISTINCT FROM fresh_row.creation_request_id::TEXT + OR payload#>>'{sourceEvidence,operationId}' IS DISTINCT FROM fresh_row.operation_id::TEXT + OR payload#>>'{sourceEvidence,requestDigest}' IS DISTINCT FROM fresh_row.request_digest + OR payload#>>'{sourceEvidence,canonicalTenantId}' IS DISTINCT FROM NEW.tenant_uuid::TEXT + OR payload#>>'{sourceEvidence,sourceGameRowId}' IS DISTINCT FROM fresh_row.source_game_row_id::TEXT + OR payload#>>'{sourceEvidence,sourceGameTenantKey}' IS DISTINCT FROM fresh_row.source_game_tenant_key + OR payload#>>'{sourceEvidence,provenanceKind}' IS DISTINCT FROM fresh_row.provenance_kind + OR payload#>>'{sourceEvidence,evidenceDigest}' IS DISTINCT FROM fresh_row.evidence_digest THEN + RAISE EXCEPTION 'Tenant authority event differs from fresh Game Design source evidence' + USING ERRCODE = '23514', CONSTRAINT = 'account_tenant_authority_source_evidence'; + END IF; + SELECT event_id, event_digest, payload INTO billing_event + FROM account_tenant_entitlement_outbox_events + WHERE tenant_uuid = NEW.tenant_uuid + AND tenant_billing_sequence = NEW.tenant_billing_sequence; + IF billing_event.event_id IS DISTINCT FROM NEW.tenant_billing_event_id + OR billing_event.event_digest IS DISTINCT FROM NEW.tenant_billing_event_digest THEN + RAISE EXCEPTION 'Tenant authority event does not link to the exact tenant billing event' + USING ERRCODE = '23514', CONSTRAINT = 'account_tenant_authority_billing_link'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_tenant_authority_source_consistency() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + head RECORD; + generation_row RECORD; + stream_sequence BIGINT; + operation_row RECORD; + entitlement_row RECORD; +BEGIN + SELECT * INTO head FROM account_tenant_authority_source_records + WHERE outbox_stream_key = NEW.outbox_stream_key; + SELECT generation, source_version INTO generation_row FROM account_authority_generations + WHERE scope_kind = 'TENANT' AND tenant_uuid = NEW.tenant_uuid; + SELECT last_sequence INTO stream_sequence FROM account_authority_outbox_streams + WHERE outbox_stream_key = NEW.outbox_stream_key; + IF head.outbox_stream_key IS NULL OR head.last_outbox_sequence <= 0 + OR head.current_generation IS DISTINCT FROM generation_row.generation + OR head.current_source_version IS DISTINCT FROM generation_row.source_version + OR stream_sequence IS DISTINCT FROM head.last_outbox_sequence THEN + RAISE EXCEPTION 'Tenant authority source checkpoint is not the current Account generation' + USING ERRCODE = '23514', CONSTRAINT = 'account_tenant_authority_source_consistent'; + END IF; + SELECT request_id, tenant_uuid, request_digest, source_creation_request_id, + source_request_digest, source_operation_id, source_evidence_digest, status, + tenant_billing_sequence, event_id, event_digest, + tenant_authority_outbox_stream_key, tenant_authority_outbox_sequence, + tenant_authority_event_id, tenant_authority_event_digest + INTO operation_row FROM account_demo_tenant_entitlement_operations + WHERE request_id = head.last_request_id; + SELECT * INTO entitlement_row FROM account_demo_tenant_entitlements + WHERE tenant_uuid = NEW.tenant_uuid; + IF operation_row.status IS DISTINCT FROM 'COMMITTED' + OR operation_row.tenant_uuid IS DISTINCT FROM NEW.tenant_uuid + OR operation_row.request_digest IS DISTINCT FROM head.last_request_digest + OR operation_row.tenant_billing_sequence IS DISTINCT FROM head.tenant_billing_sequence + OR operation_row.event_id IS DISTINCT FROM head.tenant_billing_event_id + OR operation_row.event_digest IS DISTINCT FROM head.tenant_billing_event_digest + OR operation_row.tenant_authority_outbox_stream_key IS DISTINCT FROM head.outbox_stream_key + OR operation_row.tenant_authority_outbox_sequence IS DISTINCT FROM head.last_outbox_sequence + OR operation_row.tenant_authority_event_id IS DISTINCT FROM head.last_event_id + OR operation_row.tenant_authority_event_digest IS DISTINCT FROM head.last_event_digest + OR entitlement_row.tenant_uuid IS DISTINCT FROM NEW.tenant_uuid + OR entitlement_row.tenant_authority_generation IS DISTINCT FROM head.current_generation + OR entitlement_row.tenant_authority_source_version IS DISTINCT FROM head.current_source_version + OR entitlement_row.tenant_billing_sequence IS DISTINCT FROM head.tenant_billing_sequence + OR entitlement_row.event_id IS DISTINCT FROM head.tenant_billing_event_id + OR entitlement_row.event_digest IS DISTINCT FROM head.tenant_billing_event_digest + OR entitlement_row.tenant_authority_outbox_stream_key IS DISTINCT FROM head.outbox_stream_key + OR entitlement_row.tenant_authority_outbox_sequence IS DISTINCT FROM head.last_outbox_sequence + OR entitlement_row.tenant_authority_event_id IS DISTINCT FROM head.last_event_id + OR entitlement_row.tenant_authority_event_digest IS DISTINCT FROM head.last_event_digest THEN + RAISE EXCEPTION 'Tenant authority source lacks its exact current Account receipt and entitlement' + USING ERRCODE = '23514', CONSTRAINT = 'account_tenant_authority_source_receipt'; + END IF; + RETURN NULL; +END; +$$; + +CREATE FUNCTION account_tenant_authority_generation_consistency() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + source_row RECORD; +BEGIN + IF NEW.scope_kind = 'TENANT' THEN + SELECT current_generation, current_source_version INTO source_row + FROM account_tenant_authority_source_records WHERE tenant_uuid = NEW.tenant_uuid; + IF source_row.current_generation IS DISTINCT FROM NEW.generation + OR source_row.current_source_version IS DISTINCT FROM NEW.source_version THEN + RAISE EXCEPTION 'Tenant authority generation advance lacks its canonical source event' + USING ERRCODE = '23514', CONSTRAINT = 'account_tenant_authority_generation_source'; + END IF; + END IF; + RETURN NULL; +END; +$$; + +CREATE FUNCTION account_tenant_authority_stream_consistency() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + source_row RECORD; +BEGIN + IF left(NEW.outbox_stream_key, length('account:auth-authority:v1:tenant/')) + = 'account:auth-authority:v1:tenant/' THEN + SELECT last_outbox_sequence INTO source_row + FROM account_tenant_authority_source_records + WHERE outbox_stream_key = NEW.outbox_stream_key; + IF source_row.last_outbox_sequence IS DISTINCT FROM NEW.last_sequence + OR NEW.last_sequence <= 0 THEN + RAISE EXCEPTION 'Tenant authority outbox head lacks an Account-owned source checkpoint' + USING ERRCODE = '23514', CONSTRAINT = 'account_tenant_authority_stream_source'; + END IF; + END IF; + RETURN NULL; +END; +$$; + +CREATE FUNCTION account_demo_entitlement_authority_event_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + authority_event RECORD; + payload JSONB; + generation_row RECORD; +BEGIN + IF NEW.tenant_authority_outbox_stream_key IS NULL + OR NEW.tenant_authority_outbox_sequence IS NULL + OR NEW.tenant_authority_event_id IS NULL + OR NEW.tenant_authority_event_digest IS NULL THEN + RAISE EXCEPTION 'Demo entitlement requires a distinct canonical tenant authority event' + USING ERRCODE = '23514', CONSTRAINT = 'account_demo_entitlement_authority_required'; + END IF; + IF NEW.tenant_authority_outbox_stream_key + IS DISTINCT FROM ('account:auth-authority:v1:tenant/' || NEW.tenant_uuid::TEXT) THEN + RAISE EXCEPTION 'Demo entitlement tenant authority event has the wrong scope' + USING ERRCODE = '23514', CONSTRAINT = 'account_demo_entitlement_authority_scope'; + END IF; + SELECT event_id, event_digest, payload INTO authority_event + FROM account_authority_outbox_events + WHERE outbox_stream_key = NEW.tenant_authority_outbox_stream_key + AND outbox_sequence = NEW.tenant_authority_outbox_sequence; + IF authority_event.event_id IS DISTINCT FROM NEW.tenant_authority_event_id + OR authority_event.event_digest IS DISTINCT FROM NEW.tenant_authority_event_digest THEN + RAISE EXCEPTION 'Demo entitlement authority receipt differs from its exact source event' + USING ERRCODE = '23514', CONSTRAINT = 'account_demo_entitlement_authority_event_link'; + END IF; + payload := convert_from(authority_event.payload, 'UTF8')::JSONB; + SELECT generation, source_version INTO generation_row FROM account_authority_generations + WHERE scope_kind = 'TENANT' AND tenant_uuid = NEW.tenant_uuid; + IF payload->>'schemaVersion' IS DISTINCT FROM 'account-tenant-authority-event/v1' + OR payload->>'eventType' IS DISTINCT FROM 'TENANT_AUTHORITY_CHANGED' + OR payload->>'tenantId' IS DISTINCT FROM NEW.tenant_uuid::TEXT + OR payload->>'tenantAuthorityGeneration' IS DISTINCT FROM NEW.tenant_authority_generation::TEXT + OR payload->>'tenantAuthoritySourceVersion' IS DISTINCT FROM NEW.tenant_authority_source_version::TEXT + OR payload->>'outboxStreamKey' IS DISTINCT FROM NEW.tenant_authority_outbox_stream_key + OR payload->>'outboxSequence' IS DISTINCT FROM NEW.tenant_authority_outbox_sequence::TEXT + OR payload->>'eventId' IS DISTINCT FROM NEW.tenant_authority_event_id + OR payload->>'eventDigest' IS DISTINCT FROM NEW.tenant_authority_event_digest + OR payload->>'requestId' IS DISTINCT FROM NEW.last_request_id::TEXT + OR payload->>'requestDigest' IS DISTINCT FROM NEW.last_request_digest + OR payload#>>'{tenantBillingReceipt,outboxStreamKey}' + IS DISTINCT FROM ('account:tenant-entitlement:v1:tenant/' || NEW.tenant_uuid::TEXT) + OR payload#>>'{tenantBillingReceipt,tenantBillingSequence}' + IS DISTINCT FROM NEW.tenant_billing_sequence::TEXT + OR payload#>>'{tenantBillingReceipt,eventId}' IS DISTINCT FROM NEW.event_id::TEXT + OR payload#>>'{tenantBillingReceipt,eventDigest}' IS DISTINCT FROM NEW.event_digest + OR generation_row.generation IS DISTINCT FROM NEW.tenant_authority_generation + OR generation_row.source_version IS DISTINCT FROM NEW.tenant_authority_source_version THEN + RAISE EXCEPTION 'Demo entitlement differs from its actual tenant authority source event' + USING ERRCODE = '23514', CONSTRAINT = 'account_demo_entitlement_authority_values'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_demo_entitlement_authority_receipt_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + authority_event RECORD; + payload JSONB; +BEGIN + IF NEW.status = 'COMMITTED' THEN + IF NEW.tenant_authority_outbox_stream_key + IS DISTINCT FROM ('account:auth-authority:v1:tenant/' || NEW.tenant_uuid::TEXT) + OR NEW.tenant_authority_outbox_sequence IS NULL + OR NEW.tenant_authority_event_id IS NULL + OR NEW.tenant_authority_event_digest IS NULL THEN + RAISE EXCEPTION 'Committed demo receipt requires its exact tenant authority checkpoint' + USING ERRCODE = '23514', CONSTRAINT = 'account_demo_entitlement_authority_receipt_required'; + END IF; + SELECT event_id, event_digest, payload INTO authority_event + FROM account_authority_outbox_events + WHERE outbox_stream_key = NEW.tenant_authority_outbox_stream_key + AND outbox_sequence = NEW.tenant_authority_outbox_sequence; + IF authority_event.event_id IS DISTINCT FROM NEW.tenant_authority_event_id + OR authority_event.event_digest IS DISTINCT FROM NEW.tenant_authority_event_digest THEN + RAISE EXCEPTION 'Committed demo receipt authority event differs from Account outbox' + USING ERRCODE = '23514', CONSTRAINT = 'account_demo_entitlement_authority_receipt_event'; + END IF; + payload := convert_from(authority_event.payload, 'UTF8')::JSONB; + IF payload->>'requestId' IS DISTINCT FROM NEW.request_id::TEXT + OR payload->>'requestDigest' IS DISTINCT FROM NEW.request_digest + OR payload->>'tenantId' IS DISTINCT FROM NEW.tenant_uuid::TEXT + OR payload->>'tenantAuthorityGeneration' + IS DISTINCT FROM NEW.tenant_authority_generation::TEXT + OR payload->>'tenantAuthoritySourceVersion' + IS DISTINCT FROM NEW.tenant_authority_source_version::TEXT + OR payload#>>'{tenantBillingReceipt,tenantBillingSequence}' + IS DISTINCT FROM NEW.tenant_billing_sequence::TEXT + OR payload#>>'{tenantBillingReceipt,eventId}' IS DISTINCT FROM NEW.event_id::TEXT + OR payload#>>'{tenantBillingReceipt,eventDigest}' IS DISTINCT FROM NEW.event_digest THEN + RAISE EXCEPTION 'Committed demo receipt differs from its canonical authority event' + USING ERRCODE = '23514', CONSTRAINT = 'account_demo_entitlement_authority_receipt_values'; + END IF; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER account_tenant_authority_source_insert + BEFORE INSERT ON account_tenant_authority_source_records + FOR EACH ROW EXECUTE FUNCTION account_tenant_authority_source_insert_guard(); +CREATE TRIGGER account_tenant_authority_source_update + BEFORE UPDATE OR DELETE ON account_tenant_authority_source_records + FOR EACH ROW EXECUTE FUNCTION account_tenant_authority_source_update_guard(); +CREATE TRIGGER account_tenant_authority_source_no_truncate + BEFORE TRUNCATE ON account_tenant_authority_source_records + FOR EACH STATEMENT EXECUTE FUNCTION account_demo_entitlement_reject_truncate(); +CREATE CONSTRAINT TRIGGER account_tenant_authority_source_consistency + AFTER INSERT OR UPDATE ON account_tenant_authority_source_records + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW + EXECUTE FUNCTION account_tenant_authority_source_consistency(); +CREATE CONSTRAINT TRIGGER account_tenant_authority_generation_consistency + AFTER UPDATE ON account_authority_generations + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW + EXECUTE FUNCTION account_tenant_authority_generation_consistency(); +CREATE CONSTRAINT TRIGGER account_tenant_authority_stream_consistency + AFTER INSERT OR UPDATE ON account_authority_outbox_streams + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW + EXECUTE FUNCTION account_tenant_authority_stream_consistency(); +CREATE TRIGGER account_demo_entitlement_authority_event + BEFORE INSERT OR UPDATE ON account_demo_tenant_entitlements + FOR EACH ROW EXECUTE FUNCTION account_demo_entitlement_authority_event_guard(); +CREATE TRIGGER account_demo_entitlement_authority_receipt + BEFORE INSERT OR UPDATE ON account_demo_tenant_entitlement_operations + FOR EACH ROW EXECUTE FUNCTION account_demo_entitlement_authority_receipt_guard(); +-- [jooq ignore end] diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementPersistenceIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementPersistenceIntegrationTest.java new file mode 100644 index 0000000000..a8a60b82dc --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementPersistenceIntegrationTest.java @@ -0,0 +1,551 @@ +package integration.net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementRequest; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementSnapshot; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountDemoTenantEntitlementRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantAuthorityEventRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantEntitlementOutboxRepository; +import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository; +import net.firedevops.firemud.accountservice.service.DemoTenantEntitlementException; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.support.TransactionTemplate; + +/** Physical PostgreSQL proof for exact-source demo entitlement commit and revalidation fencing. */ +class AccountDemoTenantEntitlementPersistenceIntegrationTest { + private static final String TEST_NAMESPACE = "account-service"; + private static AccountPostgresIntegrationFixture postgresFixture; + private static DriverManagerDataSource rootDataSource; + private final Set runOwnedSchemas = new java.util.LinkedHashSet<>(); + + @BeforeAll + static void setUpPostgresFixture() { + postgresFixture = new AccountPostgresIntegrationFixture(); + postgresFixture.start(); + rootDataSource = postgresFixture.dataSource(); + } + + @AfterEach + void dropOnlyRunOwnedSchemas() { + JdbcTemplate rootJdbc = new JdbcTemplate(rootDataSource); + for (String schema : runOwnedSchemas) { + rootJdbc.execute("DROP SCHEMA IF EXISTS \"" + schema + "\" CASCADE"); + } + runOwnedSchemas.clear(); + } + + @AfterAll + static void stopPostgresFixture() { + if (postgresFixture != null) { + postgresFixture.stop(); + } + } + + @Test + void exactFreshUuidReplayConflictQuotasAndGenerationChangeAreTransactionallyFenced() { + TestContext context = newTestContext(); + FreshTenantIdentityAssociationRepository identityRepository = + new FreshTenantIdentityAssociationRepository(context.dsl(), TEST_NAMESPACE); + AccountAuthorityGenerationRepository generationRepository = + new AccountAuthorityGenerationRepository(context.dsl()); + AccountTenantEntitlementOutboxRepository outboxRepository = + new AccountTenantEntitlementOutboxRepository(context.dsl()); + AccountAuthorityOutboxRepository authorityOutbox = + new AccountAuthorityOutboxRepository(context.dsl()); + AccountTenantAuthorityEventRepository tenantAuthorityEvents = + new AccountTenantAuthorityEventRepository( + context.dsl(), + authorityOutbox, + outboxRepository, + identityRepository, + generationRepository); + AccountDemoTenantEntitlementRepository entitlements = + new AccountDemoTenantEntitlementRepository( + context.dsl(), + identityRepository, + generationRepository, + outboxRepository, + tenantAuthorityEvents); + + UUID tenantId = UUID.fromString("44444444-4444-4444-8444-444444444444"); + FreshTenantCreationEvidence source = evidence(tenantId, 801L); + inTransaction( + context.transaction(), + () -> { + identityRepository.importVerified(source); + generationRepository.initializeTenantIfAbsent(tenantId); + return null; + }); + + DemoTenantEntitlementRequest create = + request( + UUID.fromString("11111111-1111-4111-8111-111111111111"), + tenantId, + source, + null, + null, + null, + true); + DemoTenantEntitlementSnapshot first = + inTransaction(context.transaction(), () -> entitlements.provision(create, source)); + assertThat(first.canonicalTenantId()).isEqualTo(tenantId); + assertThat(first.sourceEvidence()).isEqualTo(source); + assertThat(first.entitlementKind()).isEqualTo("NON_PAID_DEMO"); + assertThat(first.status()).isEqualTo("ACTIVE"); + assertThat(first.subscriptionStatus()).isNull(); + assertThat(first.paid()).isFalse(); + assertThat(first.gameplayAvailable()).isTrue(); + assertThat(first.allowPublicJoin()).isFalse(); + assertThat(first.allowNewGameplayBindings()).isFalse(); + assertThat(first.allowNewInstanceStarts()).isTrue(); + assertThat(first.quotas()).isEqualTo(new DemoTenantEntitlementRequest.Quotas(3L, 2L, 4096L)); + assertThat(first.entitlementVersion()).isEqualTo(1L); + assertThat(first.tenantAuthorityGeneration()).isEqualTo(2L); + assertThat(first.tenantAuthoritySourceVersion()).isEqualTo(2L); + assertThat(first.tenantBillingSequence()).isEqualTo(1L); + assertThat(first.outboxStreamKey()) + .isEqualTo(AccountTenantEntitlementOutboxRepository.streamKey(tenantId)); + assertThat(first.tenantAuthorityOutboxStreamKey()) + .isEqualTo("account:auth-authority:v1:tenant/" + tenantId); + assertThat(first.tenantAuthorityOutboxSequence()).isEqualTo(1L); + assertThat(first.tenantAuthorityEventId()).isNotNull(); + assertThat(first.tenantAuthorityEventDigest()).matches("sha256:[0-9a-f]{64}"); + assertThat(first.tenantAuthorityEventId()).isNotEqualTo(first.eventId()); + + assertThat(inTransaction(context.transaction(), () -> entitlements.provision(create, source))) + .isEqualTo(first); + DemoTenantEntitlementSnapshot exactReadback = + inTransaction(context.transaction(), () -> entitlements.readCurrent(tenantId)); + assertThat(exactReadback).isEqualTo(first); + var authorityReadback = + inTransaction( + context.transaction(), () -> tenantAuthorityEvents.readCurrentByTenant(tenantId)); + assertThat(authorityReadback.eventId()).isEqualTo(first.tenantAuthorityEventId()); + assertThat(authorityReadback.eventDigest()).isEqualTo(first.tenantAuthorityEventDigest()); + assertThat(authorityReadback.outboxSequence()).isEqualTo(first.tenantAuthorityOutboxSequence()); + + DemoTenantEntitlementRequest conflictingReplay = + request(create.requestId(), tenantId, source, null, null, null, false); + assertThatThrownBy( + () -> + inTransaction( + context.transaction(), () -> entitlements.provision(conflictingReplay, source))) + .isInstanceOf(DemoTenantEntitlementException.class) + .hasMessageContaining("reused for a different tenant or payload"); + + FreshTenantCreationEvidence alteredProvenance = alteredProvenance(source); + assertThatThrownBy( + () -> + inTransaction( + context.transaction(), () -> entitlements.provision(create, alteredProvenance))) + .isInstanceOf(DemoTenantEntitlementException.class) + .hasMessageContaining("differs from exact Account UUID readback"); + + UUID otherTenantId = UUID.fromString("55555555-5555-4555-8555-555555555555"); + FreshTenantCreationEvidence otherSource = evidence(otherTenantId, 802L); + inTransaction( + context.transaction(), + () -> { + identityRepository.importVerified(otherSource); + generationRepository.initializeTenantIfAbsent(otherTenantId); + return null; + }); + DemoTenantEntitlementRequest crossTenantReplay = + request(create.requestId(), otherTenantId, otherSource, null, null, null, true); + assertThatThrownBy( + () -> + inTransaction( + context.transaction(), + () -> entitlements.provision(crossTenantReplay, otherSource))) + .isInstanceOf(DemoTenantEntitlementException.class) + .hasMessageContaining("reused for a different tenant or payload"); + + DemoTenantEntitlementRequest wrongSourceTenant = + request( + UUID.fromString("77777777-7777-4777-8777-777777777777"), + otherTenantId, + source, + null, + null, + null, + true); + assertThatThrownBy( + () -> + inTransaction( + context.transaction(), () -> entitlements.provision(wrongSourceTenant, source))) + .isInstanceOf(DemoTenantEntitlementException.class) + .hasMessageContaining( + "Only exact authenticated fresh Game Design tenant creation evidence"); + + DemoTenantEntitlementRequest update = + request( + UUID.fromString("88888888-8888-4888-8888-888888888888"), + tenantId, + source, + first.entitlementVersion(), + first.tenantAuthorityGeneration(), + first.tenantAuthoritySourceVersion(), + false); + DemoTenantEntitlementSnapshot updated = + inTransaction(context.transaction(), () -> entitlements.provision(update, source)); + assertThat(updated.entitlementVersion()).isEqualTo(2L); + assertThat(updated.tenantAuthorityGeneration()).isEqualTo(3L); + assertThat(updated.tenantAuthoritySourceVersion()).isEqualTo(3L); + assertThat(updated.tenantBillingSequence()).isEqualTo(2L); + assertThat(updated.tenantAuthorityOutboxSequence()).isEqualTo(2L); + assertThat(inTransaction(context.transaction(), () -> entitlements.provision(update, source))) + .isEqualTo(updated); + assertThatThrownBy( + () -> inTransaction(context.transaction(), () -> entitlements.revalidate(first))) + .isInstanceOf(DemoTenantEntitlementException.class) + .hasMessageContaining("changed after its complete evaluation snapshot"); + + Long legacyIdentityColumnCount = + context + .dsl() + .fetchOne( + "SELECT COUNT(*) FROM information_schema.columns WHERE table_schema = ? " + + "AND table_name = 'account_demo_tenant_entitlements' " + + "AND column_name IN ('tenant_id', 'legacy_tenant_id')", + context.schema()) + .get(0, Long.class); + assertThat(legacyIdentityColumnCount).isZero(); + Long outboxEventCount = + context + .dsl() + .fetchOne( + "SELECT COUNT(*) FROM account_tenant_entitlement_outbox_events WHERE tenant_uuid = ?", + tenantId) + .get(0, Long.class); + assertThat(outboxEventCount).isEqualTo(2L); + Long authorityEventCount = + context + .dsl() + .fetchOne( + "SELECT COUNT(*) FROM account_authority_outbox_events " + + "WHERE outbox_stream_key = ?", + "account:auth-authority:v1:tenant/" + tenantId) + .get(0, Long.class); + assertThat(authorityEventCount).isEqualTo(2L); + Long operationCount = + context + .dsl() + .fetchOne( + "SELECT COUNT(*) FROM account_demo_tenant_entitlement_operations WHERE tenant_uuid = ?", + tenantId) + .get(0, Long.class); + assertThat(operationCount).isEqualTo(2L); + + assertThatThrownBy( + () -> + inTransaction( + context.transaction(), + () -> { + context + .dsl() + .execute( + "UPDATE account_authority_generations SET generation = generation + 1, " + + "source_version = source_version + 1 WHERE scope_kind = 'TENANT' " + + "AND tenant_uuid = ?", + tenantId); + return null; + })) + .isInstanceOf(RuntimeException.class); + assertThat(inTransaction(context.transaction(), () -> entitlements.readCurrent(tenantId))) + .isEqualTo(updated); + inTransaction( + context.transaction(), + () -> { + context + .dsl() + .execute( + "UPDATE account_demo_tenant_entitlements SET gameplay_available = NOT gameplay_available " + + "WHERE tenant_uuid = ?", + tenantId); + return null; + }); + assertThatThrownBy( + () -> + inTransaction( + context.transaction(), + () -> tenantAuthorityEvents.readCurrentByTenant(tenantId))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("differs from its exact committed billing event"); + } + + @Test + void failedOwnerTransactionAndUnmappedGenerationCannotCreateSyntheticAuthorityHistory() { + TestContext context = newTestContext(); + FreshTenantIdentityAssociationRepository identityRepository = + new FreshTenantIdentityAssociationRepository(context.dsl(), TEST_NAMESPACE); + AccountAuthorityGenerationRepository generationRepository = + new AccountAuthorityGenerationRepository(context.dsl()); + AccountTenantEntitlementOutboxRepository outboxRepository = + new AccountTenantEntitlementOutboxRepository(context.dsl()); + AccountTenantAuthorityEventRepository tenantAuthorityEvents = + new AccountTenantAuthorityEventRepository( + context.dsl(), + new AccountAuthorityOutboxRepository(context.dsl()), + outboxRepository, + identityRepository, + generationRepository); + AccountDemoTenantEntitlementRepository entitlements = + new AccountDemoTenantEntitlementRepository( + context.dsl(), + identityRepository, + generationRepository, + outboxRepository, + tenantAuthorityEvents); + + UUID rollbackTenant = UUID.fromString("66666666-6666-4666-8666-666666666666"); + FreshTenantCreationEvidence rollbackSource = evidence(rollbackTenant, 803L); + inTransaction( + context.transaction(), + () -> { + identityRepository.importVerified(rollbackSource); + generationRepository.initializeTenantIfAbsent(rollbackTenant); + return null; + }); + DemoTenantEntitlementRequest rollbackRequest = + request( + UUID.fromString("66666666-6666-4666-8666-666666666667"), + rollbackTenant, + rollbackSource, + null, + null, + null, + true); + assertThatThrownBy( + () -> + inTransaction( + context.transaction(), + () -> { + entitlements.provision(rollbackRequest, rollbackSource); + throw new IllegalStateException("force owner transaction rollback"); + })) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("force owner transaction rollback"); + assertTenantHasOnlyGenerationOne(context, rollbackTenant); + assertThat( + context + .dsl() + .fetchOne( + "SELECT COUNT(*) FROM account_authority_outbox_events " + + "WHERE outbox_stream_key = ?", + "account:auth-authority:v1:tenant/" + rollbackTenant) + .get(0, Long.class)) + .isZero(); + assertThat( + context + .dsl() + .fetchOne( + "SELECT COUNT(*) FROM account_tenant_entitlement_outbox_events WHERE tenant_uuid = ?", + rollbackTenant) + .get(0, Long.class)) + .isZero(); + + UUID retainedTenant = UUID.fromString("77777777-7777-4777-8777-777777777777"); + FreshTenantCreationEvidence retainedSource = evidence(retainedTenant, 804L); + inTransaction( + context.transaction(), + () -> { + identityRepository.importVerified(retainedSource); + return null; + }); + inTransaction( + context.transaction(), + () -> { + context + .dsl() + .execute( + "INSERT INTO account_authority_generations " + + "(scope_kind, issuer_id, account_uuid, tenant_uuid, generation, source_version) " + + "VALUES ('TENANT', NULL, NULL, ?, 2, 2)", + retainedTenant); + return null; + }); + DemoTenantEntitlementRequest retainedRequest = + request( + UUID.fromString("77777777-7777-4777-8777-777777777778"), + retainedTenant, + retainedSource, + null, + null, + null, + true); + assertThatThrownBy( + () -> + inTransaction( + context.transaction(), + () -> entitlements.provision(retainedRequest, retainedSource))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("advanced without canonical source-event evidence"); + assertThat( + context + .dsl() + .fetchOne( + "SELECT generation FROM account_authority_generations " + + "WHERE scope_kind = 'TENANT' AND tenant_uuid = ?", + retainedTenant) + .get(0, Long.class)) + .isEqualTo(2L); + assertThat( + context + .dsl() + .fetchOne( + "SELECT COUNT(*) FROM account_fresh_tenant_identity_associations " + + "WHERE canonical_tenant_id = ?", + retainedTenant) + .get(0, Long.class)) + .isEqualTo(1L); + } + + private static void assertTenantHasOnlyGenerationOne(TestContext context, UUID tenantId) { + assertThat( + context + .dsl() + .fetchOne( + "SELECT generation FROM account_authority_generations " + + "WHERE scope_kind = 'TENANT' AND tenant_uuid = ?", + tenantId) + .get(0, Long.class)) + .isEqualTo(1L); + assertThat( + context + .dsl() + .fetchOne( + "SELECT COUNT(*) FROM account_demo_tenant_entitlement_operations " + + "WHERE tenant_uuid = ?", + tenantId) + .get(0, Long.class)) + .isZero(); + } + + private TestContext newTestContext() { + String schema = "demo_entitlement_" + UUID.randomUUID().toString().replace("-", ""); + runOwnedSchemas.add(schema); + org.jooq + .impl + .DSL + .using(rootDataSource, SQLDialect.POSTGRES) + .execute("CREATE SCHEMA \"" + schema + "\""); + DriverManagerDataSource dataSource = postgresFixture.dataSource(schema); + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .load() + .migrate(); + DSLContext dsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + return new TestContext( + dsl, new TransactionTemplate(new DataSourceTransactionManager(dataSource)), schema); + } + + private static DemoTenantEntitlementRequest request( + UUID requestId, + UUID tenantId, + FreshTenantCreationEvidence source, + Long entitlementVersion, + Long authorityGeneration, + Long authoritySourceVersion, + boolean gameplayAvailable) { + return new DemoTenantEntitlementRequest( + requestId, + tenantId, + source.creationRequestId(), + source.requestDigest(), + entitlementVersion, + authorityGeneration, + authoritySourceVersion, + gameplayAvailable, + false, + false, + true, + new DemoTenantEntitlementRequest.Quotas(3L, 2L, 4096L)); + } + + private static FreshTenantCreationEvidence evidence(UUID tenantId, long sourceRowId) { + UUID requestId = UUID.randomUUID(); + UUID operationId = UUID.randomUUID(); + String digest = "sha256:" + Long.toHexString(sourceRowId % 16L).repeat(64); + String sourceKey = "demo-source-" + sourceRowId; + String evidenceDigest = + GameTenantCreationDigest.evidenceDigest( + TEST_NAMESPACE, + requestId, + operationId, + digest, + tenantId, + sourceRowId, + sourceKey, + "NEW_GAME_ROW"); + return new FreshTenantCreationEvidence( + 1, + TEST_NAMESPACE, + requestId, + operationId, + digest, + tenantId, + sourceRowId, + sourceKey, + "NEW_GAME_ROW", + evidenceDigest); + } + + private static FreshTenantCreationEvidence alteredProvenance(FreshTenantCreationEvidence source) { + long sourceRowId = source.sourceGameRowId() + 1000L; + UUID operationId = UUID.randomUUID(); + String sourceKey = "different-source-" + sourceRowId; + String evidenceDigest = + GameTenantCreationDigest.evidenceDigest( + source.targetNamespace(), + source.creationRequestId(), + operationId, + source.requestDigest(), + source.canonicalTenantId(), + sourceRowId, + sourceKey, + source.provenanceKind()); + return new FreshTenantCreationEvidence( + source.schemaVersion(), + source.targetNamespace(), + source.creationRequestId(), + operationId, + source.requestDigest(), + source.canonicalTenantId(), + sourceRowId, + sourceKey, + source.provenanceKind(), + evidenceDigest); + } + + private static T inTransaction( + TransactionTemplate transaction, java.util.function.Supplier action) { + return transaction.execute(status -> action.get()); + } + + private record TestContext(DSLContext dsl, TransactionTemplate transaction, String schema) {} +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/DemoTenantEntitlementCodecTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/DemoTenantEntitlementCodecTest.java new file mode 100644 index 0000000000..2135a89085 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/DemoTenantEntitlementCodecTest.java @@ -0,0 +1,207 @@ +package unit.net.firedevops.firemud.accountservice.dto; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementEventV1Codec; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementRequest; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; +import org.junit.jupiter.api.Test; +import tools.jackson.core.type.TypeReference; +import tools.jackson.databind.json.JsonMapper; + +class DemoTenantEntitlementCodecTest { + private static final UUID REQUEST_ID = UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID TENANT_ID = UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final UUID CREATION_ID = UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final UUID OPERATION_ID = UUID.fromString("44444444-4444-4444-8444-444444444444"); + private static final String CREATION_DIGEST = "sha256:" + "a".repeat(64); + private static final long TWO_TO_53 = 9_007_199_254_740_992L; + private static final long TWO_TO_53_PLUS_ONE = 9_007_199_254_740_993L; + private static final JsonMapper JSON = JsonMapper.builder().build(); + + @Test + void requestDigestDistinguishesAdjacentValuesAboveIeeeIntegerPrecision() { + String exactRequestValue = request(TWO_TO_53_PLUS_ONE, TWO_TO_53).requestDigest(); + String roundedRequestValue = request(TWO_TO_53, TWO_TO_53).requestDigest(); + String exactQuotaValue = request(TWO_TO_53, TWO_TO_53_PLUS_ONE).requestDigest(); + String roundedQuotaValue = request(TWO_TO_53, TWO_TO_53).requestDigest(); + + assertThat(exactRequestValue).isNotEqualTo(roundedRequestValue); + assertThat(exactQuotaValue).isNotEqualTo(roundedQuotaValue); + } + + @Test + void eventRoundTripPreservesLongMaxAndValuesAboveIeeeIntegerPrecisionAsDecimalStrings() { + DemoTenantEntitlementRequest request = + request( + Long.MAX_VALUE, + TWO_TO_53_PLUS_ONE, + new DemoTenantEntitlementRequest.Quotas( + Long.MAX_VALUE, TWO_TO_53_PLUS_ONE, Long.MAX_VALUE)); + FreshTenantCreationEvidence source = source(TWO_TO_53_PLUS_ONE); + DemoTenantEntitlementEventV1Codec.Event sealed = + DemoTenantEntitlementEventV1Codec.seal( + request, + source, + Long.MAX_VALUE, + TWO_TO_53_PLUS_ONE, + Long.MAX_VALUE, + TWO_TO_53_PLUS_ONE); + + DemoTenantEntitlementEventV1Codec.Event verified = + DemoTenantEntitlementEventV1Codec.verify(sealed.payload()); + String payload = new String(sealed.payload(), StandardCharsets.UTF_8); + + assertThat(verified.entitlementVersion()).isEqualTo(Long.MAX_VALUE); + assertThat(verified.tenantAuthorityGeneration()).isEqualTo(TWO_TO_53_PLUS_ONE); + assertThat(verified.tenantAuthoritySourceVersion()).isEqualTo(Long.MAX_VALUE); + assertThat(verified.tenantBillingSequence()).isEqualTo(TWO_TO_53_PLUS_ONE); + assertThat(verified.sourceEvidence().sourceGameRowId()).isEqualTo(TWO_TO_53_PLUS_ONE); + assertThat(verified.quotas()) + .isEqualTo( + new DemoTenantEntitlementRequest.Quotas( + Long.MAX_VALUE, TWO_TO_53_PLUS_ONE, Long.MAX_VALUE)); + assertThat(payload) + .contains("\"entitlementVersion\":\"9223372036854775807\"") + .contains("\"tenantAuthorityGeneration\":\"9007199254740993\"") + .contains("\"tenantBillingSequence\":\"9007199254740993\"") + .contains("\"sourceGameRowId\":\"9007199254740993\"") + .contains("\"maxConcurrentGameInstances\":\"9007199254740993\"") + .contains("\"schemaVersion\":1"); + } + + @Test + void eventVerifierRejectsNoncanonicalLongRepresentations() throws Exception { + byte[] validPayload = event().payload(); + + assertInvalidCounter(validPayload, 1); + assertInvalidCounter(validPayload, "01"); + assertInvalidCounter(validPayload, "1e2"); + assertInvalidCounter(validPayload, "1.0"); + assertInvalidCounter(validPayload, "9223372036854775808"); + assertInvalidQuota(validPayload, "01"); + assertInvalidQuota(validPayload, "-1"); + } + + @Test + void eventVerifierRejectsDuplicateKeysAndTrailingInput() throws Exception { + byte[] validPayload = event().payload(); + String canonical = new String(validPayload, StandardCharsets.UTF_8); + String duplicateKey = + canonical.replace( + "\"eventType\":\"TENANT_ENTITLEMENT_CHANGED\"", + "\"eventType\":\"TENANT_ENTITLEMENT_CHANGED\",\"eventType\":\"TENANT_ENTITLEMENT_CHANGED\""); + + assertThatThrownBy( + () -> + DemoTenantEntitlementEventV1Codec.verify( + duplicateKey.getBytes(StandardCharsets.UTF_8))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + DemoTenantEntitlementEventV1Codec.verify( + (canonical + " {}").getBytes(StandardCharsets.UTF_8))) + .isInstanceOf(IllegalArgumentException.class); + } + + private static void assertInvalidCounter(byte[] validPayload, Object invalidValue) + throws Exception { + Map wire = readWire(validPayload); + wire.put("tenantBillingSequence", invalidValue); + assertThatThrownBy(() -> DemoTenantEntitlementEventV1Codec.verify(resign(wire))) + .isInstanceOf(IllegalArgumentException.class); + } + + private static void assertInvalidQuota(byte[] validPayload, Object invalidValue) + throws Exception { + Map wire = readWire(validPayload); + nestedObject(wire, "quotas").put("maxStorageBytes", invalidValue); + assertThatThrownBy(() -> DemoTenantEntitlementEventV1Codec.verify(resign(wire))) + .isInstanceOf(IllegalArgumentException.class); + } + + private static DemoTenantEntitlementEventV1Codec.Event event() { + return DemoTenantEntitlementEventV1Codec.seal(request(1L, 1L), source(91L), 1L, 1L, 1L, 1L); + } + + private static DemoTenantEntitlementRequest request(long expectedVersion, long quotaValue) { + return request( + expectedVersion, + expectedVersion, + new DemoTenantEntitlementRequest.Quotas(quotaValue, quotaValue, quotaValue)); + } + + private static DemoTenantEntitlementRequest request( + long expectedVersion, + long expectedSourceVersion, + DemoTenantEntitlementRequest.Quotas quotas) { + return new DemoTenantEntitlementRequest( + REQUEST_ID, + TENANT_ID, + CREATION_ID, + CREATION_DIGEST, + expectedVersion, + expectedVersion, + expectedSourceVersion, + true, + false, + true, + true, + quotas); + } + + private static FreshTenantCreationEvidence source(long sourceGameRowId) { + String tenantKey = "demo-tenant-source-key"; + return new FreshTenantCreationEvidence( + 1, + "account-service", + CREATION_ID, + OPERATION_ID, + CREATION_DIGEST, + TENANT_ID, + sourceGameRowId, + tenantKey, + "NEW_GAME_ROW", + GameTenantCreationDigest.evidenceDigest( + "account-service", + CREATION_ID, + OPERATION_ID, + CREATION_DIGEST, + TENANT_ID, + sourceGameRowId, + tenantKey, + "NEW_GAME_ROW")); + } + + private static Map readWire(byte[] payload) throws IOException { + return JSON.readValue(payload, new TypeReference<>() {}); + } + + @SuppressWarnings("unchecked") + private static Map nestedObject(Map wire, String field) { + return (Map) wire.get(field); + } + + private static byte[] resign(Map wire) throws Exception { + Map preimage = new LinkedHashMap<>(wire); + preimage.remove("eventDigest"); + byte[] canonicalPreimage = + Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(preimage)); + String digest = + "sha256:" + + HexFormat.of() + .formatHex(MessageDigest.getInstance("SHA-256").digest(canonicalPreimage)); + preimage.put("eventDigest", digest); + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(preimage)); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/TenantAuthorityEventV1CodecTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/TenantAuthorityEventV1CodecTest.java new file mode 100644 index 0000000000..e783f4c871 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/TenantAuthorityEventV1CodecTest.java @@ -0,0 +1,88 @@ +package unit.net.firedevops.firemud.accountservice.dto; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementEventV1Codec; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementRequest; +import net.firedevops.firemud.accountservice.dto.TenantAuthorityEventV1Codec; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; +import org.junit.jupiter.api.Test; + +class TenantAuthorityEventV1CodecTest { + @Test + void authorityEventKeepsItsCanonicalCheckpointSeparateFromBillingReceipt() { + UUID tenantId = UUID.fromString("44444444-4444-4444-8444-444444444444"); + FreshTenantCreationEvidence source = source(tenantId); + DemoTenantEntitlementRequest request = + new DemoTenantEntitlementRequest( + UUID.fromString("11111111-1111-4111-8111-111111111111"), + tenantId, + source.creationRequestId(), + source.requestDigest(), + null, + null, + null, + true, + false, + false, + true, + new DemoTenantEntitlementRequest.Quotas(3L, 2L, 4096L)); + DemoTenantEntitlementEventV1Codec.Event billingEvent = + DemoTenantEntitlementEventV1Codec.seal(request, source, 1L, 2L, 2L, 1L); + TenantAuthorityEventV1Codec.Event authorityEvent = + TenantAuthorityEventV1Codec.seal(request, source, 2L, 2L, 1L, billingEvent); + + TenantAuthorityEventV1Codec.Event verified = + TenantAuthorityEventV1Codec.verify(authorityEvent.payload()); + assertThat(verified.outboxStreamKey()) + .isEqualTo("account:auth-authority:v1:tenant/" + tenantId); + assertThat(verified.outboxSequence()).isEqualTo(1L); + assertThat(verified.tenantBillingStreamKey()) + .isEqualTo("account:tenant-entitlement:v1:tenant/" + tenantId); + assertThat(verified.tenantBillingSequence()).isEqualTo(1L); + assertThat(verified.eventId()) + .isEqualTo(TenantAuthorityEventV1Codec.eventId(request.requestId())); + assertThat(verified.tenantBillingEventId()).isEqualTo(billingEvent.eventId()); + assertThat(verified.tenantBillingEventDigest()).isEqualTo(billingEvent.eventDigest()); + assertThat(verified.sourceEvidence()).isEqualTo(source); + assertThat(new String(verified.payload(), StandardCharsets.UTF_8)) + .contains("\"tenantAuthorityGeneration\":\"2\"") + .contains("\"tenantBillingSequence\":\"1\""); + + byte[] altered = authorityEvent.payload(); + altered[altered.length - 2] = altered[altered.length - 2] == 'a' ? (byte) 'b' : (byte) 'a'; + assertThatThrownBy(() -> TenantAuthorityEventV1Codec.verify(altered)) + .isInstanceOf(IllegalArgumentException.class); + } + + private static FreshTenantCreationEvidence source(UUID tenantId) { + UUID creationRequestId = UUID.fromString("22222222-2222-4222-8222-222222222222"); + UUID operationId = UUID.fromString("33333333-3333-4333-8333-333333333333"); + String requestDigest = "sha256:" + "a".repeat(64); + String evidenceDigest = + GameTenantCreationDigest.evidenceDigest( + "account-service", + creationRequestId, + operationId, + requestDigest, + tenantId, + 801L, + "tenant-801", + "NEW_GAME_ROW"); + return new FreshTenantCreationEvidence( + 1, + "account-service", + creationRequestId, + operationId, + requestDigest, + tenantId, + 801L, + "tenant-801", + "NEW_GAME_ROW", + evidenceDigest); + } +} From d87068635ad2833c8e0edd5800ccad8f22163f69 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 7 Oct 2026 08:04:25 +1300 Subject: [PATCH 2/9] feat(account): compose immutable authority sources and receipt readback --- .../account-service/runtime-and-data.md | 2 + design/project-management/ai-observations.md | 6 + .../player-access-and-session.md | 6 + .../DraftAuthorizationFenceBinding.java | 419 ++++++++ .../DraftAuthorizationFenceRepository.java | 652 ++++++++++++ .../dto/AccountLogoutRequestDigest.java | 116 +++ .../AccountSecurityStateMutationRequest.java | 173 +++ .../AccountSecurityStateRequestDigest.java | 51 + ...ountAuthoritySourceEvidenceRepository.java | 553 +++++++++- .../AccountLogoutAllOperationRepository.java | 321 ++++++ ...countPasswordResetOperationRepository.java | 316 ++++++ .../repository/AccountRepository.java | 10 + ...countSecurityStateOperationRepository.java | 662 ++++++++++++ ...AccountTenantAuthorityEventRepository.java | 2 +- .../AccountAuthoritySourceEventReadback.java | 714 +++++++++++++ .../service/AccountAuthoritySourceReader.java | 237 +++++ .../service/AccountGenerationProjection.java | 355 +++++++ .../service/IssuerGenerationProjection.java | 258 +++++ .../V74.1__account_global_role_source.sql | 158 +++ ...account_gameplay_token_identity_fences.sql | 85 ++ ...ount_password_reset_operation_receipts.sql | 91 ++ ...V76__draft_commit_authorization_fences.sql | 167 +++ ..._account_logout_all_operation_receipts.sql | 90 ++ ...V78__account_security_state_operations.sql | 401 +++++++ ...StateOperationPostgresIntegrationTest.java | 984 ++++++++++++++++++ ...orizationFencePostgresIntegrationTest.java | 661 ++++++++++++ ...stJoinAuthorityStorageIntegrationTest.java | 4 +- .../DraftAuthorizationFenceBindingTest.java | 446 ++++++++ .../dto/AccountLogoutRequestDigestTest.java | 105 ++ ...countSecurityStateMutationRequestTest.java | 182 ++++ ...AuthoritySourceEvidenceRepositoryTest.java | 291 +++++- ...tPasswordResetOperationRepositoryTest.java | 132 +++ .../repository/AccountRepositoryTest.java | 44 + ...tSecurityStateOperationRepositoryTest.java | 48 + ...untTenantAuthorityEventRepositoryTest.java | 147 +++ ...AccountJwtReadinessTlsInterceptorTest.java | 3 +- ...countAuthoritySourceEventReadbackTest.java | 775 ++++++++++++++ .../AccountGenerationProjectionTest.java | 334 ++++++ .../IssuerGenerationProjectionTest.java | 122 +++ ...AccountLogoutAllAuthorityEventV1Codec.java | 355 +++++++ ...untSecurityStateAuthorityEventV1Codec.java | 391 +++++++ ...IssuerGenerationAuthorityEventV1Codec.java | 327 ++++++ .../PasswordResetAuthorityEventV1Codec.java | 372 +++++++ .../common/authoring/DraftCommitBinding.java | 454 ++++++++ ...untLogoutAllAuthorityEventV1CodecTest.java | 197 ++++ ...ecurityStateAuthorityEventV1CodecTest.java | 327 ++++++ ...erGenerationAuthorityEventV1CodecTest.java | 194 ++++ ...asswordResetAuthorityEventV1CodecTest.java | 167 +++ .../authoring/DraftCommitBindingTest.java | 224 ++++ ...th-issuer-generation-event-v1-vectors.json | 126 +++ ...ount-auth-logout-all-event-v1-vectors.json | 150 +++ ...-auth-password-reset-event-v1-vectors.json | 136 +++ 52 files changed, 13519 insertions(+), 24 deletions(-) create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceBinding.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceRepository.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountLogoutRequestDigest.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountSecurityStateMutationRequest.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountSecurityStateRequestDigest.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountLogoutAllOperationRepository.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepository.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountSecurityStateOperationRepository.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadback.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceReader.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountGenerationProjection.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/IssuerGenerationProjection.java create mode 100644 services/account-service/src/main/resources/db/migration/V74.1__account_global_role_source.sql create mode 100644 services/account-service/src/main/resources/db/migration/V74__account_gameplay_token_identity_fences.sql create mode 100644 services/account-service/src/main/resources/db/migration/V75__account_password_reset_operation_receipts.sql create mode 100644 services/account-service/src/main/resources/db/migration/V76__draft_commit_authorization_fences.sql create mode 100644 services/account-service/src/main/resources/db/migration/V77__account_logout_all_operation_receipts.sql create mode 100644 services/account-service/src/main/resources/db/migration/V78__account_security_state_operations.sql create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountSecurityStateOperationPostgresIntegrationTest.java create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFencePostgresIntegrationTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceBindingTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountLogoutRequestDigestTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountSecurityStateMutationRequestTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepositoryTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountSecurityStateOperationRepositoryTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepositoryTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadbackTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountGenerationProjectionTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/IssuerGenerationProjectionTest.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/AccountLogoutAllAuthorityEventV1Codec.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1Codec.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/IssuerGenerationAuthorityEventV1Codec.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/PasswordResetAuthorityEventV1Codec.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/DraftCommitBinding.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountLogoutAllAuthorityEventV1CodecTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1CodecTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/IssuerGenerationAuthorityEventV1CodecTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/PasswordResetAuthorityEventV1CodecTest.java create mode 100644 services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/authoring/DraftCommitBindingTest.java create mode 100644 services/common-platform-core/src/test/resources/net/firedevops/firemud/common/account/authority/account-auth-issuer-generation-event-v1-vectors.json create mode 100644 services/common-platform-core/src/test/resources/net/firedevops/firemud/common/account/authority/account-auth-logout-all-event-v1-vectors.json create mode 100644 services/common-platform-core/src/test/resources/net/firedevops/firemud/common/account/authority/account-auth-password-reset-event-v1-vectors.json diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index 377452b975..8c348ad475 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -8,6 +8,8 @@ Account owns platform identity, hosted Creator Party/operator and terms currentn ## Implementation Status +The source-only Account authority-event and receipt/readback cut adds typed event codecs and vectors, draft-commit binding, owner-local operation receipts, and current-source event readback/projections above the separate tenant-authority and signer/readiness foundations. Its schema set is V74, V74.1, and V75–V78; the rejecting V61 migration and V74.1 legacy scalar-role guard are withheld, while V74.1's immutable, truncate, and fresh-birth source guards remain and reserved V79/V80 are untouched. The enabled `AccountRepository.save` path records a scalar role update as generic Account source history without changing the immutable empty global-role source; closed currentness/readback rejects that generic history. This is not canonical global-role authority, producer convergence, or activation of public LOGIN, issuance, credential release, or PLAY. The canonical role writer remains pending. Composed compilation, unit, packaged-JAR and formatting proof passes; the focused PostgreSQL regression is unexecuted, and physical PostgreSQL/Redis proof has not run. Detailed counts and limits belong to the [Account source event and receipt foundation status](../../../project-management/implementation-tracking/player-access-and-session.md#account-authority-event-and-receipt-source-foundation). + The source-only tenant-authority foundation adds Account-local non-paid entitlement storage, its immutable billing outbox, and typed tenant-authority source/current-checkpoint owners. It imports no public provisioning facade, operational activation, credential release, or gameplay admission. Physical PostgreSQL and runtime proof remain pending; see the [tenant-authority source foundation status](../../../project-management/implementation-tracking/player-access-and-session.md#account-tenant-authority-source-foundation). The source-only signer/JWKS and readiness foundation adds owner-local storage, closed shared JWT contracts, protected materializer handoff and focused readiness validation components. It does not provision signer material or activate public authentication, credential release, first-bound admission, or cluster resources. Detailed capability and proof limits remain in the [Player Access and Session tracker](../../../project-management/implementation-tracking/player-access-and-session.md#account-signer-and-readiness-source-foundation). diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index c1624662fb..69ffcb919e 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -48,3 +48,9 @@ Entry format: - Expected pattern: obtain explicit infrastructure authorization before provisioning, record the exact run-owned resource and cleanup responsibility privately, and announce remote proof distinctly from local tests and required CI. Use a permitted existing fixture only when targeted iteration is materially faster; do not add a redundant pre-publication gate. - Current status: continued use of the existing bounded fixture is explicitly approved; additional provisioning is not. Original setup authorization remains unverified, and hosted CI remains required. - Reconsideration trigger: revisit when the original provisioning authorization is confirmed or the fixture is retired, and before any additional remote provisioning. + +- `2026-10-07`: Validate transferred fixed-vector artifacts before treating them as source evidence + - Context: the Account authority storage composition included three JSON resources whose contents were failed shell-read diagnostics, not test vectors; shared codec tests failed during initialization. + - Expected pattern: verify successful source reads and parse transferred structured fixtures before integration. Preserve authentic fixed vectors and their source revision instead of replacing expected values with implementation-generated output. + - Current status: issuer vectors were recovered from composition history at `8344e6ea1`; reset and logout vectors were recovered from preserved main resources. All three parse as JSON, and all 173 shared-platform unit cases pass after recovery. + - Reconsideration trigger: check source-read success and fixture parsing on the next structured-artifact transfer; no new general-purpose tooling is required for this bounded repair. 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 9b13249f85..3c726047e5 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -29,6 +29,12 @@ Smoke identity consequence: the current demo-credential `LOGIN -> PLAY -> LOOK` SEC-04 does not move player session ownership into Logging & Admin. Game Session `/sessions*` lifecycle routes remain current owner-local hooks with direct owner edge exposure denied; the target external operator path forwards from Logging & Admin to Game Session after Account issues the authorization reference and the receiving Game Session redeems that same reference. That target lifecycle family, and other operator mutation families gated by action schemas, shared `mutationDigest/v1` vectors, and the authorization-reference flow, are not currently available to players or operators. +## Account Authority Event and Receipt Source Foundation + +The 45-path source-only Account cut adds typed immutable authority-event codecs/vectors, draft-commit binding, owner-local reset/logout/security-state receipts, and current-source event readback/projections above the separate tenant-source and signer/readiness foundations. Its schema set is V74, V74.1, and V75–V78; rejecting V61 and V74.1 legacy scalar-role guards are withheld, while V74.1's immutable, truncate, and fresh-birth source guards remain and reserved V79/V80 are untouched. The enabled `AccountRepository.save` path records scalar role updates as generic Account source history without changing the immutable empty global-role source; closed currentness/readback rejects that generic history. This does not make the legacy scalar field canonical global-role authority; the canonical role writer remains pending. It is storage/readback preparation, not operation-specific receipt convergence or activation of public LOGIN, issuance, credential release, or PLAY. + +The composed source boundary passes Account jOOQ, main/unit/integration-source compilation, boot JAR, focused source tests (65 clean executions), all shared-platform unit tests (173 clean executions), and the broader Account unit suite (844 executions, zero failures, three filesystem-assumption skips in `AccountJwtJwksApiTransportTest`). The billing-event UUID binding has a focused argument-type regression; FirstJoin storage fixtures preserve latest migration constraints without inventing tenant source authority. Java formatting with `fullCheck`, link checking and Markdown linting pass. Physical PostgreSQL, Redis and fresh-image proof have not run; integration-source compilation is not migration execution or playable-entry proof. + ## Account Tenant Authority Source Foundation The Account-local tenant-source prerequisite consists of V53's explicit non-paid entitlement operation/current-head and immutable billing outbox storage, V73's typed head over the existing authority outbox, the corresponding source repositories and closed codecs, and focused codec/PostgreSQL source tests. It reuses the inherited fresh-tenant association, canonical tenant claim, authority generation/outbox, V40 provenance, and run-owned PostgreSQL fixture owners. Retained tenant rows are not assigned fabricated initialization provenance; complete billing and authority receipts remain correlated by the existing SQL guards. This is a persistence/source prerequisite for later selected-authority projection, not public entitlement provisioning or an admission decision; canonical local ownership remains in [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md). diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceBinding.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceBinding.java new file mode 100644 index 0000000000..ea1e488fca --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceBinding.java @@ -0,0 +1,419 @@ +package net.firedevops.firemud.accountservice.authordraft; + +import java.io.ByteArrayOutputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Arrays; +import java.util.Comparator; +import java.util.HexFormat; +import java.util.List; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; + +/** Exact immutable source material, not an authorization decision or authenticated actor proof. */ +public record DraftAuthorizationFenceBinding( + UUID operationId, + UUID requestId, + UUID commitId, + UUID fenceId, + UUID actorAccountId, + UUID tenantId, + UUID versionId, + String baseCommitId, + String expectedDraftEpoch, + byte[] gameDesignBinding, + byte[] normalizedInput, + String inputDigest, + List sources) { + + public static final String SCHEMA = "account-draft-authorization-fence/v1"; + + public DraftAuthorizationFenceBinding { + for (UUID id : + List.of(operationId, requestId, commitId, fenceId, actorAccountId, tenantId, versionId)) { + requireUuid(id); + } + text(baseCommitId); + if (baseCommitId.getBytes(StandardCharsets.UTF_8).length > 256) { + throw new IllegalArgumentException("Base commit exceeds 256 UTF-8 bytes"); + } + decimal(expectedDraftEpoch, true); + gameDesignBinding = bytes(gameDesignBinding); + normalizedInput = bytes(normalizedInput); + DraftCommitBinding completeBinding; + try { + completeBinding = + DraftCommitBinding.fromStored( + new String(gameDesignBinding, StandardCharsets.UTF_8), digest(gameDesignBinding)); + } catch (IllegalStateException corrupt) { + throw new IllegalArgumentException( + "Complete canonical Game Design binding required", corrupt); + } + if (!Arrays.equals(gameDesignBinding, completeBinding.canonicalBytes()) + || !requestId.equals(completeBinding.requestId()) + || !commitId.equals(completeBinding.commitId()) + || !tenantId.equals(completeBinding.target().canonicalTenantId()) + || !versionId.equals(completeBinding.target().canonicalVersionId()) + || !baseCommitId.equals(completeBinding.baseCommitId())) { + throw new IllegalArgumentException("Account fence differs from complete Game Design binding"); + } + if (!Arrays.equals(normalizedInput, gameDesignBinding) + || !completeBinding.digest().equals(inputDigest)) { + throw new IllegalArgumentException( + "Draft input must be the exact complete canonical binding"); + } + sources = List.copyOf(Objects.requireNonNull(sources)); + if (sources.isEmpty()) { + throw new IllegalArgumentException("Applicable Account sources are required"); + } + sources = sources.stream().sorted(Comparator.comparing(SourceEvidence::key)).toList(); + if (sources.stream().map(SourceEvidence::key).distinct().count() != sources.size()) { + throw new IllegalArgumentException("Duplicate Account source scope"); + } + } + + @Override + public List sources() { + return List.copyOf(sources); + } + + @Override + public byte[] gameDesignBinding() { + return gameDesignBinding.clone(); + } + + @Override + public byte[] normalizedInput() { + return normalizedInput.clone(); + } + + /** Closed, ordered UTF-8/binary length frames; counters are exact decimal strings. */ + public byte[] canonicalBytes() { + ByteArrayOutputStream output = new ByteArrayOutputStream(); + frame(output, SCHEMA); + for (UUID id : + List.of(operationId, requestId, commitId, fenceId, actorAccountId, tenantId, versionId)) { + frame(output, id.toString()); + } + frame(output, baseCommitId); + frame(output, "DRAFT"); + frame(output, expectedDraftEpoch); + frame(output, gameDesignBinding); + frame(output, normalizedInput); + frame(output, inputDigest); + frame(output, Integer.toString(sources.size())); + for (SourceEvidence source : sources) { + frame(output, source.canonicalBytes()); + } + frame(output, "GAME_DESIGN"); + frame(output, "WORLD"); + return output.toByteArray(); + } + + public enum SourceKind { + ISSUER, + ACCOUNT, + TENANT, + MEMBERSHIP, + GLOBAL_ROLES, + CREATOR_PARTY, + HOSTED_TERMS + } + + /** + * Independent owner counters/checkpoints and exact existing source evidence; no inferred epochs. + */ + public record SourceEvidence( + SourceKind kind, + String scopeId, + String generation, + String sourceVersion, + String checkpointStream, + String checkpointSequence, + byte[] evidence) { + public SourceEvidence { + Objects.requireNonNull(kind); + text(scopeId); + // Preserve the exact configured issuer, including its supported 512-character Unicode + // identity. Bound the complete index key in bytes rather than truncating or aliasing it. + if ((kind.name() + ":" + scopeId).getBytes(StandardCharsets.UTF_8).length > 2048) { + throw new IllegalArgumentException("Source participation key exceeds 2048 UTF-8 bytes"); + } + if (kind == SourceKind.ACCOUNT + || kind == SourceKind.TENANT + || kind == SourceKind.GLOBAL_ROLES) { + canonicalUuid(scopeId); + } + if (kind == SourceKind.MEMBERSHIP) { + String[] pair = scopeId.split("/", -1); + if (pair.length != 2) { + throw new IllegalArgumentException("Canonical membership pair required"); + } + canonicalUuid(pair[0]); + canonicalUuid(pair[1]); + } + if (generation != null) { + decimal(generation, false); + } + decimal(sourceVersion, false); + if ((checkpointStream == null) != (checkpointSequence == null)) { + throw new IllegalArgumentException("Checkpoint fields must be applicable together"); + } + if (checkpointStream != null) { + text(checkpointStream); + decimal(checkpointSequence, true); + } + evidence = bytes(evidence); + } + + @Override + public byte[] evidence() { + return evidence.clone(); + } + + public String key() { + return kind.name() + ":" + scopeId; + } + + public byte[] canonicalBytes() { + ByteArrayOutputStream output = new ByteArrayOutputStream(); + for (String value : List.of("account-draft-source-evidence/v1", kind.name(), scopeId)) { + frame(output, value); + } + frame(output, generation == null ? "ABSENT" : "PRESENT"); + if (generation != null) { + frame(output, generation); + } + frame(output, sourceVersion); + frame(output, checkpointStream == null ? "ABSENT" : "PRESENT"); + if (checkpointStream != null) { + frame(output, checkpointStream); + frame(output, checkpointSequence); + } + frame(output, evidence); + return output.toByteArray(); + } + + /** Decodes only the exact immutable framing written by this source owner. */ + public static SourceEvidence fromStored(byte[] stored) { + FrameReader reader = new FrameReader(stored); + reader.expect("account-draft-source-evidence/v1"); + SourceKind kind = SourceKind.valueOf(reader.text()); + String scope = reader.text(); + String generation = reader.optionalText(); + String version = reader.text(); + String stream = reader.optionalText(); + String sequence = stream == null ? null : reader.text(); + SourceEvidence source = + new SourceEvidence(kind, scope, generation, version, stream, sequence, reader.bytes()); + reader.requireEnd(); + if (!Arrays.equals(stored, source.canonicalBytes())) { + throw new IllegalArgumentException("Noncanonical stored source evidence"); + } + return source; + } + } + + /** Bounded exact frame decoding for persisted source evidence and source-change intent. */ + static final class FrameReader { + private final ByteBuffer input; + + FrameReader(byte[] stored) { + input = ByteBuffer.wrap(DraftAuthorizationFenceBinding.bytes(stored)); + } + + byte[] bytes() { + if (input.remaining() < Integer.BYTES) { + throw new IllegalArgumentException("Truncated immutable source frame"); + } + int size = input.getInt(); + if (size < 0 || size > input.remaining()) { + throw new IllegalArgumentException("Invalid immutable source frame size"); + } + byte[] value = new byte[size]; + input.get(value); + return value; + } + + String text() { + byte[] value = bytes(); + String text = new String(value, StandardCharsets.UTF_8); + DraftAuthorizationFenceBinding.text(text); + if (!Arrays.equals(value, text.getBytes(StandardCharsets.UTF_8))) { + throw new IllegalArgumentException("Invalid UTF-8 source frame"); + } + return text; + } + + String optionalText() { + String presence = text(); + if ("ABSENT".equals(presence)) { + return null; + } + if (!"PRESENT".equals(presence)) { + throw new IllegalArgumentException("Invalid immutable source presence"); + } + return text(); + } + + void expect(String expected) { + if (!expected.equals(text())) { + throw new IllegalArgumentException("Unsupported immutable source schema"); + } + } + + int remaining() { + return input.remaining(); + } + + void requireEnd() { + if (input.hasRemaining()) { + throw new IllegalArgumentException("Trailing immutable source frames"); + } + } + } + + public enum Owner { + GAME_DESIGN, + WORLD + } + + public enum Outcome { + COMMITTED, + DEFINITIVELY_ABORTED + } + + /** Only a future authenticated owner verifier may supply this exact durable readback. */ + public record OwnerReadback( + Owner owner, + Outcome outcome, + UUID operationId, + UUID commitId, + UUID fenceId, + String inputDigest, + byte[] fullBinding, + byte[] result) { + public OwnerReadback { + Objects.requireNonNull(owner); + Objects.requireNonNull(outcome); + requireUuid(operationId); + requireUuid(commitId); + requireUuid(fenceId); + if (inputDigest == null || !inputDigest.matches("sha256:[0-9a-f]{64}")) { + throw new IllegalArgumentException("Canonical digest required"); + } + fullBinding = bytes(fullBinding); + result = bytes(result); + } + + @Override + public byte[] fullBinding() { + return fullBinding.clone(); + } + + @Override + public byte[] result() { + return result.clone(); + } + + public void requireBinding(DraftAuthorizationFenceBinding binding) { + if (!operationId.equals(binding.operationId()) + || !commitId.equals(binding.commitId()) + || !fenceId.equals(binding.fenceId()) + || !inputDigest.equals(binding.inputDigest()) + || !Arrays.equals(fullBinding, binding.canonicalBytes())) { + throw new IllegalArgumentException("Owner readback differs from complete Draft binding"); + } + } + + public byte[] canonicalBytes() { + ByteArrayOutputStream output = new ByteArrayOutputStream(); + for (String value : + List.of( + "account-draft-owner-readback/v1", + owner.name(), + outcome.name(), + operationId.toString(), + commitId.toString(), + fenceId.toString(), + inputDigest)) { + frame(output, value); + } + frame(output, fullBinding); + frame(output, result); + return output.toByteArray(); + } + } + + static byte[] bytes(byte[] value) { + if (value == null || value.length == 0) { + throw new IllegalArgumentException("Exact bytes required"); + } + return value.clone(); + } + + static void requireUuid(UUID value) { + if (value == null || value.equals(new UUID(0, 0))) { + throw new IllegalArgumentException("Non-nil UUID required"); + } + } + + static void canonicalUuid(String value) { + UUID id = UUID.fromString(value); + requireUuid(id); + if (!id.toString().equals(value)) { + throw new IllegalArgumentException("Canonical UUID required"); + } + } + + static void text(String value) { + if (value == null || value.isBlank() || value.indexOf('\0') >= 0) { + throw new IllegalArgumentException("Nonempty canonical text required"); + } + for (int i = 0; i < value.length(); i++) { + char c = value.charAt(i); + if (Character.isHighSurrogate(c)) { + if (++i >= value.length() || !Character.isLowSurrogate(value.charAt(i))) { + throw new IllegalArgumentException("Unpaired surrogate"); + } + } else if (Character.isLowSurrogate(c)) { + throw new IllegalArgumentException("Unpaired surrogate"); + } + } + } + + static void decimal(String value, boolean zero) { + if (value == null || !value.matches(zero ? "0|[1-9][0-9]*" : "[1-9][0-9]*")) { + throw new IllegalArgumentException("Canonical decimal string required"); + } + } + + static void frame(ByteArrayOutputStream output, String value) { + text(value); + frame(output, value.getBytes(StandardCharsets.UTF_8)); + } + + static void frame(ByteArrayOutputStream output, byte[] value) { + try { + DataOutputStream data = new DataOutputStream(output); + data.writeInt(value.length); + data.write(value); + } catch (IOException impossible) { + throw new IllegalStateException(impossible); + } + } + + public static String digest(byte[] value) { + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value)); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException(impossible); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceRepository.java new file mode 100644 index 0000000000..ba50e2416d --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceRepository.java @@ -0,0 +1,652 @@ +package net.firedevops.firemud.accountservice.authordraft; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.io.ByteArrayOutputStream; +import java.sql.Connection; +import java.time.OffsetDateTime; +import java.util.Arrays; +import java.util.Comparator; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceBinding.Outcome; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceBinding.Owner; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceBinding.OwnerReadback; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceBinding.SourceEvidence; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Unwired durable ordering component. Every method requires a writable caller READ_COMMITTED + * Account transaction. Callers lock/revalidate actual authority sources first, then this component + * locks sorted source participation rows and sorted operations. Never hold these locks across RPC. + * Reservation and returned source evidence alone grant no owner commit permission. + * + *

Future authenticated capture/source-change and owner-readback producers are mandatory. This + * class does not authenticate supplied evidence or manufacture missing role/terms source state. + */ +public final class DraftAuthorizationFenceRepository { + private static final String FENCES = "account_draft_authorization_fences"; + private static final String SOURCES = "account_draft_authorization_sources"; + private static final String READBACKS = "account_draft_authorization_owner_readbacks"; + private static final String CHANGES = "account_draft_authorization_source_changes"; + private static final String CHANGED = "account_draft_authorization_changed_scopes"; + private final DSLContext dsl; + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = + "Injected DSLContext is an internal owner-transaction persistence collaborator.") + public DraftAuthorizationFenceRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl); + } + + public enum Ordering { + RESERVED, + COMMIT_ORDER, + REVOKE_ORDER + } + + public enum Settlement { + PENDING, + COMMITTED, + FAILED_NONPUBLICATION + } + + /** Terminal reason for an Account source change that made no source mutation. */ + public enum SourceChangeAbortReason { + EXPIRED, + DEFINITIVE_ABORT + } + + public record FenceSnapshot( + Ordering ordering, byte[] binding, OffsetDateTime reservedAt, OffsetDateTime orderedAt) { + public FenceSnapshot { + binding = binding.clone(); + } + + @Override + public byte[] binding() { + return binding.clone(); + } + } + + public record OwnerResultSnapshot(Outcome outcome, byte[] readback, OffsetDateTime recordedAt) { + public OwnerResultSnapshot { + readback = readback.clone(); + } + + @Override + public byte[] readback() { + return readback.clone(); + } + } + + public record SourceChangeSnapshot( + UUID changeId, + byte[] binding, + String status, + OffsetDateTime requestedAt, + OffsetDateTime committedAt, + OffsetDateTime abortedAt, + SourceChangeAbortReason abortReason) { + public SourceChangeSnapshot { + binding = binding.clone(); + } + + @Override + public byte[] binding() { + return binding.clone(); + } + } + + /** Full exact mutation intent and independently captured affected source vector. */ + public record SourceChange(UUID changeId, List sources, byte[] mutation) { + public SourceChange { + DraftAuthorizationFenceBinding.requireUuid(changeId); + sources = + List.copyOf(Objects.requireNonNull(sources)).stream() + .sorted(Comparator.comparing(SourceEvidence::key)) + .toList(); + if (sources.isEmpty() + || sources.stream().map(SourceEvidence::key).distinct().count() != sources.size()) { + throw new IllegalArgumentException("Distinct affected sources required"); + } + mutation = DraftAuthorizationFenceBinding.bytes(mutation); + } + + @Override + public List sources() { + return List.copyOf(sources); + } + + @Override + public byte[] mutation() { + return mutation.clone(); + } + + public byte[] canonicalBytes() { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(out, "account-draft-source-change/v1"); + DraftAuthorizationFenceBinding.frame(out, changeId.toString()); + DraftAuthorizationFenceBinding.frame(out, Integer.toString(sources.size())); + for (SourceEvidence source : sources) { + DraftAuthorizationFenceBinding.frame(out, source.canonicalBytes()); + } + DraftAuthorizationFenceBinding.frame(out, mutation); + return out.toByteArray(); + } + + /** + * Exact recovery of the original vector; callers must never replace it with a fresh capture. + */ + public static SourceChange fromStored(byte[] stored) { + var reader = new DraftAuthorizationFenceBinding.FrameReader(stored); + reader.expect("account-draft-source-change/v1"); + String id = reader.text(); + DraftAuthorizationFenceBinding.canonicalUuid(id); + String count = reader.text(); + DraftAuthorizationFenceBinding.decimal(count, false); + final int size; + try { + size = Integer.parseInt(count); + } catch (NumberFormatException invalid) { + throw new IllegalArgumentException("Stored source count is out of range", invalid); + } + if (size > reader.remaining() / Integer.BYTES) { + throw new IllegalArgumentException("Incomplete stored source vector"); + } + java.util.ArrayList sources = new java.util.ArrayList<>(); + for (int i = 0; i < size; i++) { + sources.add(SourceEvidence.fromStored(reader.bytes())); + } + SourceChange change = new SourceChange(UUID.fromString(id), sources, reader.bytes()); + reader.requireEnd(); + if (!Arrays.equals(stored, change.canonicalBytes())) { + throw new IllegalArgumentException("Noncanonical stored source change"); + } + return change; + } + } + + /** + * Already-existing source capture only. Future producer must establish completeness/currentness. + */ + public FenceSnapshot reserve(DraftAuthorizationFenceBinding binding) { + requireTransaction(); + lockSources(binding.sources()); + Record existing = readOperation(binding.operationId()); + if (existing != null) { + return snapshot(requireExact(existing, binding)); + } + if (hasWaitingChange(binding.sources())) { + throw new IllegalStateException("Applicable authority source change is waiting"); + } + dsl.execute( + "INSERT INTO " + + FENCES + + " (operation_id, request_id, commit_id, fence_id, binding, ordering) VALUES (?, ?, ?, ?, ?, 'RESERVED')", + binding.operationId(), + binding.requestId(), + binding.commitId(), + binding.fenceId(), + binding.canonicalBytes()); + for (SourceEvidence source : binding.sources()) { + dsl.execute( + "INSERT INTO " + + SOURCES + + " (operation_id, source_key, source_evidence) VALUES (?, ?, ?)", + binding.operationId(), + source.key(), + source.canonicalBytes()); + } + return snapshot(requireExact(readOperation(binding.operationId()), binding)); + } + + /** + * Irrevocable exact operation order; revalidate actual source state under its locks before + * calling. + */ + public FenceSnapshot claimCommitOrder(DraftAuthorizationFenceBinding binding) { + requireTransaction(); + lockSources(binding.sources()); + Record row = requireExact(readOperation(binding.operationId()), binding); + Ordering ordering = Ordering.valueOf(row.get("ordering", String.class)); + if (ordering == Ordering.COMMIT_ORDER) { + return snapshot(row); + } + if (ordering == Ordering.REVOKE_ORDER || hasWaitingChange(binding.sources())) { + throw new IllegalStateException("Revocation precedes this owner commit"); + } + dsl.execute( + "UPDATE " + + FENCES + + " SET ordering = 'COMMIT_ORDER', ordered_at = CURRENT_TIMESTAMP" + + " WHERE operation_id = ? AND ordering = 'RESERVED'", + binding.operationId()); + return snapshot(requireExact(readOperation(binding.operationId()), binding)); + } + + /** + * Commit this WAITING result even when false: rolling back would lose revocation intent. True + * means settled or an exact SOURCE_COMMITTED replay; call sourceMutationPermitted before writing. + * A distinct request overlapping an already pending source change is not admitted: it must not + * retain a second old-state capture that becomes stale when the first source change commits. + */ + public boolean requestSourceChange(SourceChange change) { + requireTransaction(); + lockSources(change.sources()); + Record prior = readChange(change.changeId()); + if (prior != null) { + requireChange(prior, change); + String priorStatus = prior.get("status", String.class); + if ("SOURCE_COMMITTED".equals(priorStatus)) { + return true; + } + if ("SOURCE_ABORTED".equals(priorStatus)) { + throw new IllegalStateException("Aborted source change cannot be requested again"); + } + if (!"WAITING".equals(priorStatus)) { + throw new IllegalStateException("Source change has an unsupported terminal state"); + } + } else { + if (hasWaitingChange(change.sources())) { + throw new IllegalStateException("Another authority source change is already pending"); + } + dsl.execute( + "INSERT INTO " + CHANGES + " (change_id, binding, status) VALUES (?, ?, 'WAITING')", + change.changeId(), + change.canonicalBytes()); + for (SourceEvidence source : change.sources()) { + dsl.execute( + "INSERT INTO " + CHANGED + " (change_id, source_key) VALUES (?, ?)", + change.changeId(), + source.key()); + } + } + for (UUID operation : affectedOperations(change.sources())) { + Record row = readOperation(operation); + if ("RESERVED".equals(row.get("ordering", String.class))) { + dsl.execute( + "UPDATE " + + FENCES + + " SET ordering = 'REVOKE_ORDER', ordered_at = CURRENT_TIMESTAMP" + + " WHERE operation_id = ? AND ordering = 'RESERVED'", + operation); + } + } + return allAffectedSettled(change.sources()); + } + + /** Verify before the first source mutation and retain the transaction through source commit. */ + public boolean sourceMutationPermitted(SourceChange change) { + requireTransaction(); + lockSources(change.sources()); + Record row = readChange(change.changeId()); + requireChange(row, change); + return "WAITING".equals(row.get("status", String.class)) + && allAffectedSettled(change.sources()); + } + + /** A no-mutation cancellation is safe only after every affected owner operation is settled. */ + public boolean sourceAbortPermitted(SourceChange change) { + requireTransaction(); + lockSources(change.sources()); + Record row = readChange(change.changeId()); + requireChange(row, change); + return "WAITING".equals(row.get("status", String.class)) + && allAffectedSettled(change.sources()); + } + + /** + * Same transaction as actual source mutation/event/readback. No RPC or fake source write here. + */ + public void markSourceCommitted(SourceChange change) { + requireTransaction(); + lockSources(change.sources()); + Record row = readChange(change.changeId()); + requireChange(row, change); + String status = row.get("status", String.class); + if ("SOURCE_COMMITTED".equals(status)) { + return; + } + if ("SOURCE_ABORTED".equals(status)) { + throw new IllegalStateException("Aborted source change cannot be committed"); + } + if (!"WAITING".equals(status)) { + throw new IllegalStateException("Source change is not waiting"); + } + if (!allAffectedSettled(change.sources())) { + throw new IllegalStateException("Owner outcomes unresolved"); + } + int updated = + dsl.execute( + "UPDATE " + + CHANGES + + " SET status = 'SOURCE_COMMITTED', committed_at = CURRENT_TIMESTAMP" + + " WHERE change_id = ? AND status = 'WAITING'", + change.changeId()); + if (updated != 1) { + throw new IllegalStateException("Draft source change did not commit exactly once"); + } + } + + /** + * Records a terminal no-mutation result. The same ordering-aware settlement predicate used for + * source commit applies: revoke order requires two definitive aborts; commit order requires two + * exact terminal owner readbacks, including a mixed vector. + */ + public void markSourceAborted(SourceChange change, SourceChangeAbortReason reason) { + requireTransaction(); + Objects.requireNonNull(reason, "source-change abort reason"); + lockSources(change.sources()); + Record row = readChange(change.changeId()); + requireChange(row, change); + String status = row.get("status", String.class); + if ("SOURCE_ABORTED".equals(status)) { + if (!reason.name().equals(row.get("abort_reason", String.class))) { + throw new IllegalArgumentException("Source change abort reason differs from readback"); + } + return; + } + if ("SOURCE_COMMITTED".equals(status)) { + throw new IllegalStateException("Committed source change cannot be aborted"); + } + if (!"WAITING".equals(status)) { + throw new IllegalStateException("Source change is not waiting"); + } + if (!allAffectedSettled(change.sources())) { + throw new IllegalStateException("Owner outcomes unresolved"); + } + int updated = + dsl.execute( + "UPDATE " + + CHANGES + + " SET status = 'SOURCE_ABORTED', aborted_at = CURRENT_TIMESTAMP, abort_reason = ?" + + " WHERE change_id = ? AND status = 'WAITING'", + reason.name(), + change.changeId()); + if (updated != 1) { + throw new IllegalStateException("Draft source change did not abort exactly once"); + } + } + + /** Exact durable owner readback, supplied only by the future authenticated owner verifier. */ + public void recordOwnerReadback(DraftAuthorizationFenceBinding binding, OwnerReadback readback) { + requireTransaction(); + readback.requireBinding(binding); + Record row = requireExact(readOperation(binding.operationId()), binding); + if ("RESERVED".equals(row.get("ordering", String.class))) { + throw new IllegalStateException("Reservation alone cannot produce terminal owner evidence"); + } + Record prior = + dsl.fetchOne( + "SELECT readback FROM " + READBACKS + " WHERE operation_id = ? AND owner = ?", + binding.operationId(), + readback.owner().name()); + if (prior != null) { + if (!Arrays.equals(prior.get("readback", byte[].class), readback.canonicalBytes())) { + throw new IllegalArgumentException("Changed owner terminal evidence"); + } + return; + } + dsl.execute( + "INSERT INTO " + + READBACKS + + " (operation_id, owner, outcome, readback) VALUES (?, ?, ?, ?)", + binding.operationId(), + readback.owner().name(), + readback.outcome().name(), + readback.canonicalBytes()); + } + + public FenceSnapshot read(DraftAuthorizationFenceBinding binding) { + requireTransaction(); + return snapshot(requireExact(readOperation(binding.operationId()), binding)); + } + + /** Derived exact settlement only; original ordering and owner readbacks remain immutable. */ + public Settlement readSettlement(DraftAuthorizationFenceBinding binding) { + requireTransaction(); + Record row = requireExact(readOperation(binding.operationId()), binding); + return settlement(binding.operationId(), Ordering.valueOf(row.get("ordering", String.class))); + } + + /** Absence means UNKNOWN, never no-commit proof. */ + public Optional readOwnerResult( + DraftAuthorizationFenceBinding binding, Owner owner) { + requireTransaction(); + requireExact(readOperation(binding.operationId()), binding); + Record row = + dsl.fetchOne( + "SELECT outcome, readback, recorded_at FROM " + + READBACKS + + " WHERE operation_id = ? AND owner = ?", + binding.operationId(), + owner.name()); + return row == null + ? Optional.empty() + : Optional.of( + new OwnerResultSnapshot( + Outcome.valueOf(row.get("outcome", String.class)), + row.get("readback", byte[].class), + row.get("recorded_at", OffsetDateTime.class))); + } + + /** Durable recovery discovery only; no auto-running worker or authority decision. */ + public List waitingSourceChanges() { + requireTransaction(); + return dsl + .fetch("SELECT * FROM " + CHANGES + " WHERE status = 'WAITING' ORDER BY change_id") + .stream() + .map( + row -> + new SourceChangeSnapshot( + row.get("change_id", UUID.class), + row.get("binding", byte[].class), + row.get("status", String.class), + row.get("requested_at", OffsetDateTime.class), + row.get("committed_at", OffsetDateTime.class), + row.get("aborted_at", OffsetDateTime.class), + abortReason(row.get("abort_reason", String.class)))) + .toList(); + } + + public SourceChangeSnapshot readSourceChange(SourceChange change) { + requireTransaction(); + Record row = readChange(change.changeId()); + requireChange(row, change); + return sourceChangeSnapshot(row); + } + + /** + * Non-locking exact inspection for callers that must preserve Account/envelope/V57 lock order. + */ + public SourceChangeSnapshot inspectSourceChange(SourceChange change) { + requireTransaction(); + Record row = + dsl.fetchOne("SELECT * FROM " + CHANGES + " WHERE change_id = ?", change.changeId()); + if (row == null) { + throw new IllegalArgumentException("Absent or changed immutable source mutation intent"); + } + requireChange(row, change); + return sourceChangeSnapshot(row); + } + + private SourceChangeSnapshot sourceChangeSnapshot(Record row) { + return new SourceChangeSnapshot( + row.get("change_id", UUID.class), + row.get("binding", byte[].class), + row.get("status", String.class), + row.get("requested_at", OffsetDateTime.class), + row.get("committed_at", OffsetDateTime.class), + row.get("aborted_at", OffsetDateTime.class), + abortReason(row.get("abort_reason", String.class))); + } + + private SourceChangeAbortReason abortReason(String value) { + return value == null ? null : SourceChangeAbortReason.valueOf(value); + } + + private void lockSources(List sources) { + for (SourceEvidence source : sources) { + dsl.execute( + "INSERT INTO account_draft_authorization_source_locks (source_key) VALUES (?) ON CONFLICT DO NOTHING", + source.key()); + dsl.fetchOne( + "SELECT source_key FROM account_draft_authorization_source_locks WHERE source_key = ? FOR UPDATE", + source.key()); + } + } + + private boolean hasWaitingChange(List sources) { + for (SourceEvidence source : sources) { + if (!dsl.fetch( + "SELECT c.change_id FROM " + + CHANGES + + " c JOIN " + + CHANGED + + " s ON s.change_id = c.change_id WHERE s.source_key = ? AND c.status = 'WAITING'", + source.key()) + .isEmpty()) { + return true; + } + } + return false; + } + + private List affectedOperations(List sources) { + return sources.stream() + .flatMap( + source -> + dsl + .fetch( + "SELECT operation_id FROM " + SOURCES + " WHERE source_key = ?", + source.key()) + .getValues("operation_id", UUID.class) + .stream()) + .distinct() + .sorted(Comparator.comparing(UUID::toString)) + .toList(); + } + + /** + * Commit order settles only after both exact definitive outcomes, including mixed failure. Revoke + * order requires both definitive aborts. Missing evidence always remains pending. + */ + private boolean allAffectedSettled(List sources) { + for (UUID operation : affectedOperations(sources)) { + Record row = readOperation(operation); + if (settlement(operation, Ordering.valueOf(row.get("ordering", String.class))) + == Settlement.PENDING) { + return false; + } + } + return true; + } + + private Settlement settlement(UUID operation, Ordering ordering) { + if (ordering == Ordering.RESERVED) { + return Settlement.PENDING; + } + List outcomes = + dsl + .fetch("SELECT outcome FROM " + READBACKS + " WHERE operation_id = ?", operation) + .getValues("outcome", String.class) + .stream() + .map(Outcome::valueOf) + .toList(); + // The owner CHECK and (operation_id, owner) primary key admit exactly these two owners. + if (outcomes.size() != 2) { + return Settlement.PENDING; + } + boolean bothAborted = outcomes.stream().allMatch(o -> o == Outcome.DEFINITIVELY_ABORTED); + if (ordering == Ordering.REVOKE_ORDER) { + return bothAborted ? Settlement.FAILED_NONPUBLICATION : Settlement.PENDING; + } + return outcomes.stream().allMatch(o -> o == Outcome.COMMITTED) + ? Settlement.COMMITTED + : Settlement.FAILED_NONPUBLICATION; + } + + private Record readOperation(UUID operation) { + return dsl.fetchOne( + "SELECT * FROM " + FENCES + " WHERE operation_id = ? FOR UPDATE", operation); + } + + private Record readChange(UUID change) { + return dsl.fetchOne("SELECT * FROM " + CHANGES + " WHERE change_id = ? FOR UPDATE", change); + } + + private Record requireExact(Record row, DraftAuthorizationFenceBinding binding) { + if (row == null + || !Arrays.equals(row.get("binding", byte[].class), binding.canonicalBytes()) + || !binding.requestId().equals(row.get("request_id", UUID.class)) + || !binding.commitId().equals(row.get("commit_id", UUID.class)) + || !binding.fenceId().equals(row.get("fence_id", UUID.class))) { + throw new IllegalArgumentException("Absent or changed immutable Draft operation"); + } + List sourceRows = + dsl + .fetch( + "SELECT source_key, source_evidence FROM " + SOURCES + " WHERE operation_id = ?", + binding.operationId()) + .stream() + .sorted(Comparator.comparing(record -> record.get("source_key", String.class))) + .toList(); + if (sourceRows.size() != binding.sources().size()) { + throw new IllegalStateException("Incomplete source participation"); + } + for (int i = 0; i < sourceRows.size(); i++) { + SourceEvidence source = binding.sources().get(i); + if (!source.key().equals(sourceRows.get(i).get("source_key", String.class)) + || !Arrays.equals( + source.canonicalBytes(), sourceRows.get(i).get("source_evidence", byte[].class))) { + throw new IllegalStateException("Source participation differs from exact binding"); + } + } + return row; + } + + private void requireChange(Record row, SourceChange change) { + if (row == null || !Arrays.equals(row.get("binding", byte[].class), change.canonicalBytes())) { + throw new IllegalArgumentException("Absent or changed immutable source mutation intent"); + } + List stored = + dsl + .fetch("SELECT source_key FROM " + CHANGED + " WHERE change_id = ?", change.changeId()) + .getValues("source_key", String.class) + .stream() + .sorted() + .toList(); + if (!stored.equals(change.sources().stream().map(SourceEvidence::key).toList())) { + throw new IllegalStateException("Incomplete source change participation"); + } + } + + private FenceSnapshot snapshot(Record row) { + return new FenceSnapshot( + Ordering.valueOf(row.get("ordering", String.class)), + row.get("binding", byte[].class), + row.get("reserved_at", OffsetDateTime.class), + row.get("ordered_at", OffsetDateTime.class)); + } + + private void requireTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException("Writable caller Account transaction required"); + } + dsl.connection( + connection -> { + if (connection.getAutoCommit() + || connection.isReadOnly() + || connection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) { + throw new IllegalStateException( + "Transaction-bound writable READ_COMMITTED connection required"); + } + }); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountLogoutRequestDigest.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountLogoutRequestDigest.java new file mode 100644 index 0000000000..029c6bf10f --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountLogoutRequestDigest.java @@ -0,0 +1,116 @@ +package net.firedevops.firemud.accountservice.dto; + +import java.io.ByteArrayOutputStream; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; +import java.util.Objects; +import java.util.UUID; + +/** Canonical, bounded request digests for the two Account token-logout operations. */ +public final class AccountLogoutRequestDigest { + private static final String DOMAIN = "requestDigest/v1"; + private static final HexFormat HEX = HexFormat.of(); + + private AccountLogoutRequestDigest() {} + + public static String tokenLogout(UUID subjectAccountId, String tokenProfile, String tokenHash) { + return digest(OperationKind.TOKEN_LOGOUT, subjectAccountId, tokenProfile, tokenHash); + } + + public static String accountLogoutAll( + UUID subjectAccountId, String tokenProfile, String presentedTokenHash) { + return digest( + OperationKind.ACCOUNT_LOGOUT_ALL, subjectAccountId, tokenProfile, presentedTokenHash); + } + + /** Validates the exact closed token-profile vocabulary accepted by logout request bindings. */ + public static void validateTokenProfile(String tokenProfile) { + if (!"control-ui".equals(tokenProfile) && !"player-bootstrap".equals(tokenProfile)) { + throw new IllegalArgumentException( + "Logout request token profile must be control-ui or player-bootstrap"); + } + } + + /** Validates a SHA-256 token identity rendered as lowercase hexadecimal without a prefix. */ + public static void validateTokenHash(String tokenHash) { + if (tokenHash == null || !tokenHash.matches("[0-9a-f]{64}")) { + throw new IllegalArgumentException("Logout request token hash must be lowercase SHA-256 hex"); + } + } + + public static String tokenLogoutPreimageHex( + UUID subjectAccountId, String tokenProfile, String tokenHash) { + validateBindings(subjectAccountId, tokenProfile, tokenHash); + return HEX.formatHex( + preimage(OperationKind.TOKEN_LOGOUT, subjectAccountId, tokenProfile, tokenHash)); + } + + public static String accountLogoutAllPreimageHex( + UUID subjectAccountId, String tokenProfile, String presentedTokenHash) { + validateBindings(subjectAccountId, tokenProfile, presentedTokenHash); + return HEX.formatHex( + preimage( + OperationKind.ACCOUNT_LOGOUT_ALL, subjectAccountId, tokenProfile, presentedTokenHash)); + } + + private static String digest( + OperationKind operationKind, UUID subjectAccountId, String tokenProfile, String tokenHash) { + validateBindings(subjectAccountId, tokenProfile, tokenHash); + Objects.requireNonNull(operationKind, "A closed logout operation kind is required"); + byte[] preimage = preimage(operationKind, subjectAccountId, tokenProfile, tokenHash); + try { + return HEX.formatHex(MessageDigest.getInstance("SHA-256").digest(preimage)); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + private static void validateBindings( + UUID subjectAccountId, String tokenProfile, String tokenHash) { + if (subjectAccountId == null || new UUID(0L, 0L).equals(subjectAccountId)) { + throw new IllegalArgumentException("A canonical non-nil Account UUID is required"); + } + validateTokenProfile(tokenProfile); + validateTokenHash(tokenHash); + } + + private static byte[] preimage( + OperationKind operationKind, UUID subjectAccountId, String tokenProfile, String tokenHash) { + String tokenIdentityField = + operationKind == OperationKind.ACCOUNT_LOGOUT_ALL ? "presentedTokenHash" : "tokenHash"; + ByteArrayOutputStream output = new ByteArrayOutputStream(256); + appendSegment(output, DOMAIN); + appendStringField(output, "operationKind", operationKind.wireValue); + appendStringField(output, "subjectAccountId", subjectAccountId.toString()); + appendStringField(output, "tokenProfile", tokenProfile); + appendStringField(output, tokenIdentityField, tokenHash); + return output.toByteArray(); + } + + private static void appendStringField(ByteArrayOutputStream output, String name, String value) { + appendSegment(output, name); + appendSegment(output, "string"); + output.write('1'); + appendSegment(output, value); + } + + private static void appendSegment(ByteArrayOutputStream output, String value) { + byte[] bytes = value.getBytes(StandardCharsets.UTF_8); + output.writeBytes(Integer.toString(bytes.length).getBytes(StandardCharsets.US_ASCII)); + output.write(':'); + output.writeBytes(bytes); + } + + private enum OperationKind { + TOKEN_LOGOUT("TOKEN_LOGOUT"), + ACCOUNT_LOGOUT_ALL("ACCOUNT_LOGOUT_ALL"); + + private final String wireValue; + + OperationKind(String wireValue) { + this.wireValue = wireValue; + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountSecurityStateMutationRequest.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountSecurityStateMutationRequest.java new file mode 100644 index 0000000000..bb5f164754 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountSecurityStateMutationRequest.java @@ -0,0 +1,173 @@ +package net.firedevops.firemud.accountservice.dto; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import net.firedevops.firemud.common.account.authority.AccountSecurityStateAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.AccountSecurityStateAuthorityEventV1Codec.AccountState; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; + +/** Immutable operation correlation only; this request does not establish caller authorization. */ +public record AccountSecurityStateMutationRequest( + UUID requestId, + UUID accountUuid, + byte[] callerProofBinding, + long expectedGeneration, + long expectedSourceVersion, + List mutationKinds, + AccountState desiredState) { + private static final ObjectMapper JSON = new ObjectMapper(); + private static final Set CALLER_FIELDS = + Set.of("schemaVersion", "actorAccountUuid", "ownerOperationId", "ownerEvidenceDigest"); + + public AccountSecurityStateMutationRequest { + requireUuid(requestId); + requireUuid(accountUuid); + if (expectedGeneration <= 0 || expectedSourceVersion <= 0) { + throw new IllegalArgumentException("Original positive source counters are required"); + } + callerProofBinding = canonicalCallerBinding(callerProofBinding); + mutationKinds = List.copyOf(Objects.requireNonNull(mutationKinds)); + Objects.requireNonNull(desiredState); + // The shared source codec owns the complete state and family vocabulary. + var validated = + AccountSecurityStateAuthorityEventV1Codec.seal( + eventPreimage(requestId, accountUuid, "1", "1", "1", mutationKinds, desiredState)); + desiredState = validated.accountState(); + mutationKinds = validated.mutationKinds(); + } + + @Override + public byte[] callerProofBinding() { + return callerProofBinding.clone(); + } + + @Override + public List mutationKinds() { + return List.copyOf(mutationKinds); + } + + public byte[] canonicalDesiredState() { + return canonicalState(desiredState); + } + + public static byte[] canonicalState(AccountState state) { + Objects.requireNonNull(state); + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(state)); + } catch (IOException exception) { + throw new IllegalArgumentException("Account state cannot be canonicalized", exception); + } + } + + public static AccountState parseCanonicalState(byte[] bytes) { + try { + String text = new String(Objects.requireNonNull(bytes), StandardCharsets.UTF_8); + JsonNode node = JSON.readTree(text); + var validated = + AccountSecurityStateAuthorityEventV1Codec.seal( + eventPreimage( + UUID.fromString("11111111-1111-4111-8111-111111111111"), + UUID.fromString("22222222-2222-4222-8222-222222222222"), + "1", + "1", + "1", + List.of("EMAIL_LOGIN_ELIGIBILITY_CHANGED"), + JSON.convertValue(node, new TypeReference>() {}))); + if (!Arrays.equals(bytes, canonicalState(validated.accountState()))) { + throw new IllegalArgumentException("Stored Account state is not canonical"); + } + return validated.accountState(); + } catch (IOException exception) { + throw new IllegalArgumentException("Stored Account state is malformed", exception); + } + } + + public static Map eventPreimage( + UUID requestId, + UUID accountUuid, + String generation, + String sourceVersion, + String sequence, + List mutationKinds, + Object state) { + String stream = "account:auth-authority:v1:account/" + accountUuid; + return Map.ofEntries( + Map.entry("schemaVersion", AccountSecurityStateAuthorityEventV1Codec.SCHEMA_VERSION), + Map.entry("eventType", AccountSecurityStateAuthorityEventV1Codec.EVENT_TYPE), + Map.entry("eventId", AccountSecurityStateAuthorityEventV1Codec.EVENT_ID_PREFIX + requestId), + Map.entry("requestId", requestId.toString()), + Map.entry("accountId", accountUuid.toString()), + Map.entry("sourceScope", "account/" + accountUuid), + Map.entry("outboxStreamKey", stream), + Map.entry("outboxSequence", sequence), + Map.entry("accountAuthorityGeneration", generation), + Map.entry("sourceVersion", sourceVersion), + Map.entry( + "accountSecurityCutoff", + Map.of( + "accountAuthorityGeneration", + generation, + "outboxStreamKey", + stream, + "outboxSequence", + sequence)), + Map.entry("mutationKinds", mutationKinds), + Map.entry("accountState", state)); + } + + private static byte[] canonicalCallerBinding(byte[] bytes) { + if (bytes == null || bytes.length == 0 || bytes.length > 16_384) { + throw new IllegalArgumentException("Bounded original caller/proof correlation is required"); + } + try { + String text = new String(bytes, StandardCharsets.UTF_8); + if (!Arrays.equals(bytes, Rfc8785CanonicalJson.canonicalizeUtf8(text))) { + throw new IllegalArgumentException("Caller/proof correlation must be canonical JSON"); + } + JsonNode node = JSON.readTree(text); + Set fields = new java.util.HashSet<>(); + node.fieldNames().forEachRemaining(fields::add); + if (!node.isObject() || !fields.equals(CALLER_FIELDS)) { + throw new IllegalArgumentException( + "Caller correlation must contain exactly its identity fields"); + } + if (!"account-security-state-caller-correlation/v1" + .equals(node.path("schemaVersion").textValue())) { + throw new IllegalArgumentException("Unsupported caller correlation version"); + } + for (String field : List.of("actorAccountUuid", "ownerOperationId")) { + JsonNode id = node.get(field); + if (!id.isTextual() + || !id.textValue() + .matches("[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}")) { + throw new IllegalArgumentException("Canonical correlation UUIDs are required"); + } + requireUuid(UUID.fromString(id.textValue())); + } + if (!node.get("ownerEvidenceDigest").isTextual() + || !node.get("ownerEvidenceDigest").textValue().matches("sha256:[0-9a-f]{64}")) { + throw new IllegalArgumentException( + "Original owner evidence digest correlation is required"); + } + return bytes.clone(); + } catch (IOException exception) { + throw new IllegalArgumentException("Caller/proof correlation is malformed", exception); + } + } + + private static void requireUuid(UUID uuid) { + if (uuid == null || uuid.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException( + "Canonical non-nil operation and Account UUIDs are required"); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountSecurityStateRequestDigest.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountSecurityStateRequestDigest.java new file mode 100644 index 0000000000..e779dddd2a --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountSecurityStateRequestDigest.java @@ -0,0 +1,51 @@ +package net.firedevops.firemud.accountservice.dto; + +import java.io.ByteArrayOutputStream; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; + +/** Exact versioned request/capture bytes; neither digest establishes caller authorization. */ +public final class AccountSecurityStateRequestDigest { + public static final String REQUEST_DOMAIN = "firemud/account/security-state/request/v1"; + + private AccountSecurityStateRequestDigest() {} + + public static byte[] requestBytes(AccountSecurityStateMutationRequest request) { + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + frame(bytes, REQUEST_DOMAIN); + frame(bytes, request.requestId().toString()); + frame(bytes, request.accountUuid().toString()); + frame(bytes, request.callerProofBinding()); + frame(bytes, Long.toString(request.expectedGeneration())); + frame(bytes, Long.toString(request.expectedSourceVersion())); + // Each kind has its own frame; cardinality is also an explicit frame. + frame(bytes, Integer.toString(request.mutationKinds().size())); + request.mutationKinds().forEach(kind -> frame(bytes, kind)); + frame(bytes, request.canonicalDesiredState()); + return bytes.toByteArray(); + } + + public static String digest(AccountSecurityStateMutationRequest request) { + return sha256(requestBytes(request)); + } + + public static String sha256(byte[] bytes) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + public static void frame(ByteArrayOutputStream output, String text) { + frame(output, text.getBytes(StandardCharsets.UTF_8)); + } + + public static void frame(ByteArrayOutputStream output, byte[] value) { + output.writeBytes(ByteBuffer.allocate(Integer.BYTES).putInt(value.length).array()); + output.writeBytes(value); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidenceRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidenceRepository.java index c6c2ef3588..f99cc66df0 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidenceRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidenceRepository.java @@ -7,6 +7,7 @@ import java.util.Objects; import java.util.Optional; import java.util.UUID; +import net.firedevops.firemud.accountservice.entity.Account; import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; import net.firedevops.firemud.accountservice.entity.AccountLoginAuthModes; import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; @@ -14,8 +15,14 @@ import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.IssuanceFence; import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeKind; import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeState; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Checkpoint; import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Event; import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.EventEvidence; +import net.firedevops.firemud.accountservice.service.AccountAuthoritySourceEventReadback; +import net.firedevops.firemud.accountservice.service.AccountAuthoritySourceEventReadback.RetainedEventEvidence; +import net.firedevops.firemud.accountservice.service.AccountAuthoritySourceReader.AccountSourceSnapshot; +import net.firedevops.firemud.accountservice.service.AccountGenerationProjection; +import net.firedevops.firemud.accountservice.service.IssuerGenerationProjection; import net.firedevops.firemud.common.account.authority.AccountAuthoritySourceEventV1Codec; import net.firedevops.firemud.common.account.authority.AccountAuthoritySourceEventV1Codec.AccountEvent; import net.firedevops.firemud.common.account.authority.AccountAuthoritySourceEventV1Codec.AccountPreimage; @@ -29,6 +36,7 @@ import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; /** * Owns explicit fresh source baselines and exact Account/issuer authority event append/readback. @@ -187,7 +195,203 @@ public IssuerAccountSourceSnapshot readCurrentIssuerAccountSources( || !account.issuanceFence().equals(snapshot.account().issuanceFence())) { throw new SourceEvidenceUnavailableException(); } - return new IssuerAccountSourceSnapshot(issuer, account, snapshot.issuanceFence()); + AccountAuthoritySourceEventReadback.LatestSourceSnapshot closedSource = + closedEventReadback() + .requireCurrentLatest( + readAccountIdentityForClosedReadback(accountUuid), snapshot.account()); + if (closedSource.outboxSequence() != account.checkpoint().sequence()) { + throw new SourceEvidenceUnavailableException(); + } + if (closedSource.outboxSequence() == 0L) { + if (closedSource.latestEvent().isPresent() + || account.checkpoint().sourceEventId().isPresent() + || account.checkpoint().sourceEventDigest().isPresent()) { + throw new SourceEvidenceUnavailableException(); + } + } else { + Event closedEvent = closedSource.latestEvent().orElseThrow(); + if (closedEvent.outboxSequence() != account.checkpoint().sequence() + || !closedEvent.eventId().equals(account.checkpoint().sourceEventId().orElseThrow()) + || !closedEvent + .eventDigest() + .equals(account.checkpoint().sourceEventDigest().orElseThrow())) { + throw new SourceEvidenceUnavailableException(); + } + } + AccountGenerationProjection accountProjection = + AccountGenerationProjection.fromSource( + new AccountSourceSnapshot( + accountUuid, + snapshot.account(), + account.checkpoint().outboxStreamKey(), + account.checkpoint().sequence(), + closedSource.latestEvent())); + return new IssuerAccountSourceSnapshot( + issuer, + account, + snapshot.issuanceFence(), + accountProjection, + IssuerGenerationProjection.fromSource( + new CanonicalIssuerSourceSnapshot( + issuer, + issuer.checkpoint().sequence() == 0L + ? Optional.empty() + : Optional.of( + outbox + .findEvent( + issuer.checkpoint().outboxStreamKey(), + issuer.checkpoint().sequence()) + .orElseThrow(SourceEvidenceUnavailableException::new))))); + } + + /** + * Prepares exactly one Account-local advance against the complete current source readback. This + * is not authorization or a committed receipt. The closed event, immutable operation receipt and + * source head must all complete in this same owner transaction; deferred SQL consistency guards + * reject an incomplete transaction. + */ + @Transactional(propagation = Propagation.MANDATORY) + public ScopeState prepareClosedAccountAdvance(UUID accountUuid, CurrentSourceEvidence expected) { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || accountUuid == null + || accountUuid.equals(new UUID(0L, 0L)) + || expected == null + || !AuthorityScope.account(accountUuid).equals(expected.scope()) + || expected.issuanceFence() == null) { + throw new SourceEvidenceUnavailableException(); + } + AuthorityScope scope = AuthorityScope.account(accountUuid); + ScopeState current = generations.read(scope); + CurrentSourceEvidence actual = readCurrentSource(scope, current); + if (!expected.equals(actual) || !expected.issuanceFence().equals(current.issuanceFence())) { + throw new SourceEvidenceUnavailableException(); + } + long nextGeneration = Math.addExact(current.generation(), 1L); + long nextSourceVersion = Math.addExact(current.sourceVersion(), 1L); + long nextFence = Math.addExact(current.issuanceFence().value(), 1L); + long nextFenceVersion = Math.addExact(current.issuanceFence().sourceVersion(), 1L); + ScopeState advanced = generations.advanceForSourceEvidence(current, current.issuanceFence()); + if (!scope.equals(advanced.scope()) + || advanced.generation() != nextGeneration + || advanced.sourceVersion() != nextSourceVersion + || advanced.issuanceFence() == null + || !accountUuid.equals(advanced.issuanceFence().accountId()) + || advanced.issuanceFence().value() != nextFence + || advanced.issuanceFence().sourceVersion() != nextFenceVersion) { + throw new SourceEvidenceUnavailableException(); + } + return advanced; + } + + /** + * Advances the canonical Account source head only after a closed operation's immutable owner + * receipt and exact outbox event have been stored in this same owner transaction. + */ + @Transactional(propagation = Propagation.MANDATORY) + public CurrentSourceEvidence advanceClosedAccountHead( + UUID accountUuid, ScopeState expected, ScopeState advanced, Event event) { + Objects.requireNonNull(accountUuid, "Account UUID is required"); + Objects.requireNonNull(expected, "expected Account source state is required"); + Objects.requireNonNull(advanced, "advanced Account source state is required"); + Objects.requireNonNull(event, "closed Account source event is required"); + AuthorityScope scope = AuthorityScope.account(accountUuid); + if (!scope.equals(expected.scope()) + || !scope.equals(advanced.scope()) + || expected.issuanceFence() == null + || advanced.issuanceFence() == null + || advanced.generation() != Math.addExact(expected.generation(), 1L) + || advanced.sourceVersion() != Math.addExact(expected.sourceVersion(), 1L) + || advanced.issuanceFence().value() != Math.addExact(expected.issuanceFence().value(), 1L) + || advanced.issuanceFence().sourceVersion() + != Math.addExact(expected.issuanceFence().sourceVersion(), 1L)) { + throw new SourceEvidenceUnavailableException(); + } + + // The typed producer has already appended the event, but source_records must still contain + // the exact old head. Read and authenticate that previous head while allowing only this one + // pending outbox append; a normal current-source read would correctly reject the transaction's + // temporarily advanced stream checkpoint. + CurrentSourceEvidence before = readPreviousSourceForClosedAppend(scope, expected, event); + long expectedSequence = Math.addExact(before.checkpoint().sequence(), 1L); + RetainedEventEvidence receiptEvidence = + closedEventReadback() + .requireRetainedEvent( + readAccountIdentityForClosedReadback(accountUuid), event, advanced); + if (!streamKey(scope).equals(event.outboxStreamKey()) + || event.outboxSequence() != expectedSequence + || advanced.generation() != receiptEvidence.accountAuthorityGeneration() + || advanced.sourceVersion() != receiptEvidence.sourceVersion() + || receiptEvidence.issuanceFence() != advanced.issuanceFence().value() + || receiptEvidence.issuanceFenceSourceVersion() + != advanced.issuanceFence().sourceVersion()) { + throw new SourceEvidenceUnavailableException(); + } + Event bySequence = + outbox + .findEvent(event.outboxStreamKey(), event.outboxSequence()) + .orElseThrow(SourceEvidenceUnavailableException::new); + Event byRequest = + outbox + .findEvent(event.outboxStreamKey(), event.requestId()) + .orElseThrow(SourceEvidenceUnavailableException::new); + if (!event.equals(bySequence) || !event.equals(byRequest)) { + throw new SourceEvidenceUnavailableException(); + } + Checkpoint checkpoint = + outbox + .readCheckpoint(event.outboxStreamKey()) + .orElseThrow(SourceEvidenceUnavailableException::new); + if (checkpoint.outboxSequence() != expectedSequence + || !checkpoint.sourceEventId().equals(event.eventId()) + || !checkpoint.sourceEventDigest().equals(event.eventDigest())) { + throw new SourceEvidenceUnavailableException(); + } + var typedCutoff = receiptEvidence.accountSecurityCutoff(); + updateSourceHead( + before, + event, + new AccountSecurityCutoff( + typedCutoff.accountAuthorityGeneration(), + typedCutoff.outboxStreamKey(), + typedCutoff.outboxSequence()), + advanced, + advanced.issuanceFence()); + CurrentSourceEvidence current = readCurrentSource(scope, advanced); + if (current.checkpoint().sequence() != event.outboxSequence() + || !current.checkpoint().sourceEventId().orElseThrow().equals(event.eventId()) + || !current.checkpoint().sourceEventDigest().orElseThrow().equals(event.eventDigest())) { + throw new SourceEvidenceUnavailableException(); + } + Account latestAccount = readAccountIdentityForClosedReadback(accountUuid); + AccountAuthoritySourceEventReadback.LatestSourceSnapshot latest = + closedEventReadback().requireCurrentLatest(latestAccount, advanced); + if (latest.outboxSequence() != event.outboxSequence() + || latest.latestEvent().isEmpty() + || !event.equals(latest.latestEvent().orElseThrow())) { + throw new SourceEvidenceUnavailableException(); + } + return current; + } + + /** Returns the actual current issuer source and its retained terminal event without mutation. */ + @Transactional(propagation = Propagation.MANDATORY) + public CanonicalIssuerSourceSnapshot readCurrentCanonicalIssuerSource(String exactIssuerId) { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new SourceEvidenceUnavailableException(); + } + AuthorityScope scope = AuthorityScope.issuer(exactIssuerId); + CurrentSourceEvidence current = readCurrentSource(scope, generations.read(scope)); + Optional latest = + current.checkpoint().sequence() == 0L + ? Optional.empty() + : Optional.of( + outbox + .findEvent( + current.checkpoint().outboxStreamKey(), current.checkpoint().sequence()) + .orElseThrow(SourceEvidenceUnavailableException::new)); + return new CanonicalIssuerSourceSnapshot(current, latest); } /** Records an explicit issuer-wide mutation with exact event readback and no Account cutoff. */ @@ -279,13 +483,42 @@ private void insertFreshBaseline( } private CurrentSourceEvidence readCurrentSource(AuthorityScope scope, ScopeState authority) { - return readCurrentSource(scope, authority, Optional.empty()); + return readCurrentSource(scope, authority, Optional.empty(), false); } private CurrentSourceEvidence readCurrentSource( AuthorityScope scope, ScopeState authority, Optional expectedPreUpdateAccountState) { + return readCurrentSource(scope, authority, expectedPreUpdateAccountState, false); + } + + private CurrentSourceEvidence readPreviousSourceForClosedAppend( + AuthorityScope scope, ScopeState authority, Event pendingEvent) { + CurrentSourceEvidence before = readCurrentSource(scope, authority, Optional.empty(), true); + if (!streamKey(scope).equals(pendingEvent.outboxStreamKey()) + || pendingEvent.outboxSequence() != Math.addExact(before.checkpoint().sequence(), 1L)) { + throw new SourceEvidenceUnavailableException(); + } + Event exactPending = + outbox + .findEvent(pendingEvent.outboxStreamKey(), pendingEvent.outboxSequence()) + .orElseThrow(SourceEvidenceUnavailableException::new); + Event requestMatch = + outbox + .findEvent(pendingEvent.outboxStreamKey(), pendingEvent.requestId()) + .orElseThrow(SourceEvidenceUnavailableException::new); + if (!pendingEvent.equals(exactPending) || !pendingEvent.equals(requestMatch)) { + throw new SourceEvidenceUnavailableException(); + } + return before; + } + + private CurrentSourceEvidence readCurrentSource( + AuthorityScope scope, + ScopeState authority, + Optional expectedPreUpdateAccountState, + boolean allowOnePendingAppend) { String key = streamKey(scope); Record source = dsl.fetchOne( @@ -329,12 +562,25 @@ private CurrentSourceEvidence readCurrentSource( "SELECT last_sequence FROM account_authority_outbox_streams " + "WHERE outbox_stream_key = ? FOR SHARE", key); - if (stream == null || nonnegative(stream, "last_sequence") != sequence) { + long expectedStreamSequence = allowOnePendingAppend ? Math.addExact(sequence, 1L) : sequence; + if (stream == null || nonnegative(stream, "last_sequence") != expectedStreamSequence) { throw new SourceEvidenceUnavailableException(); } + if (scope.kind() == ScopeKind.ACCOUNT) { + Record eventCountRow = + dsl.fetchOne( + "SELECT count(*) AS event_count FROM account_authority_outbox_events " + + "WHERE outbox_stream_key = ?", + key); + Long eventCount = eventCountRow == null ? null : eventCountRow.get("event_count", Long.class); + if (eventCount == null || eventCount != expectedStreamSequence) { + throw new SourceEvidenceUnavailableException(); + } + } + SourceCheckpoint checkpoint; - Optional cutoff = Optional.empty(); - SourceEvent latest = null; + Optional cutoff = Optional.empty(); + VerifiedSourceHistory history = null; if (sequence == 0L) { if (source.get("last_event_id", String.class) != null || source.get("last_event_digest", String.class) != null @@ -347,17 +593,27 @@ private CurrentSourceEvidence readCurrentSource( } checkpoint = new SourceCheckpoint(key, 0L, Optional.empty(), Optional.empty()); } else { - latest = verifyLatestEvent(scope, key, sequence, authority, fence); - if (!latest.eventId().equals(source.get("last_event_id", String.class)) - || !latest.eventDigest().equals(source.get("last_event_digest", String.class))) { + if (scope.kind() == ScopeKind.ISSUER) { + history = verifyLatestEvent(scope, key, sequence, authority, fence); + } else { + history = verifyEventHistory(scope, key, sequence, authority, fence); + } + Event latestEvent = history.latestEvent(); + if (!latestEvent.eventId().equals(source.get("last_event_id", String.class)) + || !latestEvent.eventDigest().equals(source.get("last_event_digest", String.class))) { throw new SourceEvidenceUnavailableException(); } checkpoint = new SourceCheckpoint( - key, sequence, Optional.of(latest.eventId()), Optional.of(latest.eventDigest())); + key, + sequence, + Optional.of(latestEvent.eventId()), + Optional.of(latestEvent.eventDigest())); if (scope.kind() == ScopeKind.ACCOUNT) { - AccountEvent accountEvent = (AccountEvent) latest; - AccountSecurityCutoff exactCutoff = accountEvent.accountSecurityCutoff(); + AccountSecurityCutoff exactCutoff = + history + .accountSecurityCutoff() + .orElseThrow(() -> new SourceEvidenceUnavailableException()); if (positive(source, "cutoff_generation") != currentGeneration || !key.equals(source.get("cutoff_stream_key", String.class)) || positive(source, "cutoff_sequence") != sequence @@ -375,7 +631,8 @@ private CurrentSourceEvidence readCurrentSource( } if (scope.kind() == ScopeKind.ACCOUNT) { requireAccountSourceIdentity(source, scope); - if (latest instanceof AccountEvent accountEvent) { + if (history != null && history.latestLegacyAccountEvent().isPresent()) { + AccountEvent accountEvent = history.latestLegacyAccountEvent().orElseThrow(); AccountState expectedAccountState = expectedPreUpdateAccountState.orElseGet(() -> readAccountState(scope.accountId())); if (!accountEvent.accountState().equals(expectedAccountState)) { @@ -397,7 +654,7 @@ private CurrentSourceEvidence readCurrentSource( source.get("account_repository_insert_transaction_id", Long.class)); } - private SourceEvent verifyLatestEvent( + private VerifiedSourceHistory verifyLatestEvent( AuthorityScope scope, String streamKey, long sequence, @@ -451,7 +708,103 @@ private SourceEvent verifyLatestEvent( || fence.sourceVersion() != sequence + 1L))) { throw new SourceEvidenceUnavailableException(); } - return latest; + return new VerifiedSourceHistory(stored, Optional.empty(), Optional.empty()); + } + + private VerifiedSourceHistory verifyEventHistory( + AuthorityScope scope, + String streamKey, + long sequence, + ScopeState authority, + IssuanceFence fence) { + Event latest = null; + AccountEvent latestLegacyAccountEvent = null; + AccountSecurityCutoff latestCutoff = null; + Account sourceAccount = + scope.kind() == ScopeKind.ACCOUNT + ? readAccountIdentityForClosedReadback(scope.accountId()) + : null; + for (long current = 1L; current <= sequence; current++) { + Event stored = + outbox + .findEvent(streamKey, current) + .orElseThrow(() -> new SourceEvidenceUnavailableException()); + SourceEvent event = null; + try { + event = + AccountAuthoritySourceEventV1Codec.verify( + new String(stored.payload(), StandardCharsets.UTF_8)); + } catch (RuntimeException notLegacyEvent) { + // Closed RESET/LOGOUT/security events are verified by their operation-specific receipts + // below. Generic source history remains readable but is not accepted as current authority. + } + if (event != null) { + if (!stored.eventId().equals(event.eventId()) + || !stored.requestId().equals(event.requestId()) + || !stored.outboxStreamKey().equals(event.outboxStreamKey()) + || stored.outboxSequence() != Long.parseLong(event.outboxSequence()) + || !stored.eventDigest().equals(event.eventDigest()) + || (scope.kind() == ScopeKind.ISSUER && !(event instanceof IssuerEvent)) + || (scope.kind() == ScopeKind.ACCOUNT && !(event instanceof AccountEvent))) { + throw new SourceEvidenceUnavailableException(); + } + if (event instanceof IssuerEvent issuer + && (!issuer.issuerId().equals(scope.issuerId()) + || Long.parseLong(issuer.issuerAuthGeneration()) != current + 1L + || Long.parseLong(issuer.sourceVersion()) != current + 1L)) { + throw new SourceEvidenceUnavailableException(); + } + if (event instanceof AccountEvent account + && (!account.accountId().equals(scope.accountId().toString()) + || Long.parseLong(account.accountAuthorityGeneration()) != current + 1L + || Long.parseLong(account.sourceVersion()) != current + 1L + || Long.parseLong(account.issuanceFence()) != current + 1L + || Long.parseLong(account.issuanceFenceSourceVersion()) != current + 1L)) { + throw new SourceEvidenceUnavailableException(); + } + latestLegacyAccountEvent = event instanceof AccountEvent account ? account : null; + latestCutoff = + event instanceof AccountEvent account ? account.accountSecurityCutoff() : null; + } else if (scope.kind() == ScopeKind.ACCOUNT) { + final RetainedEventEvidence receiptEvidence; + try { + receiptEvidence = + closedEventReadback().requireRetainedEvent(sourceAccount, stored, authority); + } catch (RuntimeException missingOrInvalidReceipt) { + throw new SourceEvidenceUnavailableException(); + } + if (!streamKey.equals(receiptEvidence.outboxStreamKey()) + || receiptEvidence.outboxSequence() != current + || receiptEvidence.accountAuthorityGeneration() != current + 1L + || receiptEvidence.sourceVersion() != current + 1L + || receiptEvidence.issuanceFence() != current + 1L + || receiptEvidence.issuanceFenceSourceVersion() != current + 1L) { + throw new SourceEvidenceUnavailableException(); + } + var typedCutoff = receiptEvidence.accountSecurityCutoff(); + latestCutoff = + new AccountSecurityCutoff( + typedCutoff.accountAuthorityGeneration(), + typedCutoff.outboxStreamKey(), + typedCutoff.outboxSequence()); + latestLegacyAccountEvent = null; + } else { + throw new SourceEvidenceUnavailableException(); + } + latest = stored; + } + if (latest == null + || latest.outboxSequence() != sequence + || authority.generation() != sequence + 1L + || authority.sourceVersion() != sequence + 1L + || (scope.kind() == ScopeKind.ACCOUNT + && (fence == null + || fence.value() != sequence + 1L + || fence.sourceVersion() != sequence + 1L))) { + throw new SourceEvidenceUnavailableException(); + } + return new VerifiedSourceHistory( + latest, Optional.ofNullable(latestLegacyAccountEvent), Optional.ofNullable(latestCutoff)); } private void updateSourceHead( @@ -461,6 +814,40 @@ private void updateSourceHead( IssuanceFence advancedFence) { AccountSecurityCutoff cutoff = event instanceof AccountEvent account ? account.accountSecurityCutoff() : null; + updateSourceHead( + before, + event.outboxSequence(), + event.eventId(), + event.eventDigest(), + cutoff, + advanced, + advancedFence); + } + + private void updateSourceHead( + CurrentSourceEvidence before, + Event event, + AccountSecurityCutoff cutoff, + ScopeState advanced, + IssuanceFence advancedFence) { + updateSourceHead( + before, + Long.toString(event.outboxSequence()), + event.eventId(), + event.eventDigest(), + cutoff, + advanced, + advancedFence); + } + + private void updateSourceHead( + CurrentSourceEvidence before, + String sequenceText, + String eventId, + String eventDigest, + AccountSecurityCutoff cutoff, + ScopeState advanced, + IssuanceFence advancedFence) { Record changed = dsl.fetchOne( "UPDATE " @@ -478,9 +865,9 @@ private void updateSourceHead( advanced.sourceVersion(), advancedFence == null ? null : advancedFence.value(), advancedFence == null ? null : advancedFence.sourceVersion(), - Long.parseLong(event.outboxSequence()), - event.eventId(), - event.eventDigest(), + Long.parseLong(sequenceText), + eventId, + eventDigest, cutoff == null ? null : Long.parseLong(cutoff.accountAuthorityGeneration()), cutoff == null ? null : cutoff.outboxStreamKey(), cutoff == null ? null : Long.parseLong(cutoff.outboxSequence()), @@ -620,6 +1007,34 @@ private AccountState readAccountState(UUID accountUuid) { return accountState(account); } + private Account readAccountIdentityForClosedReadback(UUID accountUuid) { + Record row = + dsl.fetchOne( + "SELECT id, account_uuid, account_uuid_provenance, account_uuid_source_numeric_id, " + + "password_hash FROM accounts WHERE account_uuid = ? FOR SHARE", + accountUuid); + if (row == null) throw new SourceEvidenceUnavailableException(); + Account account = new Account(); + account.setId(positive(row, "id")); + account.setAccountUuid(row.get("account_uuid", UUID.class)); + account.setAccountUuidProvenance( + AccountIdentityProvenance.fromStorageValue( + row.get("account_uuid_provenance", String.class))); + account.setAccountUuidSourceNumericId(positive(row, "account_uuid_source_numeric_id")); + account.setPasswordHash(row.get("password_hash", String.class)); + return account; + } + + private AccountAuthoritySourceEventReadback closedEventReadback() { + // Construct at use, not in the repository constructor: the security-state storage owner + // itself depends on this source owner. Every invocation still requires every exact receipt. + return new AccountAuthoritySourceEventReadback( + outbox, + new AccountPasswordResetOperationRepository(dsl), + new AccountLogoutAllOperationRepository(dsl), + new AccountSecurityStateOperationRepository(dsl)); + } + private void requireAccountReadback( UUID accountUuid, long accountId, AccountRepository.AccountAuthorityState expected) { Record account = @@ -792,6 +1207,17 @@ public record SourceCheckpoint( } } + private record VerifiedSourceHistory( + Event latestEvent, + Optional latestLegacyAccountEvent, + Optional accountSecurityCutoff) { + private VerifiedSourceHistory { + Objects.requireNonNull(latestEvent); + Objects.requireNonNull(latestLegacyAccountEvent); + Objects.requireNonNull(accountSecurityCutoff); + } + } + public record CurrentSourceEvidence( AuthorityScope scope, long generation, @@ -864,8 +1290,61 @@ public record CurrentSourceEvidence( } } + public record CanonicalIssuerSourceSnapshot( + CurrentSourceEvidence source, Optional latestEvent) { + public CanonicalIssuerSourceSnapshot { + Objects.requireNonNull(source); + Objects.requireNonNull(latestEvent); + if (source.scope().kind() != ScopeKind.ISSUER + || (source.checkpoint().sequence() == 0L) != latestEvent.isEmpty()) { + throw new SourceEvidenceUnavailableException(); + } + } + } + public record IssuerAccountSourceSnapshot( - CurrentSourceEvidence issuer, CurrentSourceEvidence account, IssuanceFence issuanceFence) { + CurrentSourceEvidence issuer, + CurrentSourceEvidence account, + IssuanceFence issuanceFence, + AccountGenerationProjection canonicalAccountProjection, + IssuerGenerationProjection canonicalIssuerProjection) { + public IssuerAccountSourceSnapshot( + CurrentSourceEvidence issuer, + CurrentSourceEvidence account, + IssuanceFence issuanceFence, + AccountGenerationProjection canonicalAccountProjection) { + this( + issuer, + account, + issuanceFence, + canonicalAccountProjection, + issuer != null && issuer.checkpoint().sequence() == 0L + ? IssuerGenerationProjection.fromSource(issuer) + : null); + } + + /** + * Preserves lightweight source-state fixtures while refusing to invent advanced event bytes. + * Production snapshots are created by {@link #readCurrentIssuerAccountSources} with the exact + * receipt-verified latest event from that same composite owner read. + */ + public IssuerAccountSourceSnapshot( + CurrentSourceEvidence issuer, CurrentSourceEvidence account, IssuanceFence issuanceFence) { + this( + issuer, + account, + issuanceFence, + account != null && account.checkpoint().sequence() == 0L + ? new AccountGenerationProjection( + account.scope().accountId().toString(), + Long.toString(account.generation()), + Long.toString(account.sourceVersion()), + account.checkpoint().outboxStreamKey(), + "0", + Optional.empty()) + : null); + } + public IssuerAccountSourceSnapshot { Objects.requireNonNull(issuer); Objects.requireNonNull(account); @@ -876,6 +1355,44 @@ public record IssuerAccountSourceSnapshot( || !account.issuanceFence().equals(issuanceFence)) { throw new IllegalArgumentException("Issuer/Account source snapshot scope is invalid"); } + if (canonicalAccountProjection != null + && (!account.scope().accountId().toString().equals(canonicalAccountProjection.accountId()) + || !Long.toString(account.generation()) + .equals(canonicalAccountProjection.accountAuthorityGeneration()) + || !Long.toString(account.sourceVersion()) + .equals(canonicalAccountProjection.sourceVersion()) + || !account + .checkpoint() + .outboxStreamKey() + .equals(canonicalAccountProjection.outboxStreamKey()) + || !Long.toString(account.checkpoint().sequence()) + .equals(canonicalAccountProjection.outboxSequence()))) { + throw new IllegalArgumentException( + "Canonical Account source projection differs from its snapshot"); + } + if (canonicalIssuerProjection != null + && (!issuer.scope().issuerId().equals(canonicalIssuerProjection.issuerId()) + || !Long.toString(issuer.generation()) + .equals(canonicalIssuerProjection.issuerAuthGeneration()) + || !Long.toString(issuer.sourceVersion()) + .equals(canonicalIssuerProjection.sourceVersion()) + || !issuer + .checkpoint() + .outboxStreamKey() + .equals(canonicalIssuerProjection.outboxStreamKey()) + || !Long.toString(issuer.checkpoint().sequence()) + .equals(canonicalIssuerProjection.lastAppliedSourceOutboxSequence()) + || !issuer + .checkpoint() + .sourceEventId() + .equals(canonicalIssuerProjection.lastAppliedSourceEventId()) + || !issuer + .checkpoint() + .sourceEventDigest() + .equals(canonicalIssuerProjection.lastAppliedSourceEventDigest()))) { + throw new IllegalArgumentException( + "Canonical issuer source projection differs from its snapshot"); + } } } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountLogoutAllOperationRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountLogoutAllOperationRepository.java new file mode 100644 index 0000000000..0ce98e77e2 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountLogoutAllOperationRepository.java @@ -0,0 +1,321 @@ +package net.firedevops.firemud.accountservice.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.HexFormat; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.AccountLogoutRequestDigest; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.IssuanceFence; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeState; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Stores immutable source and lifecycle-result evidence for one Account logout-all operation. */ +@Repository +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Injected DSLContext is an internal Spring collaborator.") +public class AccountLogoutAllOperationRepository { + private static final String TABLE = "account_logout_all_operation_receipts"; + private static final String EVENT_ID_PREFIX = "account-logout-all-event-v1:"; + private static final String LIFECYCLE_RESULT = "LOGOUT_ALL_COMMITTED"; + private static final String SELECT_COLUMNS = + "request_id, account_id, account_uuid, operation_kind, request_digest_version, " + + "request_digest, presented_token_hash, token_profile, outbox_stream_key, outbox_sequence, " + + "event_id, event_digest, account_authority_generation, account_source_version, " + + "issuance_fence, issuance_fence_source_version, lifecycle_result"; + private static final HexFormat HEX = HexFormat.of(); + + private final DSLContext dsl; + + public AccountLogoutAllOperationRepository(DSLContext dsl) { + this.dsl = dsl; + } + + /** Exact request lookup; callers compare every immutable request binding before recovery. */ + @Transactional(propagation = Propagation.MANDATORY) + public Optional findByRequestId(UUID requestId) { + requireOwnerTransaction(); + requireRequestId(requestId); + Record row = + dsl.fetchOne( + "SELECT " + SELECT_COLUMNS + " FROM " + TABLE + " WHERE request_id = ?", requestId); + return Optional.ofNullable(row == null ? null : toReceipt(row)); + } + + /** + * Token identity lookup prevents an old presented token from being rebound to another request. + */ + @Transactional(propagation = Propagation.MANDATORY) + public Optional findByPresentedTokenHash(String tokenHash) { + requireOwnerTransaction(); + byte[] hash = decodeDigest(tokenHash, "presented token hash"); + Record row = + dsl.fetchOne( + "SELECT " + SELECT_COLUMNS + " FROM " + TABLE + " WHERE presented_token_hash = ?", + hash); + return Optional.ofNullable(row == null ? null : toReceipt(row)); + } + + /** Inserts the one immutable lifecycle receipt for the source event. */ + @Transactional(propagation = Propagation.MANDATORY) + public LogoutAllReceipt insert(LogoutAllReceipt receipt) { + requireOwnerTransaction(); + validateReceipt(receipt); + int inserted = + dsl.execute( + "INSERT INTO " + + TABLE + + " (request_id, account_id, account_uuid, operation_kind, " + + "request_digest_version, request_digest, presented_token_hash, token_profile, " + + "outbox_stream_key, outbox_sequence, event_id, event_digest, " + + "account_authority_generation, account_source_version, issuance_fence, " + + "issuance_fence_source_version, lifecycle_result) " + + "VALUES (?, ?, ?, 'ACCOUNT_LOGOUT_ALL', 1, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'LOGOUT_ALL_COMMITTED')", + receipt.requestId(), + receipt.accountId(), + receipt.accountUuid(), + decodeDigest(receipt.requestDigest(), "request digest"), + decodeDigest(receipt.presentedTokenHash(), "presented token hash"), + receipt.tokenProfile(), + receipt.outboxStreamKey(), + receipt.outboxSequence(), + receipt.eventId(), + receipt.eventDigest(), + receipt.accountAuthorityGeneration(), + receipt.accountSourceVersion(), + receipt.issuanceFence(), + receipt.issuanceFenceSourceVersion()); + if (inserted != 1) { + throw new IllegalStateException("Logout-all operation receipt was not inserted"); + } + return receipt; + } + + private LogoutAllReceipt toReceipt(Record row) { + return new LogoutAllReceipt( + requiredUuid(row.get("request_id", UUID.class), "request ID"), + requiredPositive(row.get("account_id", Long.class), "Account association"), + requiredUuid(row.get("account_uuid", UUID.class), "Account UUID"), + requireText(row.get("operation_kind", String.class), "operation kind"), + requiredPositive(row.get("request_digest_version", Integer.class), "digest version"), + encodeDigest(row.get("request_digest", byte[].class), "request digest"), + encodeDigest(row.get("presented_token_hash", byte[].class), "presented token hash"), + requireText(row.get("token_profile", String.class), "token profile"), + requireText(row.get("outbox_stream_key", String.class), "outbox stream key"), + requiredPositive(row.get("outbox_sequence", Long.class), "outbox sequence"), + requireText(row.get("event_id", String.class), "event ID"), + requireText(row.get("event_digest", String.class), "event digest"), + requiredPositive( + row.get("account_authority_generation", Long.class), "Account authority generation"), + requiredPositive(row.get("account_source_version", Long.class), "Account source version"), + requiredPositive(row.get("issuance_fence", Long.class), "issuance fence"), + requiredPositive( + row.get("issuance_fence_source_version", Long.class), "issuance-fence source version"), + requireText(row.get("lifecycle_result", String.class), "lifecycle result")); + } + + private static void validateReceipt(LogoutAllReceipt receipt) { + Objects.requireNonNull(receipt, "logout-all receipt is required"); + requireRequestId(receipt.requestId()); + decodeDigest(receipt.requestDigest(), "request digest"); + decodeDigest(receipt.presentedTokenHash(), "presented token hash"); + AccountLogoutRequestDigest.validateTokenProfile(receipt.tokenProfile()); + if (receipt.accountId() <= 0L + || receipt.accountUuid() == null + || isNil(receipt.accountUuid()) + || receipt.requestDigestVersion() != 1 + || !AccountLogoutRequestDigest.accountLogoutAll( + receipt.accountUuid(), receipt.tokenProfile(), receipt.presentedTokenHash()) + .equals(receipt.requestDigest()) + || receipt.outboxSequence() <= 0L + || receipt.accountAuthorityGeneration() <= 0L + || receipt.accountSourceVersion() <= 0L + || receipt.issuanceFence() <= 0L + || receipt.issuanceFenceSourceVersion() <= 0L + || !accountStreamKey(receipt.accountUuid()).equals(receipt.outboxStreamKey()) + || !expectedEventId(receipt.requestId()).equals(receipt.eventId()) + || receipt.eventDigest() == null + || !receipt.eventDigest().matches("sha256:[0-9a-f]{64}") + || !LIFECYCLE_RESULT.equals(receipt.lifecycleResult())) { + throw new IllegalArgumentException("Logout-all operation receipt is malformed"); + } + requireBoundedText(receipt.operationKind(), "operation kind", 32); + if (!"ACCOUNT_LOGOUT_ALL".equals(receipt.operationKind())) { + throw new IllegalArgumentException("Logout-all operation kind is invalid"); + } + } + + private static void requireOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Logout-all operation storage requires an active Account transaction"); + } + } + + private static UUID requiredUuid(UUID value, String field) { + if (value == null || isNil(value)) { + throw new IllegalStateException("Logout-all receipt " + field + " is missing or invalid"); + } + return value; + } + + private static long requiredPositive(Long value, String field) { + if (value == null || value <= 0L) { + throw new IllegalStateException("Logout-all receipt " + field + " is missing or invalid"); + } + return value; + } + + private static int requiredPositive(Integer value, String field) { + if (value == null || value <= 0) { + throw new IllegalStateException("Logout-all receipt " + field + " is missing or invalid"); + } + return value; + } + + private static String requireText(String value, String field) { + if (value == null || value.isBlank()) { + throw new IllegalStateException("Logout-all receipt " + field + " is missing or invalid"); + } + return value; + } + + private static void requireBoundedText(String value, String field, int maximumLength) { + if (value == null || value.isBlank() || value.length() > maximumLength) { + throw new IllegalArgumentException( + "Logout-all receipt " + field + " must contain 1 to " + maximumLength + " characters"); + } + } + + private static void requireRequestId(UUID requestId) { + if (requestId == null || isNil(requestId)) { + throw new IllegalArgumentException("A canonical non-nil logout-all request UUID is required"); + } + } + + private static byte[] decodeDigest(String value, String field) { + if (value == null || !value.matches("[0-9a-f]{64}")) { + throw new IllegalArgumentException("Logout-all receipt " + field + " is malformed"); + } + return HEX.parseHex(value); + } + + private static String encodeDigest(byte[] value, String field) { + if (value == null || value.length != 32) { + throw new IllegalStateException("Logout-all receipt " + field + " is missing or invalid"); + } + return HEX.formatHex(value); + } + + private static String accountStreamKey(UUID accountUuid) { + return "account:auth-authority:v1:account/" + accountUuid; + } + + private static String expectedEventId(UUID requestId) { + return EVENT_ID_PREFIX + requestId; + } + + private static boolean isNil(UUID value) { + return new UUID(0L, 0L).equals(value); + } + + /** Immutable committed request binding, source checkpoint and lifecycle-only result. */ + public record LogoutAllReceipt( + UUID requestId, + long accountId, + UUID accountUuid, + String operationKind, + int requestDigestVersion, + String requestDigest, + String presentedTokenHash, + String tokenProfile, + String outboxStreamKey, + long outboxSequence, + String eventId, + String eventDigest, + long accountAuthorityGeneration, + long accountSourceVersion, + long issuanceFence, + long issuanceFenceSourceVersion, + String lifecycleResult) { + public LogoutAllReceipt { + requireRequestId(requestId); + decodeDigest(requestDigest, "request digest"); + decodeDigest(presentedTokenHash, "presented token hash"); + AccountLogoutRequestDigest.validateTokenProfile(tokenProfile); + if (accountId <= 0L + || accountUuid == null + || isNil(accountUuid) + || requestDigestVersion != 1 + || !AccountLogoutRequestDigest.accountLogoutAll( + accountUuid, tokenProfile, presentedTokenHash) + .equals(requestDigest) + || outboxSequence <= 0L + || accountAuthorityGeneration <= 0L + || accountSourceVersion <= 0L + || issuanceFence <= 0L + || issuanceFenceSourceVersion <= 0L + || !accountStreamKey(accountUuid).equals(outboxStreamKey) + || !expectedEventId(requestId).equals(eventId) + || eventDigest == null + || !eventDigest.matches("sha256:[0-9a-f]{64}") + || !LIFECYCLE_RESULT.equals(lifecycleResult)) { + throw new IllegalArgumentException("Logout-all operation receipt is malformed"); + } + requireBoundedText(operationKind, "operation kind", 32); + if (!"ACCOUNT_LOGOUT_ALL".equals(operationKind)) { + throw new IllegalArgumentException("Logout-all operation kind is invalid"); + } + } + + public static LogoutAllReceipt committed( + UUID requestId, + long accountId, + UUID accountUuid, + String requestDigest, + String presentedTokenHash, + String tokenProfile, + String outboxStreamKey, + long outboxSequence, + String eventId, + String eventDigest, + ScopeState accountAuthority, + IssuanceFence issuanceFence) { + if (accountAuthority == null + || issuanceFence == null + || accountAuthority.issuanceFence() == null + || !issuanceFence.equals(accountAuthority.issuanceFence())) { + throw new IllegalArgumentException( + "Committed logout-all authority and issuance fence must match exactly"); + } + return new LogoutAllReceipt( + requestId, + accountId, + accountUuid, + "ACCOUNT_LOGOUT_ALL", + 1, + requestDigest, + presentedTokenHash, + tokenProfile, + outboxStreamKey, + outboxSequence, + eventId, + eventDigest, + accountAuthority.generation(), + accountAuthority.sourceVersion(), + issuanceFence.value(), + issuanceFence.sourceVersion(), + LIFECYCLE_RESULT); + } + + public IssuanceFence issuanceFenceEvidence() { + return new IssuanceFence(accountUuid, issuanceFence, issuanceFenceSourceVersion); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepository.java new file mode 100644 index 0000000000..700668e747 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepository.java @@ -0,0 +1,316 @@ +package net.firedevops.firemud.accountservice.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.HexFormat; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.IssuanceFence; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeState; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Stores immutable proof for one Account-owned password-reset source commit. */ +@Repository +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Injected DSLContext is an internal Spring collaborator.") +public class AccountPasswordResetOperationRepository { + private static final String TABLE = "account_password_reset_operation_receipts"; + private static final String REQUEST_ID_PREFIX = "account-password-reset-request-v1:"; + private static final String EVENT_ID_PREFIX = "account-password-reset-event-v1:"; + private static final String SELECT_COLUMNS = + "token_hash, account_id, account_uuid, operation_kind, request_id, " + + "request_digest_version, request_digest, token_expires_at, " + + "password_verifier_digest, outbox_stream_key, outbox_sequence, event_id, " + + "event_digest, account_authority_generation, account_source_version, " + + "issuance_fence, issuance_fence_source_version"; + private static final HexFormat HEX = HexFormat.of(); + + private final DSLContext dsl; + + public AccountPasswordResetOperationRepository(DSLContext dsl) { + this.dsl = dsl; + } + + /** Read-only lookup by the SHA-256 identity of the token, including after token consumption. */ + @Transactional(propagation = Propagation.MANDATORY) + public Optional findByTokenHash(String tokenHash) { + requireOwnerTransaction(); + byte[] tokenHashBytes = decodeDigest(tokenHash, "token hash"); + Record row = + dsl.fetchOne( + "SELECT " + SELECT_COLUMNS + " FROM " + TABLE + " WHERE token_hash = ?", + tokenHashBytes); + return Optional.ofNullable(row == null ? null : toReceipt(row)); + } + + /** Read-only source-history lookup used to prove a progressed Account stream. */ + @Transactional(propagation = Propagation.MANDATORY) + public Optional findByRequestId(String requestId) { + requireOwnerTransaction(); + requireBoundedText(requestId, "request ID", 128); + Record row = + dsl.fetchOne( + "SELECT " + SELECT_COLUMNS + " FROM " + TABLE + " WHERE request_id = ?", requestId); + return Optional.ofNullable(row == null ? null : toReceipt(row)); + } + + /** Inserts the one immutable receipt for this token hash. */ + @Transactional(propagation = Propagation.MANDATORY) + public PasswordResetReceipt insert(PasswordResetReceipt receipt) { + requireOwnerTransaction(); + validateReceipt(receipt); + int inserted = + dsl.execute( + "INSERT INTO " + + TABLE + + " (token_hash, account_id, account_uuid, operation_kind, request_id, " + + "request_digest_version, request_digest, token_expires_at, " + + "password_verifier_digest, outbox_stream_key, outbox_sequence, event_id, " + + "event_digest, account_authority_generation, account_source_version, " + + "issuance_fence, issuance_fence_source_version) " + + "VALUES (?, ?, ?, 'PASSWORD_RESET', ?, 1, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + decodeDigest(receipt.tokenHash(), "token hash"), + receipt.accountId(), + receipt.accountUuid(), + receipt.requestId(), + decodeDigest(receipt.requestDigest(), "request digest"), + receipt.tokenExpiresAt(), + decodeDigest(receipt.passwordVerifierDigest(), "password verifier digest"), + receipt.outboxStreamKey(), + receipt.outboxSequence(), + receipt.eventId(), + receipt.eventDigest(), + receipt.accountAuthorityGeneration(), + receipt.accountSourceVersion(), + receipt.issuanceFence(), + receipt.issuanceFenceSourceVersion()); + if (inserted != 1) { + throw new IllegalStateException("Password-reset operation receipt was not inserted"); + } + return receipt; + } + + private PasswordResetReceipt toReceipt(Record row) { + return new PasswordResetReceipt( + requiredPositive(row.get("account_id", Long.class), "Account association"), + Objects.requireNonNull(row.get("account_uuid", UUID.class), "receipt Account UUID"), + encodeDigest(row.get("token_hash", byte[].class), "token hash"), + requireText(row.get("operation_kind", String.class), "operation kind"), + requireText(row.get("request_id", String.class), "request ID"), + requiredPositive(row.get("request_digest_version", Integer.class), "digest version"), + encodeDigest(row.get("request_digest", byte[].class), "request digest"), + Objects.requireNonNull( + row.get("token_expires_at", java.time.LocalDateTime.class), "token deadline"), + encodeDigest(row.get("password_verifier_digest", byte[].class), "password verifier digest"), + requireText(row.get("outbox_stream_key", String.class), "outbox stream key"), + requiredPositive(row.get("outbox_sequence", Long.class), "outbox sequence"), + requireText(row.get("event_id", String.class), "event ID"), + requireText(row.get("event_digest", String.class), "event digest"), + requiredPositive( + row.get("account_authority_generation", Long.class), "Account authority generation"), + requiredPositive(row.get("account_source_version", Long.class), "Account source version"), + requiredPositive(row.get("issuance_fence", Long.class), "issuance fence"), + requiredPositive( + row.get("issuance_fence_source_version", Long.class), "issuance-fence source version")); + } + + private static void validateReceipt(PasswordResetReceipt receipt) { + Objects.requireNonNull(receipt, "password-reset receipt is required"); + decodeDigest(receipt.tokenHash(), "token hash"); + decodeDigest(receipt.requestDigest(), "request digest"); + decodeDigest(receipt.passwordVerifierDigest(), "password verifier digest"); + if (receipt.accountId() <= 0L + || receipt.accountUuid() == null + || new UUID(0L, 0L).equals(receipt.accountUuid()) + || receipt.requestDigestVersion() != 1 + || receipt.tokenExpiresAt() == null + || receipt.outboxSequence() <= 0L + || receipt.accountAuthorityGeneration() <= 0L + || receipt.accountSourceVersion() <= 0L + || receipt.issuanceFence() <= 0L + || receipt.issuanceFenceSourceVersion() <= 0L + || !accountStreamKey(receipt.accountUuid()).equals(receipt.outboxStreamKey()) + || receipt.eventDigest() == null + || !receipt.eventDigest().matches("sha256:[0-9a-f]{64}")) { + throw new IllegalArgumentException("Password-reset operation receipt is malformed"); + } + requireBoundedText(receipt.operationKind(), "operation kind", 32); + if (!"PASSWORD_RESET".equals(receipt.operationKind())) { + throw new IllegalArgumentException("Password-reset operation kind is invalid"); + } + requireBoundedText(receipt.requestId(), "request ID", 128); + requireBoundedText(receipt.eventId(), "event ID", 128); + if (!(REQUEST_ID_PREFIX + receipt.tokenHash()).equals(receipt.requestId()) + || !(EVENT_ID_PREFIX + receipt.tokenHash()).equals(receipt.eventId())) { + throw new IllegalArgumentException( + "Password-reset operation IDs must be derived from the token hash"); + } + } + + private static void requireOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Password-reset operation storage requires an active Account transaction"); + } + } + + private static long requiredPositive(Long value, String field) { + if (value == null || value <= 0L) { + throw new IllegalStateException("Password-reset receipt " + field + " is missing or invalid"); + } + return value; + } + + private static int requiredPositive(Integer value, String field) { + if (value == null || value <= 0) { + throw new IllegalStateException("Password-reset receipt " + field + " is missing or invalid"); + } + return value; + } + + private static String requireText(String value, String field) { + if (value == null || value.isBlank()) { + throw new IllegalStateException("Password-reset receipt " + field + " is missing or invalid"); + } + return value; + } + + private static void requireBoundedText(String value, String field, int maximumLength) { + if (value == null || value.isBlank() || value.length() > maximumLength) { + throw new IllegalArgumentException( + "Password-reset receipt " + + field + + " must contain 1 to " + + maximumLength + + " characters"); + } + } + + private static byte[] decodeDigest(String value, String field) { + if (value == null || !value.matches("[0-9a-f]{64}")) { + throw new IllegalArgumentException("Password-reset receipt " + field + " is malformed"); + } + return HEX.parseHex(value); + } + + private static String encodeDigest(byte[] value, String field) { + if (value == null || value.length != 32) { + throw new IllegalStateException("Password-reset receipt " + field + " is missing or invalid"); + } + return HEX.formatHex(value); + } + + private static String accountStreamKey(UUID accountUuid) { + return "account:auth-authority:v1:account/" + accountUuid; + } + + /** Immutable commit and retry evidence; digest values are lowercase SHA-256 hex strings. */ + public record PasswordResetReceipt( + long accountId, + UUID accountUuid, + String tokenHash, + String operationKind, + String requestId, + int requestDigestVersion, + String requestDigest, + java.time.LocalDateTime tokenExpiresAt, + String passwordVerifierDigest, + String outboxStreamKey, + long outboxSequence, + String eventId, + String eventDigest, + long accountAuthorityGeneration, + long accountSourceVersion, + long issuanceFence, + long issuanceFenceSourceVersion) { + public PasswordResetReceipt { + decodeDigest(tokenHash, "token hash"); + decodeDigest(requestDigest, "request digest"); + decodeDigest(passwordVerifierDigest, "password verifier digest"); + if (accountId <= 0L + || accountUuid == null + || new UUID(0L, 0L).equals(accountUuid) + || requestDigestVersion != 1 + || tokenExpiresAt == null + || outboxSequence <= 0L + || accountAuthorityGeneration <= 0L + || accountSourceVersion <= 0L + || issuanceFence <= 0L + || issuanceFenceSourceVersion <= 0L + || !accountStreamKey(accountUuid).equals(outboxStreamKey) + || eventDigest == null + || !eventDigest.matches("sha256:[0-9a-f]{64}")) { + throw new IllegalArgumentException("Password-reset operation receipt is malformed"); + } + requireBoundedText(operationKind, "operation kind", 32); + if (!"PASSWORD_RESET".equals(operationKind)) { + throw new IllegalArgumentException("Password-reset operation kind is invalid"); + } + requireBoundedText(requestId, "request ID", 128); + requireBoundedText(eventId, "event ID", 128); + if (!(REQUEST_ID_PREFIX + tokenHash).equals(requestId) + || !(EVENT_ID_PREFIX + tokenHash).equals(eventId)) { + throw new IllegalArgumentException( + "Password-reset operation IDs must be derived from the token hash"); + } + } + + public static PasswordResetReceipt committed( + long accountId, + UUID accountUuid, + String tokenHash, + String requestId, + String requestDigest, + java.time.LocalDateTime tokenExpiresAt, + String passwordVerifierDigest, + String outboxStreamKey, + long outboxSequence, + String eventId, + String eventDigest, + ScopeState accountAuthority, + IssuanceFence issuanceFence) { + if (accountAuthority == null + || issuanceFence == null + || accountAuthority.issuanceFence() == null + || !issuanceFence.equals(accountAuthority.issuanceFence())) { + throw new IllegalArgumentException( + "Committed password-reset authority and issuance fence must match exactly"); + } + return new PasswordResetReceipt( + accountId, + accountUuid, + tokenHash, + "PASSWORD_RESET", + requestId, + 1, + requestDigest, + tokenExpiresAt, + passwordVerifierDigest, + outboxStreamKey, + outboxSequence, + eventId, + eventDigest, + accountAuthority.generation(), + accountAuthority.sourceVersion(), + issuanceFence.value(), + issuanceFence.sourceVersion()); + } + + public IssuanceFence issuanceFenceEvidence() { + return new IssuanceFence(accountUuid, issuanceFence, issuanceFenceSourceVersion); + } + } + + /** A token identity was already committed with a different supplied password. */ + public static final class OperationConflictException extends IllegalStateException { + public OperationConflictException(String message) { + super(message); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountRepository.java index fdd91ce821..783e6705f4 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountRepository.java @@ -52,6 +52,16 @@ public Optional findById(Long id) { dsl.selectFrom(ACCOUNTS).where(ACCOUNTS.ID.eq(id)).fetchOne(this::toEntity)); } + /** Locks one exact persisted Account row before an owner-local authority mutation. */ + @Transactional + public Optional findByIdForUpdate(Long id) { + if (id == null || id <= 0L) { + throw new IllegalArgumentException("A positive persisted Account ID is required"); + } + return Optional.ofNullable( + dsl.selectFrom(ACCOUNTS).where(ACCOUNTS.ID.eq(id)).forUpdate().fetchOne(this::toEntity)); + } + public Optional findByAccountUuid(UUID accountUuid) { Objects.requireNonNull(accountUuid, "accountUuid must not be null"); return Optional.ofNullable( diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountSecurityStateOperationRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountSecurityStateOperationRepository.java new file mode 100644 index 0000000000..c8e5867660 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountSecurityStateOperationRepository.java @@ -0,0 +1,662 @@ +package net.firedevops.firemud.accountservice.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.io.ByteArrayOutputStream; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository.SourceChange; +import net.firedevops.firemud.accountservice.dto.AccountSecurityStateMutationRequest; +import net.firedevops.firemud.accountservice.dto.AccountSecurityStateRequestDigest; +import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; +import net.firedevops.firemud.accountservice.entity.AccountLoginAuthModes; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeState; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Event; +import net.firedevops.firemud.accountservice.service.AccountAuthoritySourceReader.AccountSourceEventReadback; +import net.firedevops.firemud.accountservice.service.AccountAuthoritySourceReader.AccountSourceSnapshot; +import net.firedevops.firemud.common.account.authority.AccountSecurityStateAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.AccountSecurityStateAuthorityEventV1Codec.AccountState; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Account-local immutable operation storage. Caller bytes are correlation only. This class neither + * authorizes a mutation nor updates Account/source/outbox or settles V57. Real owner evidence, + * exact workload/caller authentication and commit currentness must be proved separately; a digest + * cannot replace a retained owner receipt. Data access is not producer activation. + */ +@Repository +public class AccountSecurityStateOperationRepository { + private static final String TABLE = "account_security_state_operations"; + private final DSLContext dsl; + private final AccountAuthorityGenerationRepository generations; + private final AccountAuthorityOutboxRepository outbox; + private final AccountAuthoritySourceEvidenceRepository sourceEvidence; + + @SuppressFBWarnings( + value = {"EI_EXPOSE_REP2", "CT_CONSTRUCTOR_THROW"}, + justification = + "Spring proxies require a non-final repository; constructor only validates internal DSL collaborators, acquires no resources and publishes no partial instance.") + public AccountSecurityStateOperationRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl); + generations = new AccountAuthorityGenerationRepository(dsl); + outbox = new AccountAuthorityOutboxRepository(dsl); + sourceEvidence = new AccountAuthoritySourceEvidenceRepository(dsl, generations, outbox); + } + + /** Locks identity, then recovers the original request before comparing any new capture. */ + public Claim claim(AccountSecurityStateMutationRequest request, Capture capture) { + requireTransaction(); + Objects.requireNonNull(request); + Objects.requireNonNull(capture); + lockAssociation(capture.accountId(), request.accountUuid(), capture.provenance()); + Optional prior = readForUpdate(request.requestId()); + if (prior.isPresent()) { + Operation original = prior.orElseThrow(); + requireRequest(original, request); + if (capture.accountId() != original.capture().accountId() + || capture.provenance() != original.capture().provenance()) { + throw new OperationConflictException("Original Account association changed"); + } + if (original.receipt().isEmpty()) requireSourceChange(original.capture(), false); + return new Claim(false, original); + } + requireCapture(request, capture); + increment(request.expectedGeneration()); + increment(request.expectedSourceVersion()); + increment(capture.sourceState().issuanceFence().value()); + increment(capture.sourceState().issuanceFence().sourceVersion()); + increment(capture.checkpointSequence()); + if (request.mutationKinds().contains("GLOBAL_ROLE_CHANGED")) + increment(capture.globalRoleSourceVersion()); + ScopeState current = generations.read(AuthorityScope.account(request.accountUuid())); + if (!current.equals(capture.sourceState()) + || !readCurrentState(request.accountUuid(), capture.globalRoleSourceVersion()) + .equals(capture.beforeState())) { + throw new IllegalStateException("Original source/state capture is not current"); + } + requireCheckpoint(capture, request.accountUuid()); + requireSourceChange(capture, false); + int inserted = + dsl.execute( + "INSERT INTO " + + TABLE + + " (request_id, account_id, account_uuid, account_provenance, " + + "caller_proof_binding, request_payload, request_digest, expected_generation, " + + "expected_source_version, expected_fence, expected_fence_source_version, " + + "checkpoint_sequence, checkpoint_payload, global_role_source_version, before_state, " + + "after_state, mutation_kinds, source_change_id, source_change_binding, capture_payload, status) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'WAITING') " + + "ON CONFLICT (request_id) DO NOTHING", + request.requestId(), + capture.accountId(), + request.accountUuid(), + capture.provenance().name(), + request.callerProofBinding(), + AccountSecurityStateRequestDigest.requestBytes(request), + AccountSecurityStateRequestDigest.digest(request), + request.expectedGeneration(), + request.expectedSourceVersion(), + capture.sourceState().issuanceFence().value(), + capture.sourceState().issuanceFence().sourceVersion(), + capture.checkpointSequence(), + capture.checkpointPayload(), + capture.globalRoleSourceVersion(), + AccountSecurityStateMutationRequest.canonicalState(capture.beforeState()), + request.canonicalDesiredState(), + request.mutationKinds().toArray(String[]::new), + capture.sourceChange().changeId(), + capture.sourceChange().canonicalBytes(), + captureBytes(request, capture)); + Operation stored = readForUpdate(request.requestId()).orElseThrow(); + requireRequest(stored, request); + if (inserted == 1 + && !Arrays.equals( + captureBytes(request, capture), captureBytes(request, stored.capture()))) { + throw new IllegalStateException("Original operation capture readback differs"); + } + return new Claim(inserted == 1, stored); + } + + /** Returns immutable current or historical operation evidence without applying a mutation. */ + public Optional findByRequestId(UUID requestId) { + requireTransaction(); + Objects.requireNonNull(requestId); + Record identity = + dsl.fetchOne( + "SELECT account_id, account_uuid, account_provenance FROM " + + TABLE + + " WHERE request_id = ?", + requestId); + if (identity == null) return Optional.empty(); + lockAssociation( + identity.get("account_id", Long.class), + identity.get("account_uuid", UUID.class), + AccountIdentityProvenance.fromStorageValue( + identity.get("account_provenance", String.class))); + Optional stored = readForUpdate(requestId); + stored + .filter(operation -> operation.receipt().isEmpty()) + .ifPresent(operation -> requireSourceChange(operation.capture(), false)); + return stored; + } + + /** Proves actual current poststate, separately from immutable historical receipt validation. */ + public void requireCurrentPostState(Operation operation, ScopeState current) { + requireTransaction(); + Objects.requireNonNull(operation); + Receipt receipt = + operation + .receipt() + .orElseThrow( + () -> new IllegalStateException("Committed security-state receipt is required")); + var request = operation.request(); + lockAssociation( + operation.capture().accountId(), request.accountUuid(), operation.capture().provenance()); + Operation stored = findByRequestId(request.requestId()).orElseThrow(); + requireRequest(stored, request); + if (!stored.receipt().orElseThrow().event().equals(receipt.event()) + || current == null + || !receipt.sourceState().scope().equals(current.scope()) + || receipt.sourceState().generation() != current.generation() + || receipt.sourceState().sourceVersion() != current.sourceVersion() + || !generations.read(AuthorityScope.account(request.accountUuid())).equals(current) + || !readCurrentState(request.accountUuid(), receipt.globalRoleSourceVersion()) + .equals(request.desiredState())) { + throw new IllegalStateException( + "Latest security-state actual Account/role/source poststate differs"); + } + var checkpoint = outbox.readCheckpoint(streamKey(request.accountUuid())).orElseThrow(); + if (checkpoint.outboxSequence() != receipt.event().outboxSequence() + || !checkpoint.sourceEventId().equals(receipt.event().eventId()) + || !checkpoint.sourceEventDigest().equals(receipt.event().eventDigest())) { + throw new IllegalStateException("Latest security-state complete checkpoint differs"); + } + } + + /** Records only an existing producer-committed event and V57 completion in this transaction. */ + public Operation complete( + AccountSecurityStateMutationRequest request, + Event event, + ScopeState result, + long resultGlobalRoleSourceVersion) { + requireTransaction(); + Record identity = + dsl.fetchOne( + "SELECT account_id, account_provenance FROM " + TABLE + " WHERE request_id = ?", + request.requestId()); + if (identity == null) + throw new IllegalStateException("Original security-state request is missing"); + lockAssociation( + identity.get("account_id", Long.class), + request.accountUuid(), + AccountIdentityProvenance.fromStorageValue( + identity.get("account_provenance", String.class))); + Operation original = readForUpdate(request.requestId()).orElseThrow(); + requireRequest(original, request); + if (original.receipt().isPresent()) { + Receipt committed = original.receipt().orElseThrow(); + if (!committed.event().equals(event) + || !committed.sourceState().equals(result) + || committed.globalRoleSourceVersion() != resultGlobalRoleSourceVersion) { + throw new OperationConflictException("Committed receipt was supplied with changed results"); + } + return original; + } + requireResult(original, event, result, resultGlobalRoleSourceVersion); + requireSourceChange(original.capture(), true); + if (!generations.read(AuthorityScope.account(request.accountUuid())).equals(result) + || !readCurrentState(request.accountUuid(), resultGlobalRoleSourceVersion) + .equals(request.desiredState())) { + throw new IllegalStateException("Committed producer state readback differs"); + } + var checkpoint = outbox.readCheckpoint(event.outboxStreamKey()).orElseThrow(); + if (checkpoint.outboxSequence() != event.outboxSequence() + || !checkpoint.sourceEventId().equals(event.eventId()) + || !checkpoint.sourceEventDigest().equals(event.eventDigest())) { + throw new IllegalStateException("Committed source checkpoint readback differs"); + } + int updated = + dsl.execute( + "UPDATE " + + TABLE + + " SET status = 'COMMITTED', event_sequence = ?, event_id = ?, " + + "event_digest = ?, event_payload = ?, result_generation = ?, result_source_version = ?, " + + "result_fence = ?, result_fence_source_version = ?, result_global_role_source_version = ? " + + "WHERE request_id = ? AND status = 'WAITING'", + event.outboxSequence(), + event.eventId(), + event.eventDigest(), + event.payload(), + result.generation(), + result.sourceVersion(), + result.issuanceFence().value(), + result.issuanceFence().sourceVersion(), + resultGlobalRoleSourceVersion, + request.requestId()); + if (updated != 1) throw new IllegalStateException("Operation did not commit exactly once"); + Operation stored = readForUpdate(request.requestId()).orElseThrow(); + requireRequest(stored, request); + if (!stored.receipt().orElseThrow().event().equals(event)) { + throw new IllegalStateException("Committed operation event readback differs"); + } + sourceEvidence.advanceClosedAccountHead( + request.accountUuid(), original.capture().sourceState(), result, event); + return stored; + } + + private Optional readForUpdate(UUID requestId) { + Record row = + dsl.fetchOne("SELECT * FROM " + TABLE + " WHERE request_id = ? FOR UPDATE", requestId); + if (row == null) return Optional.empty(); + UUID accountUuid = row.get("account_uuid", UUID.class); + var request = + new AccountSecurityStateMutationRequest( + requestId, + accountUuid, + row.get("caller_proof_binding", byte[].class), + row.get("expected_generation", Long.class), + row.get("expected_source_version", Long.class), + List.of(row.get("mutation_kinds", String[].class)), + AccountSecurityStateMutationRequest.parseCanonicalState( + row.get("after_state", byte[].class))); + if (!Arrays.equals( + AccountSecurityStateRequestDigest.requestBytes(request), + row.get("request_payload", byte[].class)) + || !AccountSecurityStateRequestDigest.digest(request) + .equals(row.get("request_digest", String.class))) { + throw new IllegalStateException("Stored original request digest/bytes differ"); + } + ScopeState expected = + new ScopeState( + AuthorityScope.account(accountUuid), + request.expectedGeneration(), + request.expectedSourceVersion(), + new AccountAuthorityGenerationRepository.IssuanceFence( + accountUuid, + row.get("expected_fence", Long.class), + row.get("expected_fence_source_version", Long.class))); + Capture capture = + new Capture( + row.get("account_id", Long.class), + AccountIdentityProvenance.fromStorageValue(row.get("account_provenance", String.class)), + AccountSecurityStateMutationRequest.parseCanonicalState( + row.get("before_state", byte[].class)), + expected, + row.get("checkpoint_sequence", Long.class), + row.get("checkpoint_payload", byte[].class), + row.get("global_role_source_version", Long.class), + SourceChange.fromStored(row.get("source_change_binding", byte[].class))); + requireCapture(request, capture); + if (!capture.sourceChange().changeId().equals(row.get("source_change_id", UUID.class)) + || !Arrays.equals( + captureBytes(request, capture), row.get("capture_payload", byte[].class))) { + throw new IllegalStateException("Stored original source capture differs"); + } + String status = row.get("status", String.class); + Optional receipt = Optional.empty(); + if ("COMMITTED".equals(status)) { + Event event = + new Event( + streamKey(accountUuid), + requestId.toString(), + row.get("event_sequence", Long.class), + row.get("event_id", String.class), + row.get("event_digest", String.class), + row.get("event_payload", byte[].class)); + ScopeState result = + new ScopeState( + AuthorityScope.account(accountUuid), + row.get("result_generation", Long.class), + row.get("result_source_version", Long.class), + new AccountAuthorityGenerationRepository.IssuanceFence( + accountUuid, + row.get("result_fence", Long.class), + row.get("result_fence_source_version", Long.class))); + receipt = + Optional.of( + new Receipt(event, result, row.get("result_global_role_source_version", Long.class))); + } else if (!"WAITING".equals(status)) { + throw new IllegalStateException("Unsupported operation state"); + } + Operation operation = new Operation(request, capture, receipt); + if (receipt.isPresent()) { + requireResult( + operation, + receipt.orElseThrow().event(), + receipt.orElseThrow().sourceState(), + receipt.orElseThrow().globalRoleSourceVersion()); + requireSourceChange(capture, true); + requireReceiptNotAhead(operation); + } + return Optional.of(operation); + } + + private void requireResult( + Operation operation, Event event, ScopeState result, long roleSourceVersion) { + if (event == null || result == null || result.issuanceFence() == null) { + throw new IllegalStateException("Complete Account source receipt is required"); + } + var request = operation.request(); + var capture = operation.capture(); + var verified = + AccountSecurityStateAuthorityEventV1Codec.verify( + new String(event.payload(), StandardCharsets.UTF_8)); + if (!Arrays.equals(event.payload(), verified.canonicalJsonUtf8()) + || !request.accountUuid().toString().equals(verified.accountId()) + || !request.requestId().toString().equals(verified.requestId()) + || !request.requestId().toString().equals(event.requestId()) + || !streamKey(request.accountUuid()).equals(event.outboxStreamKey()) + || !event.outboxStreamKey().equals(verified.outboxStreamKey()) + || !event.eventId().equals(verified.eventId()) + || !event.eventDigest().equals(verified.eventDigest()) + || !Long.toString(event.outboxSequence()).equals(verified.outboxSequence()) + || event.outboxSequence() != increment(capture.checkpointSequence()) + || !result.scope().equals(capture.sourceState().scope()) + || result.generation() != increment(request.expectedGeneration()) + || result.sourceVersion() != increment(request.expectedSourceVersion()) + || !Long.toString(result.generation()).equals(verified.accountAuthorityGeneration()) + || !Long.toString(result.sourceVersion()).equals(verified.sourceVersion()) + || !request.accountUuid().equals(result.issuanceFence().accountId()) + || result.issuanceFence().value() + != increment(capture.sourceState().issuanceFence().value()) + || result.issuanceFence().sourceVersion() + != increment(capture.sourceState().issuanceFence().sourceVersion()) + || roleSourceVersion + != (request.mutationKinds().contains("GLOBAL_ROLE_CHANGED") + ? increment(capture.globalRoleSourceVersion()) + : capture.globalRoleSourceVersion()) + || !verified.accountState().equals(request.desiredState()) + || !verified.mutationKinds().equals(request.mutationKinds())) { + throw new IllegalStateException("Source receipt differs from the original operation/result"); + } + Event byRequest = outbox.findEvent(event.outboxStreamKey(), event.requestId()).orElseThrow(); + Event bySequence = + outbox.findEvent(event.outboxStreamKey(), event.outboxSequence()).orElseThrow(); + if (!event.equals(byRequest) || !event.equals(bySequence)) { + throw new IllegalStateException("Canonical outbox receipt readback differs"); + } + } + + private void requireCapture(AccountSecurityStateMutationRequest request, Capture capture) { + Objects.requireNonNull(capture.sourceChange(), "Original V57 source change is required"); + if (!capture.sourceState().scope().equals(AuthorityScope.account(request.accountUuid())) + || capture.sourceState().generation() != request.expectedGeneration() + || capture.sourceState().sourceVersion() != request.expectedSourceVersion() + || !request.accountUuid().equals(capture.sourceState().issuanceFence().accountId()) + || !detectedKinds(capture.beforeState(), request.desiredState()) + .equals(request.mutationKinds())) { + throw new IllegalArgumentException( + "Original state/source/family capture differs from request"); + } + // Passwords are intentionally absent; their real owner operation is outside this journal. + boolean accountSource = false; + boolean roleSource = false; + for (var source : capture.sourceChange().sources()) { + if (!request.accountUuid().toString().equals(source.scopeId())) { + throw new IllegalArgumentException("Source participation targets another Account"); + } + if (source.kind() == SourceKind.ACCOUNT) { + accountSource = true; + if (!Long.toString(request.expectedGeneration()).equals(source.generation()) + || !Long.toString(request.expectedSourceVersion()).equals(source.sourceVersion()) + || !streamKey(request.accountUuid()).equals(source.checkpointStream()) + || !Long.toString(capture.checkpointSequence()).equals(source.checkpointSequence()) + || !Arrays.equals(captureBytes(request, capture), source.evidence())) { + throw new IllegalArgumentException("Exact Account source participation is required"); + } + } else if (source.kind() == SourceKind.GLOBAL_ROLES) { + roleSource = true; + if (!Long.toString(capture.globalRoleSourceVersion()).equals(source.sourceVersion()) + || source.generation() != null + || source.checkpointStream() != null + || !Arrays.equals(captureBytes(request, capture), source.evidence())) { + throw new IllegalArgumentException("Independent role-source version differs"); + } + } else { + throw new IllegalArgumentException("Unrelated source participation is unsupported"); + } + } + if (!accountSource + || roleSource != request.mutationKinds().contains("GLOBAL_ROLE_CHANGED") + || !Arrays.equals(captureBytes(request, capture), capture.sourceChange().mutation())) { + throw new IllegalArgumentException("Complete exact source-change binding is required"); + } + } + + public static List detectedKinds(AccountState before, AccountState after) { + List kinds = new ArrayList<>(); + if (before.emailVerified() != after.emailVerified()) + kinds.add("EMAIL_LOGIN_ELIGIBILITY_CHANGED"); + if (!before.globalRoles().equals(after.globalRoles())) kinds.add("GLOBAL_ROLE_CHANGED"); + if (!before.lifecycleState().equals(after.lifecycleState())) + kinds.add("LIFECYCLE_STATE_CHANGED"); + if (!before.loginAuthModes().equals(after.loginAuthModes())) + kinds.add("LOGIN_AUTH_MODES_CHANGED"); + return List.copyOf(kinds); + } + + public static byte[] captureBytes(AccountSecurityStateMutationRequest request, Capture capture) { + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + AccountSecurityStateRequestDigest.frame(bytes, "firemud/account/security-state/capture/v1"); + AccountSecurityStateRequestDigest.frame( + bytes, AccountSecurityStateRequestDigest.requestBytes(request)); + AccountSecurityStateRequestDigest.frame(bytes, Long.toString(capture.accountId())); + AccountSecurityStateRequestDigest.frame(bytes, capture.provenance().name()); + AccountSecurityStateRequestDigest.frame( + bytes, AccountSecurityStateMutationRequest.canonicalState(capture.beforeState())); + AccountSecurityStateRequestDigest.frame( + bytes, Long.toString(capture.sourceState().issuanceFence().value())); + AccountSecurityStateRequestDigest.frame( + bytes, Long.toString(capture.sourceState().issuanceFence().sourceVersion())); + AccountSecurityStateRequestDigest.frame(bytes, Long.toString(capture.checkpointSequence())); + AccountSecurityStateRequestDigest.frame(bytes, capture.checkpointPayload()); + AccountSecurityStateRequestDigest.frame( + bytes, Long.toString(capture.globalRoleSourceVersion())); + return bytes.toByteArray(); + } + + private void requireCheckpoint(Capture capture, UUID accountUuid) { + var checkpoint = outbox.readCheckpoint(streamKey(accountUuid)); + if (capture.checkpointSequence() == 0) { + Record history = + dsl.fetchOne( + "SELECT count(*)::integer AS count FROM account_authority_outbox_events WHERE outbox_stream_key = ?", + streamKey(accountUuid)); + if (history == null) { + throw new IllegalStateException("Original Account source history count is missing"); + } + Integer count = history.get("count", Integer.class); + if (capture.sourceState().generation() != 1 + || capture.sourceState().sourceVersion() != 1 + || checkpoint.isPresent() + || count == null + || count != 0 + || capture.checkpointPayload().length != 0) { + throw new IllegalStateException("Original sequence-zero baseline is not proved"); + } + } else { + Event latest = + outbox.findEvent(streamKey(accountUuid), capture.checkpointSequence()).orElseThrow(); + if (checkpoint.orElseThrow().outboxSequence() != capture.checkpointSequence() + || !checkpoint.orElseThrow().sourceEventId().equals(latest.eventId()) + || !checkpoint.orElseThrow().sourceEventDigest().equals(latest.eventDigest()) + || !latest.equals( + outbox.findEvent(streamKey(accountUuid), latest.requestId()).orElseThrow()) + || !Arrays.equals(capture.checkpointPayload(), latest.payload())) { + throw new IllegalStateException("Original checkpoint capture differs"); + } + // Structural closed-schema verification only; this does not prove caller authorization. + new AccountSourceSnapshot( + accountUuid, + capture.sourceState(), + streamKey(accountUuid), + capture.checkpointSequence(), + Optional.of(latest)); + } + } + + private void requireReceiptNotAhead(Operation operation) { + Receipt retained = operation.receipt().orElseThrow(); + UUID accountUuid = operation.request().accountUuid(); + ScopeState current = generations.read(AuthorityScope.account(accountUuid)); + var checkpoint = outbox.readCheckpoint(streamKey(accountUuid)).orElseThrow(); + Event latest = + outbox.findEvent(streamKey(accountUuid), checkpoint.outboxSequence()).orElseThrow(); + AccountSourceSnapshot snapshot = + new AccountSourceSnapshot( + accountUuid, + current, + streamKey(accountUuid), + checkpoint.outboxSequence(), + Optional.of(latest)); + new AccountSourceEventReadback(snapshot, retained.event()); + Record role = + dsl.fetchOne( + "SELECT global_role_source_version FROM account_global_role_sources WHERE account_uuid = ? FOR SHARE", + accountUuid); + Long roleVersion = role == null ? null : role.get("global_role_source_version", Long.class); + if (retained.sourceState().issuanceFence().value() > current.issuanceFence().value() + || retained.sourceState().issuanceFence().sourceVersion() + > current.issuanceFence().sourceVersion() + || roleVersion == null + || retained.globalRoleSourceVersion() > roleVersion) { + throw new IllegalStateException("Retained receipt is ahead of present Account authority"); + } + } + + private void requireSourceChange(Capture capture, boolean committed) { + Record source = + dsl.fetchOne( + "SELECT binding, status FROM account_draft_authorization_source_changes WHERE change_id = ? FOR SHARE", + capture.sourceChange().changeId()); + if (source == null + || !Arrays.equals( + capture.sourceChange().canonicalBytes(), source.get("binding", byte[].class)) + || !(committed ? "SOURCE_COMMITTED" : "WAITING") + .equals(source.get("status", String.class))) { + throw new IllegalStateException("Original V57 source-change evidence/status differs"); + } + } + + private void lockAssociation( + long numericId, UUID accountUuid, AccountIdentityProvenance provenance) { + Record account = + dsl.fetchOne( + "SELECT id, account_uuid, account_uuid_source_numeric_id, account_uuid_provenance FROM accounts WHERE id = ? FOR UPDATE", + numericId); + if (account == null + || !accountUuid.equals(account.get("account_uuid", UUID.class)) + || !Long.valueOf(numericId) + .equals(account.get("account_uuid_source_numeric_id", Long.class)) + || !provenance.name().equals(account.get("account_uuid_provenance", String.class))) { + throw new IllegalStateException("Persisted numeric/UUID/provenance association differs"); + } + } + + private AccountState readCurrentState(UUID accountUuid, long roleVersion) { + Record row = + dsl.fetchOne( + "SELECT a.email_verified, a.login_auth_modes, a.lifecycle_state, r.global_roles, r.global_role_source_version FROM accounts a JOIN account_global_role_sources r ON r.account_uuid = a.account_uuid WHERE a.account_uuid = ? FOR SHARE OF a, r", + accountUuid); + if (row == null + || !Long.valueOf(roleVersion).equals(row.get("global_role_source_version", Long.class))) { + throw new IllegalStateException( + "Current independently versioned global-role source is unavailable"); + } + var state = + new AccountState( + Boolean.TRUE.equals(row.get("email_verified", Boolean.class)), + AccountLoginAuthModes.read(row.get("login_auth_modes", String.class)).stream() + .map(Enum::name) + .sorted() + .toList(), + Arrays.stream(row.get("global_roles", String[].class)).sorted().toList(), + row.get("lifecycle_state", String.class).toUpperCase(java.util.Locale.ROOT)); + return AccountSecurityStateMutationRequest.parseCanonicalState( + AccountSecurityStateMutationRequest.canonicalState(state)); + } + + private static void requireRequest( + Operation original, AccountSecurityStateMutationRequest request) { + if (!Arrays.equals( + AccountSecurityStateRequestDigest.requestBytes(original.request()), + AccountSecurityStateRequestDigest.requestBytes(request))) { + throw new OperationConflictException( + "Request ID was reused with changed original caller/state binding"); + } + } + + private static long increment(long value) { + try { + return Math.addExact(value, 1L); + } catch (ArithmeticException overflow) { + throw new IllegalStateException("Account source counter overflow", overflow); + } + } + + private static String streamKey(UUID accountUuid) { + return "account:auth-authority:v1:account/" + accountUuid; + } + + private static void requireTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException("Writable Account owner transaction is required"); + } + } + + public record Capture( + long accountId, + AccountIdentityProvenance provenance, + AccountState beforeState, + ScopeState sourceState, + long checkpointSequence, + byte[] checkpointPayload, + long globalRoleSourceVersion, + SourceChange sourceChange) { + public Capture { + if (accountId <= 0 + || checkpointSequence < 0 + || globalRoleSourceVersion <= 0 + || provenance == null + || beforeState == null + || sourceState == null + || sourceState.issuanceFence() == null + || checkpointPayload == null) + throw new IllegalArgumentException("Complete original capture is required"); + checkpointPayload = checkpointPayload.clone(); + beforeState = + AccountSecurityStateMutationRequest.parseCanonicalState( + AccountSecurityStateMutationRequest.canonicalState(beforeState)); + // A temporary null change is permitted solely while constructing its non-circular capture + // bytes. + } + + @Override + public byte[] checkpointPayload() { + return checkpointPayload.clone(); + } + } + + public record Receipt(Event event, ScopeState sourceState, long globalRoleSourceVersion) {} + + public record Operation( + AccountSecurityStateMutationRequest request, Capture capture, Optional receipt) {} + + public record Claim(boolean claimed, Operation operation) {} + + public static final class OperationConflictException extends IllegalStateException { + public OperationConflictException(String message) { + super(message); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepository.java index f66e3c5d48..7c9ae87a0a 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepository.java @@ -225,7 +225,7 @@ public Event append( typed.eventId().toString(), typed.eventDigest(), typed.tenantBillingSequence(), - typed.tenantBillingEventId().toString(), + typed.tenantBillingEventId(), typed.tenantBillingEventDigest(), streamKey, typed.tenantAuthorityGeneration() - 1L, diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadback.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadback.java new file mode 100644 index 0000000000..a351a3354f --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadback.java @@ -0,0 +1,714 @@ +package net.firedevops.firemud.accountservice.service; + +import com.fasterxml.jackson.core.JsonFactory; +import com.fasterxml.jackson.core.StreamReadFeature; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import java.io.IOException; +import java.math.BigInteger; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.AccountLogoutRequestDigest; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.IssuanceFence; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeState; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Checkpoint; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Event; +import net.firedevops.firemud.accountservice.repository.AccountLogoutAllOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountLogoutAllOperationRepository.LogoutAllReceipt; +import net.firedevops.firemud.accountservice.repository.AccountPasswordResetOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountPasswordResetOperationRepository.PasswordResetReceipt; +import net.firedevops.firemud.accountservice.repository.AccountSecurityStateOperationRepository; +import net.firedevops.firemud.common.account.authority.AccountAuthoritySourceEventV1Codec.AccountSecurityCutoff; +import net.firedevops.firemud.common.account.authority.AccountLogoutAllAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.AccountLogoutAllAuthorityEventV1Codec.AccountLogoutAllAuthorityEvent; +import net.firedevops.firemud.common.account.authority.AccountSecurityStateAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.PasswordResetAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.PasswordResetAuthorityEventV1Codec.PasswordResetAuthorityEvent; + +/** + * Narrow receipt validator for the three closed Account account-scope source-event schemas. It does + * not authenticate a caller or turn source evidence into recipient authority. + */ +public final class AccountAuthoritySourceEventReadback { + private static final ObjectMapper SNAPSHOT_JSON = + new ObjectMapper( + JsonFactory.builder().enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION).build()) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS); + private static final String STREAM_PREFIX = "account:auth-authority:v1:account/"; + private static final String PASSWORD_RESET_REQUEST_ID_PREFIX = + "account-password-reset-request-v1:"; + private static final String PASSWORD_RESET_EVENT_ID_PREFIX = "account-password-reset-event-v1:"; + private static final String PASSWORD_RESET_REQUEST_DOMAIN = "account-password-reset-request/v1"; + private static final String LOGOUT_ALL_EVENT_ID_PREFIX = "account-logout-all-event-v1:"; + private static final String PASSWORD_RESET_OPERATION_KIND = "PASSWORD_RESET"; + private static final String LOGOUT_ALL_OPERATION_KIND = "ACCOUNT_LOGOUT_ALL"; + private static final String LOGOUT_ALL_RESULT = "LOGOUT_ALL_COMMITTED"; + + private final AccountAuthorityOutboxRepository outboxRepository; + private final AccountPasswordResetOperationRepository passwordResetRepository; + private final AccountLogoutAllOperationRepository logoutAllRepository; + private final AccountSecurityStateOperationRepository securityStateRepository; + + public AccountAuthoritySourceEventReadback( + AccountAuthorityOutboxRepository outboxRepository, + AccountPasswordResetOperationRepository passwordResetRepository, + AccountLogoutAllOperationRepository logoutAllRepository, + AccountSecurityStateOperationRepository securityStateRepository) { + this.outboxRepository = + Objects.requireNonNull(outboxRepository, "Account authority outbox repository is required"); + this.passwordResetRepository = + Objects.requireNonNull( + passwordResetRepository, "Password-reset operation repository is required"); + this.logoutAllRepository = + Objects.requireNonNull(logoutAllRepository, "Logout-all operation repository is required"); + this.securityStateRepository = + Objects.requireNonNull( + securityStateRepository, "Security-state operation repository is required"); + } + + /** + * Proves the exact current Account source generation, source version and shared outbox + * checkpoint. Sequence zero is valid only for the original positive 1/1 source baseline and + * absent history. + */ + public LatestSourceSnapshot requireCurrentLatest(Account account, ScopeState current) { + requireAccountAssociation(account); + AuthorityScope expectedScope = AuthorityScope.account(account.getAccountUuid()); + if (current == null + || !expectedScope.equals(current.scope()) + || current.generation() <= 0L + || current.sourceVersion() <= 0L) { + throw new IllegalStateException("Account source authority scope or counters are invalid"); + } + requireCurrentFence(current.issuanceFence(), account.getAccountUuid()); + + String streamKey = streamKey(account.getAccountUuid()); + Optional checkpoint = outboxRepository.readCheckpoint(streamKey); + if (checkpoint.isEmpty()) { + if (current.generation() != 1L || current.sourceVersion() != 1L) { + throw new IllegalStateException( + "Account source sequence zero is not the original positive 1/1 baseline"); + } + return new LatestSourceSnapshot(0L, Optional.empty()); + } + + Checkpoint latestCheckpoint = checkpoint.orElseThrow(); + if (current.generation() == 1L && current.sourceVersion() == 1L) { + throw new IllegalStateException("Pristine Account source has contradictory event history"); + } + if (current.generation() <= 1L || current.sourceVersion() <= 1L) { + throw new IllegalStateException("Account source history is not proven"); + } + // The latest closed receipt cannot make an earlier generic Account mutation authoritative. + // Retain generic history for inspection elsewhere, but fail closed for currentness until every + // event in this stream has the closed operation-specific receipt/readback contract. + for (long sequence = 1L; sequence < latestCheckpoint.outboxSequence(); sequence++) { + Event retainedEvent = + outboxRepository + .findEvent(streamKey, sequence) + .orElseThrow( + () -> new IllegalStateException("Retained Account source event is missing")); + requireRetainedEvent(account, retainedEvent, current); + } + Event latestEvent = + outboxRepository + .findEvent(streamKey, latestCheckpoint.outboxSequence()) + .orElseThrow(() -> new IllegalStateException("Latest Account source event is missing")); + requireCheckpointMatches(latestCheckpoint, latestEvent); + VerifiedSourceEvent verified = verifyEvent(latestEvent, account.getAccountUuid()); + if (!Long.toString(current.generation()).equals(verified.accountAuthorityGeneration()) + || !Long.toString(current.sourceVersion()).equals(verified.sourceVersion())) { + throw new IllegalStateException( + "Latest Account source event does not match its current generation and source version"); + } + + if (verified.passwordReset().isPresent()) { + PasswordResetReceipt receipt = + passwordResetRepository + .findByRequestId(verified.requestId()) + .orElseThrow( + () -> + new IllegalStateException( + "Latest Account password-reset event has no immutable operation receipt")); + requirePasswordResetReceipt(account, receipt, latestEvent, verified, current); + } else if (verified.securityState().isPresent()) { + requireSecurityStateReceipt(account, latestEvent, verified, current, true); + } else { + UUID requestId = parseLogoutAllRequestId(verified.requestId()); + LogoutAllReceipt receipt = + logoutAllRepository + .findByRequestId(requestId) + .orElseThrow( + () -> + new IllegalStateException( + "Latest Account logout-all event has no immutable operation receipt")); + requireLogoutAllReceipt(account, receipt, latestEvent, verified, current); + } + return new LatestSourceSnapshot(latestEvent.outboxSequence(), Optional.of(latestEvent)); + } + + /** Validates one retained logout-all receipt after the account stream has advanced further. */ + public void requireLogoutAllReceiptRetained( + Account account, LogoutAllReceipt receipt, Event event, ScopeState current) { + requireAccountAssociation(account); + if (current == null + || !AuthorityScope.account(account.getAccountUuid()).equals(current.scope())) { + throw new IllegalStateException("Logout-all current Account source scope is invalid"); + } + requireCurrentFence(current.issuanceFence(), account.getAccountUuid()); + VerifiedSourceEvent verified = verifyEvent(event, account.getAccountUuid()); + requireLogoutAllReceipt(account, receipt, event, verified, current); + if (event.outboxSequence() > currentSourceSequence(account)) { + throw new IllegalStateException( + "Logout-all operation event is ahead of its source checkpoint"); + } + } + + /** + * Validates one selected immutable Account event and its receipt against the current local + * authority fence. Historical password-reset evidence deliberately does not prove that the old + * password verifier remains current or make that reset operation recoverable. + */ + public RetainedEventEvidence requireRetainedEvent( + Account account, Event event, ScopeState current) { + requireAccountAssociation(account); + if (current == null + || !AuthorityScope.account(account.getAccountUuid()).equals(current.scope()) + || current.generation() <= 0L + || current.sourceVersion() <= 0L) { + throw new IllegalStateException("Retained Account source authority state is invalid"); + } + requireCurrentFence(current.issuanceFence(), account.getAccountUuid()); + VerifiedSourceEvent verified = verifyEvent(event, account.getAccountUuid()); + if (event.outboxSequence() > currentSourceSequence(account)) { + throw new IllegalStateException("Selected Account source event is ahead of its checkpoint"); + } + + if (verified.passwordReset().isPresent()) { + PasswordResetReceipt receipt = + passwordResetRepository + .findByRequestId(verified.requestId()) + .orElseThrow( + () -> + new IllegalStateException( + "Selected Account password-reset event has no immutable operation receipt")); + requirePasswordResetReceiptBinding(account, receipt, event, verified, current); + return retainedEvidence( + event, verified, receipt.issuanceFence(), receipt.issuanceFenceSourceVersion()); + } + + if (verified.securityState().isPresent()) { + var operation = + securityStateRepository + .findByRequestId(UUID.fromString(verified.requestId())) + .orElseThrow( + () -> + new IllegalStateException( + "Selected Account security-state event has no immutable operation receipt")); + var receipt = + operation + .receipt() + .orElseThrow( + () -> + new IllegalStateException( + "Selected Account security-state operation is not COMMITTED")); + requireSecurityStateReceipt(account, event, verified, current, false); + return retainedEvidence( + event, + verified, + receipt.sourceState().issuanceFence().value(), + receipt.sourceState().issuanceFence().sourceVersion()); + } + UUID requestId = parseLogoutAllRequestId(verified.requestId()); + LogoutAllReceipt receipt = + logoutAllRepository + .findByRequestId(requestId) + .orElseThrow( + () -> + new IllegalStateException( + "Selected Account logout-all event has no immutable operation receipt")); + requireLogoutAllReceipt(account, receipt, event, verified, current); + return retainedEvidence( + event, verified, receipt.issuanceFence(), receipt.issuanceFenceSourceVersion()); + } + + private RetainedEventEvidence retainedEvidence( + Event event, VerifiedSourceEvent verified, long issuanceFence, long fenceSourceVersion) { + return new RetainedEventEvidence( + event.outboxStreamKey(), + event.outboxSequence(), + Long.parseLong(verified.accountAuthorityGeneration()), + Long.parseLong(verified.sourceVersion()), + issuanceFence, + fenceSourceVersion, + verified.accountSecurityCutoff()); + } + + private long currentSourceSequence(Account account) { + return outboxRepository + .readCheckpoint(streamKey(account.getAccountUuid())) + .map(Checkpoint::outboxSequence) + .orElse(0L); + } + + private void requireSecurityStateReceipt( + Account account, + Event event, + VerifiedSourceEvent verified, + ScopeState current, + boolean latest) { + var operation = + securityStateRepository + .findByRequestId(UUID.fromString(verified.requestId())) + .orElseThrow( + () -> + new IllegalStateException( + "Account security-state event has no immutable operation receipt")); + var receipt = + operation + .receipt() + .orElseThrow( + () -> + new IllegalStateException("Account security-state operation is not COMMITTED")); + if (!operation.request().accountUuid().equals(account.getAccountUuid()) + || operation.capture().accountId() != account.getId() + || operation.capture().provenance() != account.getAccountUuidProvenance() + || !receipt.event().equals(event)) { + throw new IllegalStateException("Account security-state operation association/event differs"); + } + requireReceiptNotAhead( + receipt.sourceState().generation(), + receipt.sourceState().sourceVersion(), + receipt.sourceState().issuanceFence().value(), + receipt.sourceState().issuanceFence().sourceVersion(), + current, + "Security-state"); + if (latest) securityStateRepository.requireCurrentPostState(operation, current); + } + + private void requirePasswordResetReceipt( + Account account, + PasswordResetReceipt receipt, + Event event, + VerifiedSourceEvent verified, + ScopeState current) { + requirePasswordResetReceiptBinding(account, receipt, event, verified, current); + requireCurrentPasswordVerifier(account, receipt); + } + + private void requirePasswordResetReceiptBinding( + Account account, + PasswordResetReceipt receipt, + Event event, + VerifiedSourceEvent verified, + ScopeState current) { + if (receipt.accountId() != account.getId() + || !account.getAccountUuid().equals(receipt.accountUuid()) + || !PASSWORD_RESET_OPERATION_KIND.equals(receipt.operationKind()) + || receipt.requestDigestVersion() != 1 + || !streamKey(account.getAccountUuid()).equals(receipt.outboxStreamKey()) + || receipt.outboxSequence() != event.outboxSequence() + || !receipt.requestId().equals(event.requestId()) + || !receipt.eventId().equals(event.eventId()) + || !receipt.eventDigest().equals(event.eventDigest()) + || !receipt.eventId().equals(PASSWORD_RESET_EVENT_ID_PREFIX + receipt.tokenHash()) + || !receipt.requestId().equals(PASSWORD_RESET_REQUEST_ID_PREFIX + receipt.tokenHash()) + || !Long.toString(receipt.accountAuthorityGeneration()) + .equals(verified.accountAuthorityGeneration()) + || !Long.toString(receipt.accountSourceVersion()).equals(verified.sourceVersion())) { + throw new IllegalStateException( + "Latest Account password-reset receipt does not match its source event"); + } + String expectedDigest = + passwordResetRequestDigest( + receipt.accountUuid(), + receipt.tokenHash(), + receipt.tokenExpiresAt().toString(), + receipt.passwordVerifierDigest()); + if (!constantTimeTextEquals(expectedDigest, receipt.requestDigest())) { + throw new IllegalStateException( + "Latest Account password-reset receipt request digest is inconsistent"); + } + requireReceiptNotAhead( + receipt.accountAuthorityGeneration(), + receipt.accountSourceVersion(), + receipt.issuanceFence(), + receipt.issuanceFenceSourceVersion(), + current, + "Password-reset"); + } + + private void requireCurrentPasswordVerifier(Account account, PasswordResetReceipt receipt) { + String currentVerifier = account.getPasswordHash(); + if (currentVerifier == null + || currentVerifier.isBlank() + || !constantTimeTextEquals(sha256Hex(currentVerifier), receipt.passwordVerifierDigest())) { + throw new IllegalStateException( + "Latest Account password-reset event does not match the current password verifier"); + } + } + + private void requireLogoutAllReceipt( + Account account, + LogoutAllReceipt receipt, + Event event, + VerifiedSourceEvent verified, + ScopeState current) { + UUID requestId = parseLogoutAllRequestId(verified.requestId()); + if (!requestId.toString().equals(verified.requestId()) + || !requestId.equals(receipt.requestId()) + || receipt.accountId() != account.getId() + || !account.getAccountUuid().equals(receipt.accountUuid()) + || !LOGOUT_ALL_OPERATION_KIND.equals(receipt.operationKind()) + || receipt.requestDigestVersion() != 1 + || !receipt.lifecycleResult().equals(LOGOUT_ALL_RESULT) + || !streamKey(account.getAccountUuid()).equals(receipt.outboxStreamKey()) + || receipt.outboxSequence() != event.outboxSequence() + || !receipt.requestId().toString().equals(event.requestId()) + || !receipt.eventId().equals(event.eventId()) + || !receipt.eventDigest().equals(event.eventDigest()) + || !receipt.eventId().equals(LOGOUT_ALL_EVENT_ID_PREFIX + receipt.requestId()) + || !Long.toString(receipt.accountAuthorityGeneration()) + .equals(verified.accountAuthorityGeneration()) + || !Long.toString(receipt.accountSourceVersion()).equals(verified.sourceVersion())) { + throw new IllegalStateException("Latest Account logout-all receipt does not match its event"); + } + String expectedRequestDigest = + AccountLogoutRequestDigest.accountLogoutAll( + receipt.accountUuid(), receipt.tokenProfile(), receipt.presentedTokenHash()); + if (!constantTimeTextEquals(expectedRequestDigest, receipt.requestDigest())) { + throw new IllegalStateException( + "Account logout-all receipt request digest does not match its immutable caller bindings"); + } + requireReceiptNotAhead( + receipt.accountAuthorityGeneration(), + receipt.accountSourceVersion(), + receipt.issuanceFence(), + receipt.issuanceFenceSourceVersion(), + current, + "Logout-all"); + } + + private UUID parseLogoutAllRequestId(String requestIdText) { + UUID requestId; + try { + requestId = UUID.fromString(requestIdText); + } catch (IllegalArgumentException exception) { + throw new IllegalStateException("Logout-all source request ID is malformed", exception); + } + if (!requestId.toString().equals(requestIdText)) { + throw new IllegalStateException("Logout-all source request ID is not canonical"); + } + return requestId; + } + + private static VerifiedSourceEvent verifyEvent(Event event, UUID accountUuid) { + if (event == null) throw new IllegalStateException("Account source event is missing"); + String payload = new String(event.payload(), StandardCharsets.UTF_8); + try { + JsonNode tree = SNAPSHOT_JSON.readTree(payload); + if (tree == null || !tree.isObject() || !tree.path("schemaVersion").isTextual()) { + throw new IllegalStateException("Account source event schema is missing"); + } + return switch (tree.path("schemaVersion").textValue()) { + case PasswordResetAuthorityEventV1Codec.SCHEMA_VERSION -> { + var reset = PasswordResetAuthorityEventV1Codec.verify(payload); + requireEventBinding( + event, + accountUuid, + reset.accountId(), + reset.requestId(), + reset.eventId(), + reset.eventDigest(), + reset.outboxStreamKey(), + reset.outboxSequence(), + reset.canonicalJsonUtf8()); + yield VerifiedSourceEvent.passwordReset(reset); + } + case AccountLogoutAllAuthorityEventV1Codec.SCHEMA_VERSION -> { + var logout = AccountLogoutAllAuthorityEventV1Codec.verify(payload); + requireEventBinding( + event, + accountUuid, + logout.accountId(), + logout.requestId(), + logout.eventId(), + logout.eventDigest(), + logout.outboxStreamKey(), + logout.outboxSequence(), + logout.canonicalJsonUtf8()); + yield VerifiedSourceEvent.logoutAll(logout); + } + case AccountSecurityStateAuthorityEventV1Codec.SCHEMA_VERSION -> { + var security = AccountSecurityStateAuthorityEventV1Codec.verify(payload); + requireEventBinding( + event, + accountUuid, + security.accountId(), + security.requestId(), + security.eventId(), + security.eventDigest(), + security.outboxStreamKey(), + security.outboxSequence(), + security.canonicalJsonUtf8()); + yield VerifiedSourceEvent.securityState(security); + } + default -> throw new IllegalStateException("Account source event schema is unsupported"); + }; + } catch (IOException | IllegalArgumentException invalid) { + throw new IllegalStateException("Account source event is invalid", invalid); + } + } + + private static void requireEventBinding( + Event event, + UUID accountUuid, + String accountId, + String requestId, + String eventId, + String digest, + String stream, + String sequence, + byte[] canonical) { + if (!MessageDigest.isEqual(event.payload(), canonical) + || !accountUuid.toString().equals(accountId) + || !event.requestId().equals(requestId) + || !event.eventId().equals(eventId) + || !event.eventDigest().equals(digest) + || !event.outboxStreamKey().equals(stream) + || !Long.toString(event.outboxSequence()).equals(sequence)) { + throw new IllegalStateException("Account source event readback is inconsistent"); + } + } + + /** Structural binding only; owner receipt proof is checked separately. */ + static void requireEventMatchesSnapshot( + Event event, UUID accountUuid, ScopeState current, boolean mustBeCurrentLatest) { + if (accountUuid == null + || current == null + || !AuthorityScope.account(accountUuid).equals(current.scope()) + || current.generation() <= 0L + || current.sourceVersion() <= 0L) { + throw new IllegalStateException("Account source snapshot scope or counters are invalid"); + } + SnapshotCounters verified = verifySnapshotEvent(event, accountUuid); + BigInteger eventGeneration = new BigInteger(verified.accountAuthorityGeneration()); + BigInteger eventSourceVersion = new BigInteger(verified.sourceVersion()); + BigInteger currentGeneration = BigInteger.valueOf(current.generation()); + BigInteger currentSourceVersion = BigInteger.valueOf(current.sourceVersion()); + boolean countersMatch = + mustBeCurrentLatest + ? eventGeneration.equals(currentGeneration) + && eventSourceVersion.equals(currentSourceVersion) + : eventGeneration.compareTo(currentGeneration) <= 0 + && eventSourceVersion.compareTo(currentSourceVersion) <= 0; + if (!countersMatch) { + throw new IllegalStateException( + "Account source event counters contradict or lead the current snapshot"); + } + } + + private static SnapshotCounters verifySnapshotEvent(Event event, UUID accountUuid) { + VerifiedSourceEvent verified = verifyEvent(event, accountUuid); + return new SnapshotCounters(verified.accountAuthorityGeneration(), verified.sourceVersion()); + } + + private record SnapshotCounters(String accountAuthorityGeneration, String sourceVersion) {} + + private void requireReceiptNotAhead( + long generation, + long sourceVersion, + long fence, + long fenceSourceVersion, + ScopeState current, + String operation) { + IssuanceFence currentFence = current.issuanceFence(); + if (generation > current.generation() + || sourceVersion > current.sourceVersion() + || fence > currentFence.value() + || fenceSourceVersion > currentFence.sourceVersion()) { + throw new IllegalStateException(operation + " receipt is ahead of current Account authority"); + } + } + + private void requireCurrentFence(IssuanceFence fence, UUID accountUuid) { + if (fence == null + || !accountUuid.equals(fence.accountId()) + || fence.value() <= 0L + || fence.sourceVersion() <= 0L) { + throw new IllegalStateException("Account source issuance fence is missing or invalid"); + } + } + + private void requireAccountAssociation(Account account) { + AccountIdentityProvenance provenance = + account == null ? null : account.getAccountUuidProvenance(); + if (account == null + || account.getId() == null + || account.getId() <= 0L + || account.getAccountUuid() == null + || new UUID(0L, 0L).equals(account.getAccountUuid()) + || account.getAccountUuidSourceNumericId() == null + || !account.getId().equals(account.getAccountUuidSourceNumericId()) + || (provenance != AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT + && provenance != AccountIdentityProvenance.ACCOUNT_V29_MIGRATION + && provenance != AccountIdentityProvenance.ACCOUNT_DATABASE_INSERT)) { + throw new IllegalStateException("Verified persisted Account association is required"); + } + } + + private void requireCheckpointMatches(Checkpoint checkpoint, Event event) { + if (!checkpoint.outboxStreamKey().equals(event.outboxStreamKey()) + || checkpoint.outboxSequence() != event.outboxSequence() + || !checkpoint.sourceEventId().equals(event.eventId()) + || !checkpoint.sourceEventDigest().equals(event.eventDigest())) { + throw new IllegalStateException("Account source checkpoint differs from its latest event"); + } + } + + private String streamKey(UUID accountUuid) { + return STREAM_PREFIX + accountUuid; + } + + private String passwordResetRequestDigest( + UUID accountUuid, String tokenHash, String tokenExpiresAt, String verifierDigest) { + try { + MessageDigest digest = MessageDigest.getInstance("SHA-256"); + updateLengthPrefixed(digest, PASSWORD_RESET_REQUEST_DOMAIN); + updateLengthPrefixed(digest, PASSWORD_RESET_OPERATION_KIND); + updateLengthPrefixed(digest, accountUuid.toString()); + updateLengthPrefixed(digest, tokenHash); + updateLengthPrefixed(digest, tokenExpiresAt); + updateLengthPrefixed(digest, verifierDigest); + return HexFormat.of().formatHex(digest.digest()); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + private void updateLengthPrefixed(MessageDigest digest, String value) { + if (value == null) { + throw new IllegalArgumentException("Password-reset request field is required"); + } + byte[] encoded = value.getBytes(StandardCharsets.UTF_8); + digest.update(ByteBuffer.allocate(Integer.BYTES).putInt(encoded.length).array()); + digest.update(encoded); + } + + private String sha256Hex(String value) { + try { + return HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256").digest(value.getBytes(StandardCharsets.UTF_8))); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + private boolean constantTimeTextEquals(String left, String right) { + return left != null + && right != null + && MessageDigest.isEqual( + left.getBytes(StandardCharsets.US_ASCII), right.getBytes(StandardCharsets.US_ASCII)); + } + + /** Current exact source checkpoint; empty event is legal only for the proven 1/1 baseline. */ + public record LatestSourceSnapshot(long outboxSequence, Optional latestEvent) { + public LatestSourceSnapshot { + latestEvent = Objects.requireNonNull(latestEvent, "latest source event optional is required"); + if (outboxSequence < 0L + || (outboxSequence == 0L && latestEvent.isPresent()) + || (outboxSequence > 0L + && (latestEvent.isEmpty() + || latestEvent.orElseThrow().outboxSequence() != outboxSequence))) { + throw new IllegalArgumentException("Account latest source snapshot is inconsistent"); + } + } + } + + /** Exact closed-schema source counters and cutoff returned only after receipt validation. */ + public record RetainedEventEvidence( + String outboxStreamKey, + long outboxSequence, + long accountAuthorityGeneration, + long sourceVersion, + long issuanceFence, + long issuanceFenceSourceVersion, + AccountSecurityCutoff accountSecurityCutoff) { + public RetainedEventEvidence { + if (outboxStreamKey == null + || outboxSequence <= 0L + || accountAuthorityGeneration <= 0L + || sourceVersion <= 0L + || issuanceFence != accountAuthorityGeneration + || issuanceFenceSourceVersion != sourceVersion + || accountSecurityCutoff == null + || !outboxStreamKey.equals(accountSecurityCutoff.outboxStreamKey()) + || outboxSequence != Long.parseLong(accountSecurityCutoff.outboxSequence()) + || accountAuthorityGeneration + != Long.parseLong(accountSecurityCutoff.accountAuthorityGeneration())) { + throw new IllegalArgumentException("Retained Account source evidence is inconsistent"); + } + } + } + + private record VerifiedSourceEvent( + String requestId, + String accountAuthorityGeneration, + String sourceVersion, + AccountSecurityCutoff accountSecurityCutoff, + Optional passwordReset, + Optional + securityState) { + private static VerifiedSourceEvent passwordReset(PasswordResetAuthorityEvent event) { + return new VerifiedSourceEvent( + event.requestId(), + event.accountAuthorityGeneration(), + event.sourceVersion(), + new AccountSecurityCutoff( + event.accountSecurityCutoff().accountAuthorityGeneration(), + event.accountSecurityCutoff().outboxStreamKey(), + event.accountSecurityCutoff().outboxSequence()), + Optional.of(event), + Optional.empty()); + } + + private static VerifiedSourceEvent logoutAll(AccountLogoutAllAuthorityEvent event) { + return new VerifiedSourceEvent( + event.requestId(), + event.accountAuthorityGeneration(), + event.sourceVersion(), + new AccountSecurityCutoff( + event.accountSecurityCutoff().accountAuthorityGeneration(), + event.accountSecurityCutoff().outboxStreamKey(), + event.accountSecurityCutoff().outboxSequence()), + Optional.empty(), + Optional.empty()); + } + + private static VerifiedSourceEvent securityState( + AccountSecurityStateAuthorityEventV1Codec.AccountSecurityStateAuthorityEvent event) { + return new VerifiedSourceEvent( + event.requestId(), + event.accountAuthorityGeneration(), + event.sourceVersion(), + new AccountSecurityCutoff( + event.accountSecurityCutoff().accountAuthorityGeneration(), + event.accountSecurityCutoff().outboxStreamKey(), + event.accountSecurityCutoff().outboxSequence()), + Optional.empty(), + Optional.of(event)); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceReader.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceReader.java new file mode 100644 index 0000000000..104217fe25 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceReader.java @@ -0,0 +1,237 @@ +package net.firedevops.firemud.accountservice.service; + +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeState; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Event; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Unwired owner-local reader for current and selected historical Account authority source events. + * Returned source evidence is not recipient authority. + */ +public final class AccountAuthoritySourceReader { + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final String ACCOUNT_STREAM_PREFIX = "account:auth-authority:v1:account/"; + + private final AccountRepository accountRepository; + private final AccountAuthorityGenerationRepository generationRepository; + private final AccountAuthorityOutboxRepository outboxRepository; + private final AccountAuthoritySourceEventReadback sourceEventReadback; + private final TransactionTemplate ownerTransaction; + + public AccountAuthoritySourceReader( + AccountRepository accountRepository, + AccountAuthorityGenerationRepository generationRepository, + AccountAuthorityOutboxRepository outboxRepository, + AccountAuthoritySourceEventReadback sourceEventReadback, + PlatformTransactionManager transactionManager) { + this.accountRepository = + Objects.requireNonNull(accountRepository, "Account repository is required"); + this.generationRepository = + Objects.requireNonNull(generationRepository, "authority generation repository is required"); + this.outboxRepository = + Objects.requireNonNull(outboxRepository, "authority outbox repository is required"); + this.sourceEventReadback = + Objects.requireNonNull(sourceEventReadback, "source event readback is required"); + + this.ownerTransaction = + new TransactionTemplate( + Objects.requireNonNull(transactionManager, "Account transaction manager is required")); + this.ownerTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + this.ownerTransaction.setReadOnly(false); + } + + /** Reads the current positive Account source and its exact latest event, if one exists. */ + public AccountSourceSnapshot readCurrent(UUID accountId) { + requireCanonicalAccountId(accountId); + requireNoAmbientTransaction(); + return requireTransactionResult( + ownerTransaction.execute( + status -> readCurrentSnapshot(loadLockedAccount(accountId), accountId))); + } + + /** + * Reads one positive immutable event from this Account stream together with the current source + * snapshot that fences its use. + */ + public AccountSourceEventReadback readCommittedEvent(UUID accountId, long outboxSequence) { + requireCanonicalAccountId(accountId); + if (outboxSequence <= 0L) { + throw new IllegalArgumentException("A positive Account source event sequence is required"); + } + requireNoAmbientTransaction(); + return requireTransactionResult( + ownerTransaction.execute( + status -> { + Account account = loadLockedAccount(accountId); + AccountSourceSnapshot current = readCurrentSnapshot(account, accountId); + if (outboxSequence > current.outboxSequence()) { + throw new IllegalStateException( + "Selected Account source event is ahead of its current checkpoint"); + } + Event requested = + outboxRepository + .findEvent(current.outboxStreamKey(), outboxSequence) + .orElseThrow( + () -> + new IllegalStateException( + "Selected Account source event is missing")); + if (!current.outboxStreamKey().equals(requested.outboxStreamKey()) + || requested.outboxSequence() != outboxSequence) { + throw new IllegalStateException( + "Selected Account source event identity changed during readback"); + } + sourceEventReadback.requireRetainedEvent(account, requested, current.sourceState()); + return new AccountSourceEventReadback(current, requested); + })); + } + + private AccountSourceSnapshot readCurrentSnapshot(Account account, UUID accountId) { + AuthorityScope scope = AuthorityScope.account(accountId); + ScopeState state = generationRepository.read(scope); + if (state == null || !scope.equals(state.scope())) { + throw new IllegalStateException("Current Account authority scope changed during readback"); + } + AccountAuthoritySourceEventReadback.LatestSourceSnapshot latest = + sourceEventReadback.requireCurrentLatest(account, state); + return new AccountSourceSnapshot( + accountId, + state, + accountStreamKey(accountId), + latest.outboxSequence(), + latest.latestEvent()); + } + + private Account loadLockedAccount(UUID accountId) { + Account associated = + accountRepository + .findByAccountUuid(accountId) + .orElseThrow( + () -> new IllegalStateException("Persisted Account UUID association is missing")); + requirePersistedAssociation(associated, accountId); + + Account locked = + accountRepository + .findByIdForUpdate(associated.getId()) + .orElseThrow( + () -> new IllegalStateException("Persisted Account source row is missing")); + requirePersistedAssociation(locked, accountId); + if (!Objects.equals(associated.getId(), locked.getId()) + || !Objects.equals(associated.getAccountUuid(), locked.getAccountUuid()) + || associated.getAccountUuidProvenance() != locked.getAccountUuidProvenance() + || !Objects.equals( + associated.getAccountUuidSourceNumericId(), locked.getAccountUuidSourceNumericId())) { + throw new IllegalStateException( + "Locked Account row changed its exact UUID association or provenance"); + } + return locked; + } + + private void requirePersistedAssociation(Account account, UUID accountId) { + AccountIdentityProvenance provenance = + account == null ? null : account.getAccountUuidProvenance(); + if (account == null + || account.getId() == null + || account.getId() <= 0L + || !accountId.equals(account.getAccountUuid()) + || account.getAccountUuidSourceNumericId() == null + || !account.getId().equals(account.getAccountUuidSourceNumericId()) + || (provenance != AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT + && provenance != AccountIdentityProvenance.ACCOUNT_V29_MIGRATION + && provenance != AccountIdentityProvenance.ACCOUNT_DATABASE_INSERT)) { + throw new IllegalStateException("Verified persisted Account association is required"); + } + } + + private static void requireCanonicalAccountId(UUID accountId) { + if (accountId == null || NIL_UUID.equals(accountId)) { + throw new IllegalArgumentException("A canonical non-nil Account UUID is required"); + } + } + + private static void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Account authority source reader must own its transaction without an ambient transaction"); + } + } + + private static T requireTransactionResult(T result) { + if (result == null) { + throw new IllegalStateException("Account authority source readback returned no result"); + } + return result; + } + + private static String accountStreamKey(UUID accountId) { + return ACCOUNT_STREAM_PREFIX + accountId; + } + + /** Immutable current owner-local source snapshot; it carries no credential or recipient tuple. */ + public record AccountSourceSnapshot( + UUID accountId, + ScopeState sourceState, + String outboxStreamKey, + long outboxSequence, + Optional latestEvent) { + public AccountSourceSnapshot { + requireCanonicalAccountId(accountId); + Objects.requireNonNull(sourceState, "Account source state is required"); + Objects.requireNonNull(outboxStreamKey, "Account source stream key is required"); + latestEvent = Objects.requireNonNull(latestEvent, "latest source event optional is required"); + AuthorityScope expectedScope = AuthorityScope.account(accountId); + if (!expectedScope.equals(sourceState.scope()) + || sourceState.generation() <= 0L + || sourceState.sourceVersion() <= 0L + || !outboxStreamKey.equals(accountStreamKey(accountId)) + || sourceState.issuanceFence() == null + || !accountId.equals(sourceState.issuanceFence().accountId()) + || sourceState.issuanceFence().value() <= 0L + || sourceState.issuanceFence().sourceVersion() <= 0L + || outboxSequence < 0L + || (outboxSequence == 0L + && (sourceState.generation() != 1L + || sourceState.sourceVersion() != 1L + || latestEvent.isPresent())) + || (outboxSequence > 0L + && (sourceState.generation() <= 1L + || sourceState.sourceVersion() <= 1L + || latestEvent.isEmpty() + || latestEvent.orElseThrow().outboxSequence() != outboxSequence + || !outboxStreamKey.equals(latestEvent.orElseThrow().outboxStreamKey())))) { + throw new IllegalArgumentException("Account source snapshot is inconsistent"); + } + latestEvent.ifPresent( + event -> + AccountAuthoritySourceEventReadback.requireEventMatchesSnapshot( + event, accountId, sourceState, true)); + } + } + + /** Immutable selected event paired with the current Account source fence. */ + public record AccountSourceEventReadback( + AccountSourceSnapshot currentSnapshot, Event requestedEvent) { + public AccountSourceEventReadback { + Objects.requireNonNull(currentSnapshot, "current Account source snapshot is required"); + Objects.requireNonNull(requestedEvent, "selected Account source event is required"); + if (requestedEvent.outboxSequence() <= 0L + || requestedEvent.outboxSequence() > currentSnapshot.outboxSequence() + || !currentSnapshot.outboxStreamKey().equals(requestedEvent.outboxStreamKey())) { + throw new IllegalArgumentException("Selected Account source event is inconsistent"); + } + AccountAuthoritySourceEventReadback.requireEventMatchesSnapshot( + requestedEvent, currentSnapshot.accountId(), currentSnapshot.sourceState(), false); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountGenerationProjection.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountGenerationProjection.java new file mode 100644 index 0000000000..3dcf25d099 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountGenerationProjection.java @@ -0,0 +1,355 @@ +package net.firedevops.firemud.accountservice.service; + +import com.fasterxml.jackson.core.JsonFactory; +import com.fasterxml.jackson.core.StreamReadFeature; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import java.io.IOException; +import java.math.BigInteger; +import java.nio.ByteBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.util.HashSet; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeKind; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Event; +import net.firedevops.firemud.accountservice.service.AccountAuthoritySourceReader.AccountSourceSnapshot; +import net.firedevops.firemud.common.account.authority.AccountLogoutAllAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.AccountLogoutAllAuthorityEventV1Codec.AccountLogoutAllAuthorityEvent; +import net.firedevops.firemud.common.account.authority.AccountSecurityStateAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.PasswordResetAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.PasswordResetAuthorityEventV1Codec.PasswordResetAuthorityEvent; + +/** Closed current-snapshot projection of one durable Account account-generation source. */ +public record AccountGenerationProjection( + String accountId, + String accountAuthorityGeneration, + String sourceVersion, + String outboxStreamKey, + String outboxSequence, + Optional sourceEvent) { + public static final String SCHEMA_VERSION = "account-auth-account-generation-projection/v1"; + public static final String KEY_PREFIX = "session:auth:generation:account:"; + private static final String STREAM_PREFIX = "account:auth-authority:v1:account/"; + private static final Pattern POSITIVE_DECIMAL = Pattern.compile("[1-9][0-9]*"); + private static final Pattern NON_NEGATIVE_DECIMAL = Pattern.compile("0|[1-9][0-9]*"); + private static final ObjectMapper JSON = + new ObjectMapper( + JsonFactory.builder().enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION).build()) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS); + private static final Set REQUIRED_FIELDS = + Set.of( + "schemaVersion", + "accountId", + "accountAuthorityGeneration", + "sourceVersion", + "outboxStreamKey", + "outboxSequence"); + private static final Set ALL_FIELDS = + Set.of( + "schemaVersion", + "accountId", + "accountAuthorityGeneration", + "sourceVersion", + "outboxStreamKey", + "outboxSequence", + "sourceEvent"); + + public AccountGenerationProjection { + requireCanonicalAccountId(accountId); + requirePositiveDecimal(accountAuthorityGeneration, "accountAuthorityGeneration"); + requirePositiveDecimal(sourceVersion, "sourceVersion"); + requireNonNegativeDecimal(outboxSequence, "outboxSequence"); + if (!streamKeyForAccount(accountId).equals(outboxStreamKey)) { + throw new IllegalArgumentException( + "Account generation projection stream key is not canonical"); + } + sourceEvent = Objects.requireNonNull(sourceEvent, "sourceEvent optional is required"); + BigInteger sequence = new BigInteger(outboxSequence); + if (sequence.signum() == 0) { + if (!"1".equals(accountAuthorityGeneration) + || !"1".equals(sourceVersion) + || sourceEvent.isPresent()) { + throw new IllegalArgumentException( + "Account sequence zero requires the original 1/1 source baseline and no event"); + } + } else { + if (new BigInteger(accountAuthorityGeneration).compareTo(BigInteger.ONE) <= 0 + || new BigInteger(sourceVersion).compareTo(BigInteger.ONE) <= 0 + || sourceEvent.isEmpty()) { + throw new IllegalArgumentException( + "Positive Account source sequence requires advanced counters and its exact event"); + } + validateSourceEvent( + sourceEvent.orElseThrow(), + accountId, + accountAuthorityGeneration, + sourceVersion, + outboxStreamKey, + outboxSequence); + } + } + + /** Builds projection evidence only from Account's owner-local current durable readback. */ + public static AccountGenerationProjection fromSource(AccountSourceSnapshot source) { + Objects.requireNonNull(source, "Account source snapshot is required"); + AuthorityScope scope = source.sourceState().scope(); + if (scope.kind() != ScopeKind.ACCOUNT || !source.accountId().equals(scope.accountId())) { + throw new IllegalArgumentException("Account source snapshot has a different authority scope"); + } + Optional event = + source.latestEvent().map(AccountGenerationProjection::decodeCanonicalEvent); + return new AccountGenerationProjection( + source.accountId().toString(), + Long.toString(source.sourceState().generation()), + Long.toString(source.sourceState().sourceVersion()), + source.outboxStreamKey(), + Long.toString(source.outboxSequence()), + event); + } + + /** + * Parses the closed wire shape and rejects noncanonical JSON and all alternate representations. + */ + public static AccountGenerationProjection parse(String json) { + Objects.requireNonNull(json, "projection JSON is required"); + final JsonNode root; + try { + root = JSON.readTree(json); + } catch (IOException exception) { + throw new IllegalArgumentException( + "Account generation projection JSON is malformed", exception); + } + if (!(root instanceof ObjectNode object)) { + throw new IllegalArgumentException("Account generation projection must be a JSON object"); + } + Set fields = new HashSet<>(); + object.fieldNames().forEachRemaining(fields::add); + if (!fields.contains("sourceEvent") && !fields.equals(REQUIRED_FIELDS)) { + throw new IllegalArgumentException( + "Account generation projection has unknown or missing fields"); + } + if (fields.contains("sourceEvent") && !fields.equals(ALL_FIELDS)) { + throw new IllegalArgumentException( + "Account generation projection has unknown or missing fields"); + } + if (!SCHEMA_VERSION.equals(requireText(object, "schemaVersion"))) { + throw new IllegalArgumentException( + "Account generation projection schemaVersion is unsupported"); + } + Optional event = + fields.contains("sourceEvent") + ? Optional.of(requireText(object, "sourceEvent")) + : Optional.empty(); + AccountGenerationProjection projection = + new AccountGenerationProjection( + requireText(object, "accountId"), + requireText(object, "accountAuthorityGeneration"), + requireText(object, "sourceVersion"), + requireText(object, "outboxStreamKey"), + requireText(object, "outboxSequence"), + event); + if (!projection.toJson().equals(json)) { + throw new IllegalArgumentException("Account generation projection JSON is not canonical"); + } + return projection; + } + + public String key() { + return KEY_PREFIX + accountId; + } + + public String toJson() { + ObjectNode object = JSON.createObjectNode(); + object.put("schemaVersion", SCHEMA_VERSION); + object.put("accountId", accountId); + object.put("accountAuthorityGeneration", accountAuthorityGeneration); + object.put("sourceVersion", sourceVersion); + object.put("outboxStreamKey", outboxStreamKey); + object.put("outboxSequence", outboxSequence); + sourceEvent.ifPresent(value -> object.put("sourceEvent", value)); + try { + return JSON.writeValueAsString(object); + } catch (IOException exception) { + throw new IllegalStateException( + "Account generation projection cannot be serialized", exception); + } + } + + public BigInteger generationValue() { + return new BigInteger(accountAuthorityGeneration); + } + + public BigInteger sourceVersionValue() { + return new BigInteger(sourceVersion); + } + + public BigInteger outboxSequenceValue() { + return new BigInteger(outboxSequence); + } + + static String keyForAccount(UUID accountId) { + Objects.requireNonNull(accountId, "Account UUID is required"); + if (new UUID(0L, 0L).equals(accountId)) { + throw new IllegalArgumentException("A canonical non-nil Account UUID is required"); + } + return KEY_PREFIX + accountId; + } + + private static String streamKeyForAccount(String accountId) { + return STREAM_PREFIX + accountId; + } + + private static String decodeCanonicalEvent(Event event) { + try { + return StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(event.payload())) + .toString(); + } catch (CharacterCodingException exception) { + throw new IllegalArgumentException("Account source event is not valid UTF-8", exception); + } + } + + private static void validateSourceEvent( + String eventJson, + String accountId, + String generation, + String sourceVersion, + String streamKey, + String sequence) { + final JsonNode root; + try { + root = JSON.readTree(eventJson); + } catch (IOException exception) { + throw new IllegalArgumentException("Account source event JSON is malformed", exception); + } + if (!(root instanceof ObjectNode object)) { + throw new IllegalArgumentException("Account source event must be a JSON object"); + } + String canonicalEvent; + switch (requireText(object, "schemaVersion")) { + case PasswordResetAuthorityEventV1Codec.SCHEMA_VERSION -> { + PasswordResetAuthorityEvent reset = PasswordResetAuthorityEventV1Codec.verify(eventJson); + canonicalEvent = new String(reset.canonicalJsonUtf8(), StandardCharsets.UTF_8); + requireEventBinding( + accountId, + generation, + sourceVersion, + streamKey, + sequence, + reset.accountId(), + reset.accountAuthorityGeneration(), + reset.sourceVersion(), + reset.outboxStreamKey(), + reset.outboxSequence()); + } + case AccountLogoutAllAuthorityEventV1Codec.SCHEMA_VERSION -> { + AccountLogoutAllAuthorityEvent logout = + AccountLogoutAllAuthorityEventV1Codec.verify(eventJson); + canonicalEvent = new String(logout.canonicalJsonUtf8(), StandardCharsets.UTF_8); + requireEventBinding( + accountId, + generation, + sourceVersion, + streamKey, + sequence, + logout.accountId(), + logout.accountAuthorityGeneration(), + logout.sourceVersion(), + logout.outboxStreamKey(), + logout.outboxSequence()); + } + case AccountSecurityStateAuthorityEventV1Codec.SCHEMA_VERSION -> { + var security = AccountSecurityStateAuthorityEventV1Codec.verify(eventJson); + canonicalEvent = security.canonicalJson(); + requireEventBinding( + accountId, + generation, + sourceVersion, + streamKey, + sequence, + security.accountId(), + security.accountAuthorityGeneration(), + security.sourceVersion(), + security.outboxStreamKey(), + security.outboxSequence()); + } + default -> { + throw new IllegalArgumentException( + "Account source event is not one of the declared closed schemas"); + } + } + if (!canonicalEvent.equals(eventJson)) { + throw new IllegalArgumentException("Account source event JSON is not canonical"); + } + } + + private static void requireEventBinding( + String expectedAccount, + String expectedGeneration, + String expectedSourceVersion, + String expectedStream, + String expectedSequence, + String actualAccount, + String actualGeneration, + String actualSourceVersion, + String actualStream, + String actualSequence) { + if (!expectedAccount.equals(actualAccount) + || !expectedGeneration.equals(actualGeneration) + || !expectedSourceVersion.equals(actualSourceVersion) + || !expectedStream.equals(actualStream) + || !expectedSequence.equals(actualSequence)) { + throw new IllegalArgumentException( + "Account source event does not match its current projection checkpoint"); + } + } + + private static String requireText(ObjectNode object, String field) { + JsonNode value = object.get(field); + if (value == null || !value.isTextual()) { + throw new IllegalArgumentException( + "Account generation projection " + field + " must be a string"); + } + return value.textValue(); + } + + private static void requireCanonicalAccountId(String value) { + Objects.requireNonNull(value, "accountId is required"); + try { + UUID parsed = UUID.fromString(value); + if (!parsed.toString().equals(value) || new UUID(0L, 0L).equals(parsed)) { + throw new IllegalArgumentException( + "Account generation projection accountId is not canonical"); + } + } catch (IllegalArgumentException malformed) { + throw new IllegalArgumentException( + "Account generation projection accountId must be a lowercase canonical non-nil UUID", + malformed); + } + } + + private static void requirePositiveDecimal(String value, String field) { + if (value == null || !POSITIVE_DECIMAL.matcher(value).matches()) { + throw new IllegalArgumentException(field + " must be a positive canonical decimal string"); + } + } + + private static void requireNonNegativeDecimal(String value, String field) { + if (value == null || !NON_NEGATIVE_DECIMAL.matcher(value).matches()) { + throw new IllegalArgumentException( + field + " must be a non-negative canonical decimal string"); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/IssuerGenerationProjection.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/IssuerGenerationProjection.java new file mode 100644 index 0000000000..543a77eea2 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/IssuerGenerationProjection.java @@ -0,0 +1,258 @@ +package net.firedevops.firemud.accountservice.service; + +import com.fasterxml.jackson.core.JsonFactory; +import com.fasterxml.jackson.core.StreamReadFeature; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import java.io.IOException; +import java.math.BigInteger; +import java.util.HashSet; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeKind; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository.CurrentSourceEvidence; +import net.firedevops.firemud.common.account.authority.IssuerGenerationAuthorityEventV1Codec; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; + +/** Closed Account-owned current issuer projection; not recipient or token authorization. */ +public record IssuerGenerationProjection( + String issuerId, + String issuerAuthGeneration, + String sourceVersion, + String outboxStreamKey, + String lastAppliedSourceOutboxSequence, + Optional lastAppliedSourceEventId, + Optional lastAppliedSourceEventDigest, + Optional sourceEvent) { + public static final String SCHEMA_VERSION = "account-auth-issuer-generation-projection/v1"; + public static final String KEY_PREFIX = "session:auth:generation:issuer:"; + private static final String STREAM = + "account:auth-authority:v1:issuer/" + GameSessionAccountDelegationProfile.ISSUER; + private static final Set BASE_FIELDS = + Set.of( + "schemaVersion", + "issuerId", + "issuerAuthGeneration", + "sourceVersion", + "outboxStreamKey", + "lastAppliedSourceOutboxSequence"); + private static final Set EVENT_FIELDS = + Set.of( + "schemaVersion", + "issuerId", + "issuerAuthGeneration", + "sourceVersion", + "outboxStreamKey", + "lastAppliedSourceOutboxSequence", + "lastAppliedSourceEventId", + "lastAppliedSourceEventDigest", + "sourceEvent"); + private static final ObjectMapper JSON = + new ObjectMapper( + JsonFactory.builder().enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION).build()) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS); + + public IssuerGenerationProjection { + keyForIssuer(issuerId); + positive(issuerAuthGeneration); + positive(sourceVersion); + if (lastAppliedSourceOutboxSequence == null + || !lastAppliedSourceOutboxSequence.matches("0|[1-9][0-9]*") + || !STREAM.equals(outboxStreamKey)) { + throw new IllegalArgumentException("Issuer projection stream/checkpoint is not canonical"); + } + lastAppliedSourceEventId = Objects.requireNonNull(lastAppliedSourceEventId); + lastAppliedSourceEventDigest = Objects.requireNonNull(lastAppliedSourceEventDigest); + sourceEvent = Objects.requireNonNull(sourceEvent); + if (new BigInteger(lastAppliedSourceOutboxSequence).signum() == 0) { + if (!"1".equals(issuerAuthGeneration) + || !"1".equals(sourceVersion) + || lastAppliedSourceEventId.isPresent() + || lastAppliedSourceEventDigest.isPresent() + || sourceEvent.isPresent()) { + throw new IllegalArgumentException( + "Issuer sequence zero requires original 1/1 and no event"); + } + } else { + if (new BigInteger(issuerAuthGeneration).compareTo(BigInteger.ONE) <= 0 + || new BigInteger(sourceVersion).compareTo(BigInteger.ONE) <= 0 + || lastAppliedSourceEventId.isEmpty() + || lastAppliedSourceEventDigest.isEmpty() + || sourceEvent.isEmpty()) { + throw new IllegalArgumentException( + "Advanced issuer projection requires complete event evidence"); + } + var event = IssuerGenerationAuthorityEventV1Codec.verify(sourceEvent.orElseThrow()); + if (!sourceEvent.orElseThrow().equals(event.canonicalJson()) + || !issuerId.equals(event.issuerId()) + || !("issuer/" + issuerId).equals(event.sourceScope()) + || !issuerAuthGeneration.equals(event.issuerAuthGeneration()) + || !sourceVersion.equals(event.sourceVersion()) + || !outboxStreamKey.equals(event.outboxStreamKey()) + || !lastAppliedSourceOutboxSequence.equals(event.outboxSequence()) + || !lastAppliedSourceEventId.orElseThrow().equals(event.eventId()) + || !lastAppliedSourceEventDigest.orElseThrow().equals(event.eventDigest())) { + throw new IllegalArgumentException( + "Issuer projection differs from its exact canonical event"); + } + } + } + + /** Adapts only the owner-proved original source; unsupported historical codecs deny. */ + public static IssuerGenerationProjection fromSource( + net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository + .CanonicalIssuerSourceSnapshot + snapshot) { + Objects.requireNonNull(snapshot); + CurrentSourceEvidence source = snapshot.source(); + if (source.checkpoint().sequence() == 0L) return fromSource(source); + if (source.scope().kind() != ScopeKind.ISSUER + || !"ISSUER_SCOPE_INSERT".equals(source.initializationProvenance()) + || source.initializationTransactionId() <= 0L + || source.issuanceFence() != null) { + throw new IllegalArgumentException("Issuer source enrollment is unavailable"); + } + var stored = snapshot.latestEvent().orElseThrow(); + var event = + IssuerGenerationAuthorityEventV1Codec.verify( + new String(stored.payload(), java.nio.charset.StandardCharsets.UTF_8)); + if (!java.util.Arrays.equals(stored.payload(), event.canonicalJsonUtf8()) + || !stored.outboxStreamKey().equals(source.checkpoint().outboxStreamKey()) + || stored.outboxSequence() != source.checkpoint().sequence() + || !source.checkpoint().sourceEventId().equals(Optional.of(stored.eventId())) + || !source.checkpoint().sourceEventDigest().equals(Optional.of(stored.eventDigest())) + || !stored.eventId().equals(event.eventId()) + || !stored.eventDigest().equals(event.eventDigest()) + || !stored.requestId().equals(event.requestId()) + || !stored.eventId().equals("account-issuer-authority-event-v1:" + stored.requestId())) { + throw new IllegalArgumentException( + "Issuer projection event differs from the owned checkpoint"); + } + return new IssuerGenerationProjection( + source.scope().issuerId(), Long.toString(source.generation()), + Long.toString(source.sourceVersion()), source.checkpoint().outboxStreamKey(), + Long.toString(source.checkpoint().sequence()), source.checkpoint().sourceEventId(), + source.checkpoint().sourceEventDigest(), Optional.of(event.canonicalJson())); + } + + /** Original enrollment only; advanced values require their unchanged canonical event bytes. */ + public static IssuerGenerationProjection fromSource(CurrentSourceEvidence source) { + Objects.requireNonNull(source); + if (source.scope().kind() != ScopeKind.ISSUER + || !"ISSUER_SCOPE_INSERT".equals(source.initializationProvenance()) + || source.initializationTransactionId() <= 0L + || source.issuanceFence() != null + || source.checkpoint().sequence() != 0L + || source.checkpoint().sourceEventId().isPresent() + || source.checkpoint().sourceEventDigest().isPresent()) { + throw new IllegalArgumentException( + "Current issuer source cannot prove the canonical issuer event contract"); + } + return new IssuerGenerationProjection( + source.scope().issuerId(), + Long.toString(source.generation()), + Long.toString(source.sourceVersion()), + source.checkpoint().outboxStreamKey(), + Long.toString(source.checkpoint().sequence()), + Optional.empty(), + Optional.empty(), + Optional.empty()); + } + + public static IssuerGenerationProjection parse(String json) { + Objects.requireNonNull(json); + final JsonNode root; + try { + root = JSON.readTree(json); + } catch (IOException failure) { + throw new IllegalArgumentException("Issuer projection JSON is malformed", failure); + } + if (!(root instanceof ObjectNode object)) { + throw new IllegalArgumentException("Issuer projection must be an object"); + } + Set fields = new HashSet<>(); + object.fieldNames().forEachRemaining(fields::add); + if (!fields.equals(BASE_FIELDS) && !fields.equals(EVENT_FIELDS)) { + throw new IllegalArgumentException("Issuer projection has missing or unknown fields"); + } + if (!SCHEMA_VERSION.equals(text(object, "schemaVersion"))) { + throw new IllegalArgumentException("Issuer projection schema is unsupported"); + } + boolean event = fields.equals(EVENT_FIELDS); + var projection = + new IssuerGenerationProjection( + text(object, "issuerId"), + text(object, "issuerAuthGeneration"), + text(object, "sourceVersion"), + text(object, "outboxStreamKey"), + text(object, "lastAppliedSourceOutboxSequence"), + event ? Optional.of(text(object, "lastAppliedSourceEventId")) : Optional.empty(), + event ? Optional.of(text(object, "lastAppliedSourceEventDigest")) : Optional.empty(), + event ? Optional.of(text(object, "sourceEvent")) : Optional.empty()); + if (!projection.toJson().equals(json)) { + throw new IllegalArgumentException("Issuer projection JSON is not canonical"); + } + return projection; + } + + public String toJson() { + ObjectNode object = JSON.createObjectNode(); + object.put("schemaVersion", SCHEMA_VERSION); + object.put("issuerId", issuerId); + object.put("issuerAuthGeneration", issuerAuthGeneration); + object.put("sourceVersion", sourceVersion); + object.put("outboxStreamKey", outboxStreamKey); + object.put("lastAppliedSourceOutboxSequence", lastAppliedSourceOutboxSequence); + lastAppliedSourceEventId.ifPresent(value -> object.put("lastAppliedSourceEventId", value)); + lastAppliedSourceEventDigest.ifPresent( + value -> object.put("lastAppliedSourceEventDigest", value)); + sourceEvent.ifPresent(value -> object.put("sourceEvent", value)); + try { + return JSON.writeValueAsString(object); + } catch (IOException failure) { + throw new IllegalStateException("Issuer projection cannot be serialized", failure); + } + } + + public String key() { + return keyForIssuer(issuerId); + } + + public BigInteger generationValue() { + return new BigInteger(issuerAuthGeneration); + } + + public BigInteger sourceVersionValue() { + return new BigInteger(sourceVersion); + } + + public BigInteger outboxSequenceValue() { + return new BigInteger(lastAppliedSourceOutboxSequence); + } + + public static String keyForIssuer(String issuerId) { + if (!GameSessionAccountDelegationProfile.ISSUER.equals(issuerId)) { + throw new IllegalArgumentException( + "Issuer projection must bind the configured Account issuer"); + } + return KEY_PREFIX + issuerId; + } + + private static String text(ObjectNode object, String field) { + JsonNode value = object.get(field); + if (value == null || !value.isTextual()) { + throw new IllegalArgumentException("Issuer projection field must be a string: " + field); + } + return value.textValue(); + } + + private static void positive(String value) { + if (value == null || !value.matches("[1-9][0-9]*")) { + throw new IllegalArgumentException( + "Issuer projection counter must be a positive canonical decimal"); + } + } +} diff --git a/services/account-service/src/main/resources/db/migration/V74.1__account_global_role_source.sql b/services/account-service/src/main/resources/db/migration/V74.1__account_global_role_source.sql new file mode 100644 index 0000000000..78047e0790 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V74.1__account_global_role_source.sql @@ -0,0 +1,158 @@ +ALTER TABLE accounts + ADD CONSTRAINT accounts_global_role_source_identity_uq + UNIQUE (account_uuid, account_uuid_source_numeric_id, account_uuid_provenance); + +CREATE TABLE account_global_role_sources ( + account_uuid UUID PRIMARY KEY, + account_uuid_source_numeric_id BIGINT NOT NULL, + account_uuid_provenance VARCHAR(40) NOT NULL, + global_roles TEXT[] NOT NULL, + global_role_source_version BIGINT NOT NULL, + CONSTRAINT account_global_role_sources_account_identity_fk + FOREIGN KEY ( + account_uuid, + account_uuid_source_numeric_id, + account_uuid_provenance + ) + REFERENCES accounts ( + account_uuid, + account_uuid_source_numeric_id, + account_uuid_provenance + ) + ON DELETE RESTRICT, + CONSTRAINT account_global_role_sources_account_numeric_id_check + CHECK (account_uuid_source_numeric_id > 0), + CONSTRAINT account_global_role_sources_account_uuid_check + CHECK (account_uuid <> '00000000-0000-0000-0000-000000000000'::UUID), + CONSTRAINT account_global_role_sources_fresh_provenance_check + CHECK (account_uuid_provenance IN ( + 'ACCOUNT_REPOSITORY_INSERT', + 'ACCOUNT_DATABASE_INSERT' + )), + CONSTRAINT account_global_role_sources_empty_roles_check + CHECK (global_roles = ARRAY[]::TEXT[]), + CONSTRAINT account_global_role_sources_positive_version_check + CHECK (global_role_source_version > 0) +); + +-- This prerequisite admits only the explicit-empty state. Role mutations need a +-- separately versioned, fenced producer before this immutable source can advance. +-- [jooq ignore start] +CREATE FUNCTION account_global_role_source_immutable_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'Fresh Account global-role source is immutable until a versioned writer exists' + USING ERRCODE = '23514', CONSTRAINT = 'account_global_role_source_immutable'; + RETURN OLD; +END; +$$; + +CREATE TRIGGER account_global_role_source_immutable + BEFORE UPDATE OR DELETE ON account_global_role_sources + FOR EACH ROW EXECUTE FUNCTION account_global_role_source_immutable_guard(); + +CREATE FUNCTION account_global_role_source_truncate_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'Fresh Account global-role source cannot be truncated' + USING ERRCODE = '23514', CONSTRAINT = 'account_global_role_source_truncate_denied'; + RETURN NULL; +END; +$$; + +CREATE TRIGGER account_global_role_source_truncate_guard + BEFORE TRUNCATE ON account_global_role_sources + FOR EACH STATEMENT EXECUTE FUNCTION account_global_role_source_truncate_guard(); + +CREATE FUNCTION account_global_role_source_birth_insert_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + account_identity_exists BOOLEAN; +BEGIN + IF pg_trigger_depth() <> 2 THEN + RAISE EXCEPTION 'Account global-role source may only be inserted by its fresh Account birth path' + USING ERRCODE = '23514', CONSTRAINT = 'account_global_role_source_birth_only'; + END IF; + + -- The source table and its Account owner may be written through a + -- schema-qualified relation while the connection search_path names another + -- schema. Resolve the paired Account row in the trigger table's own schema. + EXECUTE format( + 'SELECT EXISTS ( + SELECT 1 + FROM %I.accounts account_row + WHERE account_row.id = $1 + AND account_row.account_uuid = $2 + AND account_row.account_uuid_source_numeric_id = $3 + AND account_row.account_uuid_provenance = $4 + AND account_row.account_uuid_provenance IN ( + ''ACCOUNT_REPOSITORY_INSERT'', + ''ACCOUNT_DATABASE_INSERT'' + ) + AND account_row.role IS NULL + )', + TG_TABLE_SCHEMA + ) INTO account_identity_exists + USING NEW.account_uuid_source_numeric_id, + NEW.account_uuid, + NEW.account_uuid_source_numeric_id, + NEW.account_uuid_provenance; + + IF NOT account_identity_exists THEN + RAISE EXCEPTION 'Account global-role source may only be inserted by its fresh Account birth path' + USING ERRCODE = '23514', CONSTRAINT = 'account_global_role_source_birth_only'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER account_global_role_source_birth_insert_guard + BEFORE INSERT ON account_global_role_sources + FOR EACH ROW EXECUTE FUNCTION account_global_role_source_birth_insert_guard(); + +CREATE FUNCTION account_global_role_source_birth() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + IF NEW.account_uuid_provenance IN ( + 'ACCOUNT_REPOSITORY_INSERT', + 'ACCOUNT_DATABASE_INSERT' + ) AND NEW.role IS NULL THEN + IF NEW.account_uuid IS NULL + OR NEW.account_uuid = '00000000-0000-0000-0000-000000000000'::UUID + OR NEW.account_uuid_source_numeric_id IS DISTINCT FROM NEW.id THEN + RAISE EXCEPTION 'Fresh Account has no exact canonical UUID source identity' + USING ERRCODE = '23514', + CONSTRAINT = 'account_global_role_source_birth_identity'; + END IF; + + -- Bind the fresh source row to the schema that owns this Account row, + -- even when the caller inserted through a qualified table name. + EXECUTE format( + 'INSERT INTO %I.account_global_role_sources ( + account_uuid, + account_uuid_source_numeric_id, + account_uuid_provenance, + global_roles, + global_role_source_version + ) VALUES ($1, $2, $3, ARRAY[]::TEXT[], 1)', + TG_TABLE_SCHEMA + ) USING NEW.account_uuid, + NEW.account_uuid_source_numeric_id, + NEW.account_uuid_provenance; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER accounts_global_role_source_birth + AFTER INSERT ON accounts + FOR EACH ROW EXECUTE FUNCTION account_global_role_source_birth(); +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V74__account_gameplay_token_identity_fences.sql b/services/account-service/src/main/resources/db/migration/V74__account_gameplay_token_identity_fences.sql new file mode 100644 index 0000000000..00b9ddbbdb --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V74__account_gameplay_token_identity_fences.sql @@ -0,0 +1,85 @@ +-- Only the real COMMITTED issuance transaction establishes initial fences; no registry adoption. +-- Historical COMMITTED rows with no fence fail closed and require fresh LOGIN. +CREATE TABLE account_gameplay_token_identity_fences ( + operation_id UUID PRIMARY KEY REFERENCES account_gameplay_delegation_issuance_operations (operation_id) ON DELETE RESTRICT, + account_uuid UUID NOT NULL REFERENCES accounts (account_uuid) ON DELETE RESTRICT, + issuance_request_id UUID NOT NULL UNIQUE, + token_hash VARCHAR(64) NOT NULL UNIQUE, + token_jti UUID NOT NULL UNIQUE, + not_before_epoch_second BIGINT NOT NULL, + token_generation BIGINT NOT NULL, + issuance_fence BIGINT NOT NULL, + token_identity_fence BIGINT NOT NULL DEFAULT 1, + state VARCHAR(16) NOT NULL DEFAULT 'ACTIVE', + revocation_request_id UUID UNIQUE, + revocation_digest VARCHAR(64), + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT account_gameplay_token_identity_shape CHECK ( + token_hash ~ '^[0-9a-f]{64}$' AND not_before_epoch_second > 0 + AND token_generation = 1 AND issuance_fence > 0 + AND account_uuid::text ~ '^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$' + AND operation_id::text ~ '^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$' + AND issuance_request_id::text ~ '^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$' + AND token_jti::text ~ '^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$'), + CONSTRAINT account_gameplay_token_revocation_shape CHECK ( + (state = 'ACTIVE' AND token_identity_fence = 1 + AND revocation_request_id IS NULL AND revocation_digest IS NULL) + OR (state IN ('PENDING', 'COMMITTED') + AND token_identity_fence = CASE WHEN state = 'PENDING' THEN 2 ELSE 3 END + AND revocation_request_id IS NOT NULL AND revocation_digest IS NOT NULL + AND revocation_request_id::text ~ '^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$' + AND revocation_digest ~ '^[0-9a-f]{64}$')) +); + +-- Retain immutable identity and forbid reset/recreation. Triggers reinforce the repository's +-- account-row-first lock order; callers must acquire that Account lock before row mutations. +-- [jooq ignore start] +CREATE FUNCTION account_gameplay_token_identity_fence_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'Account token fence retention cannot be bypassed by deletion' USING ERRCODE = '23514'; + END IF; + PERFORM account_uuid FROM accounts WHERE account_uuid = NEW.account_uuid FOR UPDATE; + IF NOT FOUND THEN + RAISE EXCEPTION 'Account token fence Account source absent' USING ERRCODE = '23514'; + END IF; + PERFORM operation_id FROM account_gameplay_delegation_issuance_operations + WHERE operation_id = NEW.operation_id AND account_uuid = NEW.account_uuid + AND request_id = NEW.issuance_request_id AND token_hash = NEW.token_hash + AND token_jti = NEW.token_jti AND not_before_epoch_second = NEW.not_before_epoch_second + AND token_generation = NEW.token_generation AND issuance_fence = NEW.issuance_fence + AND status = 'COMMITTED' FOR SHARE; + IF NOT FOUND THEN + RAISE EXCEPTION 'Account token fence requires exact COMMITTED issuance' USING ERRCODE = '23514'; + END IF; + IF TG_OP = 'INSERT' THEN + IF NEW.state <> 'ACTIVE' OR NEW.token_identity_fence <> 1 + OR NEW.revocation_request_id IS NOT NULL OR NEW.revocation_digest IS NOT NULL THEN + RAISE EXCEPTION 'Account token fence must begin ACTIVE' USING ERRCODE = '23514'; + END IF; + RETURN NEW; + END IF; + IF ROW(NEW.operation_id, NEW.account_uuid, NEW.issuance_request_id, NEW.token_hash, + NEW.token_jti, NEW.not_before_epoch_second, NEW.token_generation, NEW.issuance_fence, NEW.created_at) + IS DISTINCT FROM ROW(OLD.operation_id, OLD.account_uuid, OLD.issuance_request_id, OLD.token_hash, + OLD.token_jti, OLD.not_before_epoch_second, OLD.token_generation, OLD.issuance_fence, OLD.created_at) THEN + RAISE EXCEPTION 'Account token fence identity is immutable' USING ERRCODE = '23514'; + END IF; + IF NEW IS NOT DISTINCT FROM OLD THEN RETURN NEW; END IF; + IF OLD.state = 'ACTIVE' AND NEW.state = 'PENDING' AND NEW.token_identity_fence = 2 THEN + RETURN NEW; + END IF; + -- Storage only: there is no completion API until the real Gateway deny/clear owner exists. + IF OLD.state = 'PENDING' AND NEW.state = 'COMMITTED' AND NEW.token_identity_fence = 3 + AND NEW.revocation_request_id = OLD.revocation_request_id + AND NEW.revocation_digest = OLD.revocation_digest THEN + RETURN NEW; + END IF; + RAISE EXCEPTION 'Account token fence transition or revocation identity conflicts' USING ERRCODE = '23514'; +END; +$$; +CREATE TRIGGER account_gameplay_token_identity_fence_guard +BEFORE INSERT OR UPDATE OR DELETE ON account_gameplay_token_identity_fences +FOR EACH ROW EXECUTE FUNCTION account_gameplay_token_identity_fence_guard(); +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V75__account_password_reset_operation_receipts.sql b/services/account-service/src/main/resources/db/migration/V75__account_password_reset_operation_receipts.sql new file mode 100644 index 0000000000..33b0cb2992 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V75__account_password_reset_operation_receipts.sql @@ -0,0 +1,91 @@ +-- Immutable source receipts make a consumed Account-issued reset token an exact retry identity. +CREATE TABLE account_password_reset_operation_receipts ( + token_hash BYTEA NOT NULL, + account_id BIGINT NOT NULL REFERENCES accounts(id) ON DELETE RESTRICT, + account_uuid UUID NOT NULL, + operation_kind VARCHAR(32) NOT NULL DEFAULT 'PASSWORD_RESET', + request_id VARCHAR(128) NOT NULL UNIQUE, + request_digest_version INTEGER NOT NULL, + request_digest BYTEA NOT NULL, + token_expires_at TIMESTAMP WITHOUT TIME ZONE NOT NULL, + password_verifier_digest BYTEA NOT NULL, + outbox_stream_key VARCHAR(2048) NOT NULL, + outbox_sequence BIGINT NOT NULL, + event_id VARCHAR(128) NOT NULL, + event_digest VARCHAR(71) NOT NULL, + account_authority_generation BIGINT NOT NULL, + account_source_version BIGINT NOT NULL, + issuance_fence BIGINT NOT NULL, + issuance_fence_source_version BIGINT NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT account_password_reset_operation_token_hash_check + CHECK (octet_length(token_hash) = 32), + CONSTRAINT account_password_reset_operation_identity_check + CHECK (account_id > 0 + AND account_uuid <> '00000000-0000-0000-0000-000000000000'::UUID + AND operation_kind = 'PASSWORD_RESET' + AND length(btrim(request_id)) BETWEEN 1 AND 128 + AND request_id = 'account-password-reset-request-v1:' || encode(token_hash, 'hex') + AND request_digest_version = 1 + AND octet_length(request_digest) = 32 + AND octet_length(password_verifier_digest) = 32), + CONSTRAINT account_password_reset_operation_checkpoint_check + CHECK (outbox_stream_key = 'account:auth-authority:v1:account/' || account_uuid::TEXT + AND outbox_sequence > 0 + AND length(btrim(event_id)) BETWEEN 1 AND 128 + AND event_id = 'account-password-reset-event-v1:' || encode(token_hash, 'hex') + AND event_digest ~ '^sha256:[0-9a-f]{64}$' + AND account_authority_generation > 0 + AND account_source_version > 0 + AND issuance_fence > 0 + AND issuance_fence_source_version > 0), + CONSTRAINT account_password_reset_operation_event_uq + UNIQUE (outbox_stream_key, event_id), + CONSTRAINT account_password_reset_operation_outbox_fk + FOREIGN KEY (outbox_stream_key, outbox_sequence) + REFERENCES account_authority_outbox_events (outbox_stream_key, outbox_sequence) + ON DELETE RESTRICT +); + +-- Bind the private numeric association and canonical Account UUID at the immutable insert point. +-- [jooq ignore start] +ALTER TABLE account_password_reset_operation_receipts + ADD CONSTRAINT account_password_reset_operation_receipts_pk PRIMARY KEY (token_hash); + +CREATE FUNCTION account_password_reset_operation_account_binding_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + persisted_uuid UUID; +BEGIN + SELECT account_uuid INTO persisted_uuid + FROM accounts + WHERE id = NEW.account_id; + IF persisted_uuid IS DISTINCT FROM NEW.account_uuid THEN + RAISE EXCEPTION 'Password-reset receipt Account identity does not match its source row' + USING ERRCODE = '23514', CONSTRAINT = 'account_password_reset_operation_account_binding'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER account_password_reset_operation_account_binding + BEFORE INSERT ON account_password_reset_operation_receipts + FOR EACH ROW EXECUTE FUNCTION account_password_reset_operation_account_binding_guard(); + +CREATE FUNCTION account_password_reset_operation_immutable_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'Password-reset operation receipts are immutable' + USING ERRCODE = '23514', CONSTRAINT = 'account_password_reset_operation_immutable'; + RETURN OLD; +END; +$$; + +CREATE TRIGGER account_password_reset_operation_immutable + BEFORE UPDATE OR DELETE ON account_password_reset_operation_receipts + FOR EACH ROW EXECUTE FUNCTION account_password_reset_operation_immutable_guard(); +-- [jooq ignore end] diff --git a/services/account-service/src/main/resources/db/migration/V76__draft_commit_authorization_fences.sql b/services/account-service/src/main/resources/db/migration/V76__draft_commit_authorization_fences.sql new file mode 100644 index 0000000000..e0fb5be03a --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V76__draft_commit_authorization_fences.sql @@ -0,0 +1,167 @@ +-- Internal storage only. No source writer or authenticated authorization producer is enabled. +CREATE TABLE account_draft_authorization_source_locks ( + source_key VARCHAR(512) PRIMARY KEY CHECK (length(source_key) > 0 AND octet_length(source_key) <= 512) +); + +CREATE TABLE account_draft_authorization_fences ( + operation_id UUID PRIMARY KEY, + request_id UUID NOT NULL UNIQUE, + commit_id UUID NOT NULL UNIQUE, + fence_id UUID NOT NULL UNIQUE, + binding BYTEA NOT NULL CHECK (octet_length(binding) > 0), + ordering VARCHAR(20) NOT NULL CHECK (ordering IN ('RESERVED', 'COMMIT_ORDER', 'REVOKE_ORDER')), + reserved_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + ordered_at TIMESTAMPTZ, + CHECK ((ordering = 'RESERVED') = (ordered_at IS NULL)) +); + +CREATE TABLE account_draft_authorization_sources ( + operation_id UUID NOT NULL REFERENCES account_draft_authorization_fences(operation_id), + source_key VARCHAR(512) NOT NULL REFERENCES account_draft_authorization_source_locks(source_key), + source_evidence BYTEA NOT NULL CHECK (octet_length(source_evidence) > 0), + PRIMARY KEY (operation_id, source_key) +); +CREATE INDEX account_draft_authorization_sources_by_scope + ON account_draft_authorization_sources(source_key, operation_id); + +CREATE TABLE account_draft_authorization_owner_readbacks ( + operation_id UUID NOT NULL REFERENCES account_draft_authorization_fences(operation_id), + owner VARCHAR(16) NOT NULL CHECK (owner IN ('GAME_DESIGN', 'WORLD')), + outcome VARCHAR(24) NOT NULL CHECK (outcome IN ('COMMITTED', 'DEFINITIVELY_ABORTED')), + readback BYTEA NOT NULL CHECK (octet_length(readback) > 0), + recorded_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (operation_id, owner) +); + +CREATE TABLE account_draft_authorization_source_changes ( + change_id UUID PRIMARY KEY, + binding BYTEA NOT NULL CHECK (octet_length(binding) > 0), + status VARCHAR(16) NOT NULL CHECK (status IN ('WAITING', 'SOURCE_COMMITTED')), + requested_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + committed_at TIMESTAMPTZ, + CHECK ((status = 'WAITING') = (committed_at IS NULL)) +); + +CREATE TABLE account_draft_authorization_changed_scopes ( + change_id UUID NOT NULL REFERENCES account_draft_authorization_source_changes(change_id), + source_key VARCHAR(512) NOT NULL REFERENCES account_draft_authorization_source_locks(source_key), + PRIMARY KEY (change_id, source_key) +); +CREATE INDEX account_draft_authorization_changes_by_scope + ON account_draft_authorization_changed_scopes(source_key, change_id); + +-- [jooq ignore start] +CREATE FUNCTION account_draft_authorization_immutable_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + RAISE EXCEPTION 'Draft authorization evidence is immutable' + USING ERRCODE = '23514'; +END; +$$; + +CREATE FUNCTION account_draft_authorization_order_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'Draft authorization fence cannot be deleted'; + END IF; + IF OLD.ordering <> 'RESERVED' OR NEW.ordering NOT IN ('COMMIT_ORDER', 'REVOKE_ORDER') + OR NEW.operation_id IS DISTINCT FROM OLD.operation_id + OR NEW.request_id IS DISTINCT FROM OLD.request_id + OR NEW.commit_id IS DISTINCT FROM OLD.commit_id + OR NEW.fence_id IS DISTINCT FROM OLD.fence_id + OR NEW.binding IS DISTINCT FROM OLD.binding + OR NEW.reserved_at IS DISTINCT FROM OLD.reserved_at + OR NEW.ordered_at IS NULL THEN + RAISE EXCEPTION 'Draft commit/revoke ordering is immutable'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_draft_authorization_source_change_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'Draft source change cannot be deleted'; + END IF; + IF OLD.status <> 'WAITING' OR NEW.status <> 'SOURCE_COMMITTED' + OR NEW.change_id IS DISTINCT FROM OLD.change_id + OR NEW.binding IS DISTINCT FROM OLD.binding + OR NEW.requested_at IS DISTINCT FROM OLD.requested_at + OR NEW.committed_at IS NULL THEN + RAISE EXCEPTION 'Draft source change result is immutable'; + END IF; + IF EXISTS ( + SELECT 1 FROM account_draft_authorization_changed_scopes changed + JOIN account_draft_authorization_sources source USING (source_key) + JOIN account_draft_authorization_fences fence USING (operation_id) + WHERE changed.change_id = OLD.change_id + AND NOT ((fence.ordering = 'REVOKE_ORDER' AND ( + SELECT count(*) FROM account_draft_authorization_owner_readbacks readback + WHERE readback.operation_id = fence.operation_id + AND readback.outcome = 'DEFINITIVELY_ABORTED' + ) = 2) OR (fence.ordering = 'COMMIT_ORDER' AND ( + SELECT count(*) FROM account_draft_authorization_owner_readbacks readback + WHERE readback.operation_id = fence.operation_id + ) = 2)) + ) THEN + RAISE EXCEPTION 'Both definitive owner outcomes are required before source commit'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_draft_authorization_insert_phase_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + phase TEXT; +BEGIN + IF TG_TABLE_NAME = 'account_draft_authorization_changed_scopes' THEN + SELECT status INTO phase FROM account_draft_authorization_source_changes + WHERE change_id = NEW.change_id FOR UPDATE; + IF phase IS DISTINCT FROM 'WAITING' THEN + RAISE EXCEPTION 'Completed source change cannot acquire new scopes'; + END IF; + ELSE + SELECT ordering INTO phase FROM account_draft_authorization_fences + WHERE operation_id = NEW.operation_id FOR UPDATE; + IF TG_TABLE_NAME = 'account_draft_authorization_sources' AND phase IS DISTINCT FROM 'RESERVED' THEN + RAISE EXCEPTION 'Ordered Draft operation cannot acquire new sources'; + ELSIF TG_TABLE_NAME = 'account_draft_authorization_owner_readbacks' + AND (phase IS NULL OR phase = 'RESERVED') THEN + RAISE EXCEPTION 'Reservation alone cannot produce owner terminal evidence'; + END IF; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER account_draft_authorization_fence_guard + BEFORE UPDATE OR DELETE ON account_draft_authorization_fences + FOR EACH ROW EXECUTE FUNCTION account_draft_authorization_order_guard(); +CREATE TRIGGER account_draft_authorization_change_guard + BEFORE UPDATE OR DELETE ON account_draft_authorization_source_changes + FOR EACH ROW EXECUTE FUNCTION account_draft_authorization_source_change_guard(); +CREATE TRIGGER account_draft_authorization_sources_immutable + BEFORE UPDATE OR DELETE ON account_draft_authorization_sources + FOR EACH ROW EXECUTE FUNCTION account_draft_authorization_immutable_guard(); +CREATE TRIGGER account_draft_authorization_readbacks_immutable + BEFORE UPDATE OR DELETE ON account_draft_authorization_owner_readbacks + FOR EACH ROW EXECUTE FUNCTION account_draft_authorization_immutable_guard(); +CREATE TRIGGER account_draft_authorization_scopes_immutable + BEFORE UPDATE OR DELETE ON account_draft_authorization_changed_scopes + FOR EACH ROW EXECUTE FUNCTION account_draft_authorization_immutable_guard(); +CREATE TRIGGER account_draft_authorization_source_locks_immutable + BEFORE UPDATE OR DELETE ON account_draft_authorization_source_locks + FOR EACH ROW EXECUTE FUNCTION account_draft_authorization_immutable_guard(); +CREATE TRIGGER account_draft_authorization_source_insert_phase + BEFORE INSERT ON account_draft_authorization_sources + FOR EACH ROW EXECUTE FUNCTION account_draft_authorization_insert_phase_guard(); +CREATE TRIGGER account_draft_authorization_readback_insert_phase + BEFORE INSERT ON account_draft_authorization_owner_readbacks + FOR EACH ROW EXECUTE FUNCTION account_draft_authorization_insert_phase_guard(); +CREATE TRIGGER account_draft_authorization_scope_insert_phase + BEFORE INSERT ON account_draft_authorization_changed_scopes + FOR EACH ROW EXECUTE FUNCTION account_draft_authorization_insert_phase_guard(); +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V77__account_logout_all_operation_receipts.sql b/services/account-service/src/main/resources/db/migration/V77__account_logout_all_operation_receipts.sql new file mode 100644 index 0000000000..09ae1789ae --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V77__account_logout_all_operation_receipts.sql @@ -0,0 +1,90 @@ +-- Immutable lifecycle receipts bind one logout-all request and presented token to its source event. +CREATE TABLE account_logout_all_operation_receipts ( + request_id UUID NOT NULL, + account_id BIGINT NOT NULL REFERENCES accounts(id) ON DELETE RESTRICT, + account_uuid UUID NOT NULL, + operation_kind VARCHAR(32) NOT NULL DEFAULT 'ACCOUNT_LOGOUT_ALL', + request_digest_version INTEGER NOT NULL, + request_digest BYTEA NOT NULL, + presented_token_hash BYTEA NOT NULL, + token_profile VARCHAR(32) NOT NULL, + outbox_stream_key VARCHAR(2048) NOT NULL, + outbox_sequence BIGINT NOT NULL, + event_id VARCHAR(128) NOT NULL, + event_digest VARCHAR(71) NOT NULL, + account_authority_generation BIGINT NOT NULL, + account_source_version BIGINT NOT NULL, + issuance_fence BIGINT NOT NULL, + issuance_fence_source_version BIGINT NOT NULL, + lifecycle_result VARCHAR(32) NOT NULL DEFAULT 'LOGOUT_ALL_COMMITTED', + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT account_logout_all_operation_identity_check + CHECK (request_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND account_uuid <> '00000000-0000-0000-0000-000000000000'::UUID + AND operation_kind = 'ACCOUNT_LOGOUT_ALL' + AND request_digest_version = 1 + AND octet_length(request_digest) = 32 + AND octet_length(presented_token_hash) = 32 + AND token_profile IN ('control-ui', 'player-bootstrap') + AND lifecycle_result = 'LOGOUT_ALL_COMMITTED'), + CONSTRAINT account_logout_all_operation_checkpoint_check + CHECK (outbox_stream_key = 'account:auth-authority:v1:account/' || account_uuid::TEXT + AND outbox_sequence > 0 + AND event_id = 'account-logout-all-event-v1:' || request_id::TEXT + AND event_digest ~ '^sha256:[0-9a-f]{64}$' + AND account_authority_generation > 0 + AND account_source_version > 0 + AND issuance_fence > 0 + AND issuance_fence_source_version > 0), + CONSTRAINT account_logout_all_operation_event_uq + UNIQUE (outbox_stream_key, event_id), + CONSTRAINT account_logout_all_operation_outbox_fk + FOREIGN KEY (outbox_stream_key, outbox_sequence) + REFERENCES account_authority_outbox_events (outbox_stream_key, outbox_sequence) + ON DELETE RESTRICT +); + +-- [jooq ignore start] +ALTER TABLE account_logout_all_operation_receipts + ADD CONSTRAINT account_logout_all_operation_receipts_pk PRIMARY KEY (request_id); + +CREATE UNIQUE INDEX account_logout_all_operation_presented_token_uq + ON account_logout_all_operation_receipts (presented_token_hash); + +CREATE FUNCTION account_logout_all_operation_account_binding_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + persisted_uuid UUID; +BEGIN + SELECT account_uuid INTO persisted_uuid + FROM accounts + WHERE id = NEW.account_id; + IF persisted_uuid IS DISTINCT FROM NEW.account_uuid THEN + RAISE EXCEPTION 'Logout-all receipt Account identity does not match its source row' + USING ERRCODE = '23514', CONSTRAINT = 'account_logout_all_operation_account_binding'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER account_logout_all_operation_account_binding + BEFORE INSERT ON account_logout_all_operation_receipts + FOR EACH ROW EXECUTE FUNCTION account_logout_all_operation_account_binding_guard(); + +CREATE FUNCTION account_logout_all_operation_immutable_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'Logout-all operation receipts are immutable' + USING ERRCODE = '23514', CONSTRAINT = 'account_logout_all_operation_immutable'; + RETURN OLD; +END; +$$; + +CREATE TRIGGER account_logout_all_operation_immutable + BEFORE UPDATE OR DELETE ON account_logout_all_operation_receipts + FOR EACH ROW EXECUTE FUNCTION account_logout_all_operation_immutable_guard(); +-- [jooq ignore end] diff --git a/services/account-service/src/main/resources/db/migration/V78__account_security_state_operations.sql b/services/account-service/src/main/resources/db/migration/V78__account_security_state_operations.sql new file mode 100644 index 0000000000..78309fc3fd --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V78__account_security_state_operations.sql @@ -0,0 +1,401 @@ +-- Correlation/receipt storage only. No source writer, authorization grant, or retained-row backfill. +CREATE TABLE account_security_state_operations ( + request_id UUID PRIMARY KEY CHECK (request_id <> '00000000-0000-0000-0000-000000000000'), + account_id BIGINT NOT NULL REFERENCES accounts(id) ON DELETE RESTRICT, + account_uuid UUID NOT NULL, + account_provenance VARCHAR(40) NOT NULL, + caller_proof_binding BYTEA NOT NULL CHECK (octet_length(caller_proof_binding) BETWEEN 1 AND 16384), + request_payload BYTEA NOT NULL CHECK (octet_length(request_payload) > 0), + request_digest VARCHAR(64) NOT NULL CHECK (request_digest ~ '^[0-9a-f]{64}$'), + expected_generation BIGINT NOT NULL CHECK (expected_generation > 0), + expected_source_version BIGINT NOT NULL CHECK (expected_source_version > 0), + expected_fence BIGINT NOT NULL CHECK (expected_fence > 0), + expected_fence_source_version BIGINT NOT NULL CHECK (expected_fence_source_version > 0), + checkpoint_sequence BIGINT NOT NULL CHECK (checkpoint_sequence >= 0), + checkpoint_payload BYTEA NOT NULL, + global_role_source_version BIGINT NOT NULL CHECK (global_role_source_version > 0), + before_state BYTEA NOT NULL, + after_state BYTEA NOT NULL, + mutation_kinds TEXT[] NOT NULL CHECK (cardinality(mutation_kinds) BETWEEN 1 AND 4), + source_change_id UUID NOT NULL UNIQUE REFERENCES account_draft_authorization_source_changes(change_id), + source_change_binding BYTEA NOT NULL CHECK (octet_length(source_change_binding) > 0), + capture_payload BYTEA NOT NULL CHECK (octet_length(capture_payload) > 0), + status VARCHAR(12) NOT NULL CHECK (status IN ('WAITING', 'COMMITTED')), + event_sequence BIGINT CHECK (event_sequence > 0), + event_id VARCHAR(128), + event_digest VARCHAR(71), + event_payload BYTEA, + result_generation BIGINT CHECK (result_generation > 0), + result_source_version BIGINT CHECK (result_source_version > 0), + result_fence BIGINT CHECK (result_fence > 0), + result_fence_source_version BIGINT CHECK (result_fence_source_version > 0), + result_global_role_source_version BIGINT CHECK (result_global_role_source_version > 0), + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + committed_at TIMESTAMPTZ, + FOREIGN KEY (account_uuid, account_id, account_provenance) + REFERENCES accounts(account_uuid, account_uuid_source_numeric_id, account_uuid_provenance) + ON DELETE RESTRICT, + CONSTRAINT account_security_state_result_shape CHECK ( + (status = 'WAITING' AND event_sequence IS NULL AND event_id IS NULL AND event_digest IS NULL + AND event_payload IS NULL AND result_generation IS NULL AND result_source_version IS NULL + AND result_fence IS NULL AND result_fence_source_version IS NULL + AND result_global_role_source_version IS NULL AND committed_at IS NULL) + OR (status = 'COMMITTED' AND event_sequence IS NOT NULL AND event_id IS NOT NULL + AND event_digest IS NOT NULL AND event_digest ~ '^sha256:[0-9a-f]{64}$' AND event_payload IS NOT NULL + AND result_generation IS NOT NULL AND result_source_version IS NOT NULL + AND result_fence IS NOT NULL AND result_fence_source_version IS NOT NULL + AND result_global_role_source_version IS NOT NULL AND committed_at IS NOT NULL)) +); + +CREATE UNIQUE INDEX account_security_state_event_checkpoint_unique + ON account_security_state_operations(account_uuid, event_sequence) WHERE event_sequence IS NOT NULL; + +-- [jooq ignore start] +CREATE FUNCTION account_security_state_frame(value BYTEA) +RETURNS BYTEA LANGUAGE SQL IMMUTABLE STRICT AS $$ + SELECT int4send(octet_length(value)) || value; +$$; + +CREATE FUNCTION account_security_state_canonical_state(value BYTEA) +RETURNS TEXT LANGUAGE plpgsql IMMUTABLE STRICT AS $$ +DECLARE + state JSONB := convert_from(value, 'UTF8')::JSONB; + modes TEXT[]; + roles TEXT[]; + canonical TEXT; +BEGIN + IF jsonb_typeof(state) <> 'object' + OR (SELECT array_agg(k ORDER BY k) FROM jsonb_object_keys(state) k) + <> ARRAY['emailVerified','globalRoles','lifecycleState','loginAuthModes'] + OR jsonb_typeof(state->'emailVerified') <> 'boolean' + OR jsonb_typeof(state->'loginAuthModes') <> 'array' + OR jsonb_typeof(state->'globalRoles') <> 'array' + OR jsonb_typeof(state->'lifecycleState') <> 'string' + OR state->>'lifecycleState' NOT IN ('ACTIVE','SECURITY_LOCKED','DEACTIVATED_PENDING_DELETE','DELETED') THEN + RAISE EXCEPTION 'Unsupported security-state representation' USING ERRCODE = '23514'; + END IF; + SELECT COALESCE(array_agg(v ORDER BY ordinal), ARRAY[]::TEXT[]) INTO modes + FROM jsonb_array_elements_text(state->'loginAuthModes') WITH ORDINALITY AS t(v, ordinal); + SELECT COALESCE(array_agg(v ORDER BY ordinal), ARRAY[]::TEXT[]) INTO roles + FROM jsonb_array_elements_text(state->'globalRoles') WITH ORDINALITY AS t(v, ordinal); + IF cardinality(modes) = 0 OR NOT modes <@ ARRAY['EMAIL_OTP','PASSWORD']::TEXT[] + OR modes <> (SELECT array_agg(DISTINCT v ORDER BY v) FROM unnest(modes) v) + OR NOT roles <@ ARRAY['billingAdmin','platformAdmin','support']::TEXT[] + OR roles <> (SELECT COALESCE(array_agg(DISTINCT v ORDER BY v), ARRAY[]::TEXT[]) FROM unnest(roles) v) THEN + RAISE EXCEPTION 'Unsupported security-state arrays' USING ERRCODE = '23514'; + END IF; + canonical := '{"emailVerified":' || (state->'emailVerified')::TEXT + || ',"globalRoles":' || replace((state->'globalRoles')::TEXT, ', ', ',') + || ',"lifecycleState":"' || (state->>'lifecycleState') || '"' + || ',"loginAuthModes":' || replace((state->'loginAuthModes')::TEXT, ', ', ',') || '}'; + IF value IS DISTINCT FROM convert_to(canonical, 'UTF8') THEN + RAISE EXCEPTION 'Security-state bytes must be complete canonical JSON' USING ERRCODE = '23514'; + END IF; + RETURN canonical; +END; +$$; + +CREATE FUNCTION account_security_state_operation_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + before_json JSONB; + after_json JSONB; + kinds TEXT[] := ARRAY[]::TEXT[]; + request_bytes BYTEA; + capture_bytes BYTEA; + account_source_bytes BYTEA; + role_source_bytes BYTEA; + change_bytes BYTEA; + kind TEXT; + source_row RECORD; + baseline_row RECORD; + account_row RECORD; + role_row RECORD; + authority_row RECORD; + fence_row RECORD; + outbox_row RECORD; + stream_row RECORD; + key TEXT; + preimage TEXT; + expected_digest TEXT; + expected_wire TEXT; + caller_json JSONB; + canonical_caller TEXT; + checkpoint_json JSONB; + checkpoint_text TEXT; + checkpoint_preimage TEXT; +BEGIN + IF TG_OP = 'UPDATE' THEN + IF OLD.status <> 'WAITING' OR NEW.status <> 'COMMITTED' + OR (to_jsonb(NEW) - ARRAY['status','event_sequence','event_id','event_digest','event_payload', + 'result_generation','result_source_version','result_fence','result_fence_source_version', + 'result_global_role_source_version','committed_at']) + IS DISTINCT FROM (to_jsonb(OLD) - ARRAY['status','event_sequence','event_id','event_digest','event_payload', + 'result_generation','result_source_version','result_fence','result_fence_source_version', + 'result_global_role_source_version','committed_at']) THEN + RAISE EXCEPTION 'Original security-state request/capture and committed results are immutable' + USING ERRCODE = '23514'; + END IF; + NEW.committed_at := CURRENT_TIMESTAMP; + ELSIF NEW.status <> 'WAITING' THEN + RAISE EXCEPTION 'Security-state operation must start WAITING' USING ERRCODE = '23514'; + END IF; + before_json := account_security_state_canonical_state(NEW.before_state)::JSONB; + after_json := account_security_state_canonical_state(NEW.after_state)::JSONB; + caller_json := convert_from(NEW.caller_proof_binding,'UTF8')::JSONB; + IF jsonb_typeof(caller_json) <> 'object' + OR (SELECT array_agg(k ORDER BY k) FROM jsonb_object_keys(caller_json) k) + <> ARRAY['actorAccountUuid','ownerEvidenceDigest','ownerOperationId','schemaVersion'] + OR caller_json->>'schemaVersion' <> 'account-security-state-caller-correlation/v1' + OR jsonb_typeof(caller_json->'actorAccountUuid') <> 'string' + OR jsonb_typeof(caller_json->'ownerOperationId') <> 'string' + OR jsonb_typeof(caller_json->'ownerEvidenceDigest') <> 'string' + OR jsonb_typeof(caller_json->'schemaVersion') <> 'string' + OR caller_json->>'actorAccountUuid' !~ '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' + OR caller_json->>'ownerOperationId' !~ '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' + OR caller_json->>'actorAccountUuid' = '00000000-0000-0000-0000-000000000000' + OR caller_json->>'ownerOperationId' = '00000000-0000-0000-0000-000000000000' + OR caller_json->>'ownerEvidenceDigest' !~ '^sha256:[0-9a-f]{64}$' THEN + RAISE EXCEPTION 'Unsupported original caller correlation shape' USING ERRCODE = '23514'; + END IF; + canonical_caller := '{"actorAccountUuid":"' || (caller_json->>'actorAccountUuid') + || '","ownerEvidenceDigest":"' || (caller_json->>'ownerEvidenceDigest') + || '","ownerOperationId":"' || (caller_json->>'ownerOperationId') + || '","schemaVersion":"account-security-state-caller-correlation/v1"}'; + IF NEW.caller_proof_binding IS DISTINCT FROM convert_to(canonical_caller,'UTF8') THEN + RAISE EXCEPTION 'Original caller correlation bytes must be canonical' USING ERRCODE = '23514'; + END IF; + IF before_json->'emailVerified' <> after_json->'emailVerified' THEN + kinds := array_append(kinds, 'EMAIL_LOGIN_ELIGIBILITY_CHANGED'); + END IF; + IF before_json->'globalRoles' <> after_json->'globalRoles' THEN + kinds := array_append(kinds, 'GLOBAL_ROLE_CHANGED'); + END IF; + IF before_json->'lifecycleState' <> after_json->'lifecycleState' THEN + kinds := array_append(kinds, 'LIFECYCLE_STATE_CHANGED'); + END IF; + IF before_json->'loginAuthModes' <> after_json->'loginAuthModes' THEN + kinds := array_append(kinds, 'LOGIN_AUTH_MODES_CHANGED'); + END IF; + IF kinds <> NEW.mutation_kinds OR cardinality(kinds) = 0 THEN + RAISE EXCEPTION 'Complete changed-family set differs from state images' USING ERRCODE = '23514'; + END IF; + request_bytes := account_security_state_frame(convert_to('firemud/account/security-state/request/v1','UTF8')) + || account_security_state_frame(convert_to(NEW.request_id::TEXT,'UTF8')) + || account_security_state_frame(convert_to(NEW.account_uuid::TEXT,'UTF8')) + || account_security_state_frame(NEW.caller_proof_binding) + || account_security_state_frame(convert_to(NEW.expected_generation::TEXT,'UTF8')) + || account_security_state_frame(convert_to(NEW.expected_source_version::TEXT,'UTF8')) + || account_security_state_frame(convert_to(cardinality(kinds)::TEXT,'UTF8')); + FOREACH kind IN ARRAY kinds LOOP + request_bytes := request_bytes || account_security_state_frame(convert_to(kind,'UTF8')); + END LOOP; + request_bytes := request_bytes || account_security_state_frame(NEW.after_state); + capture_bytes := account_security_state_frame(convert_to('firemud/account/security-state/capture/v1','UTF8')) + || account_security_state_frame(request_bytes) + || account_security_state_frame(convert_to(NEW.account_id::TEXT,'UTF8')) + || account_security_state_frame(convert_to(NEW.account_provenance,'UTF8')) + || account_security_state_frame(NEW.before_state) + || account_security_state_frame(convert_to(NEW.expected_fence::TEXT,'UTF8')) + || account_security_state_frame(convert_to(NEW.expected_fence_source_version::TEXT,'UTF8')) + || account_security_state_frame(convert_to(NEW.checkpoint_sequence::TEXT,'UTF8')) + || account_security_state_frame(NEW.checkpoint_payload) + || account_security_state_frame(convert_to(NEW.global_role_source_version::TEXT,'UTF8')); + IF request_bytes <> NEW.request_payload OR encode(sha256(request_bytes),'hex') <> NEW.request_digest + OR capture_bytes <> NEW.capture_payload THEN + RAISE EXCEPTION 'Security-state request/capture bytes or digest differ' USING ERRCODE = '23514'; + END IF; + -- Reuse the exact V57 framing; correlation cannot substitute a different source vector. + key := 'account:auth-authority:v1:account/' || NEW.account_uuid::TEXT; + account_source_bytes := account_security_state_frame(convert_to('account-draft-source-evidence/v1','UTF8')) + || account_security_state_frame(convert_to('ACCOUNT','UTF8')) + || account_security_state_frame(convert_to(NEW.account_uuid::TEXT,'UTF8')) + || account_security_state_frame(convert_to('PRESENT','UTF8')) + || account_security_state_frame(convert_to(NEW.expected_generation::TEXT,'UTF8')) + || account_security_state_frame(convert_to(NEW.expected_source_version::TEXT,'UTF8')) + || account_security_state_frame(convert_to('PRESENT','UTF8')) + || account_security_state_frame(convert_to(key,'UTF8')) + || account_security_state_frame(convert_to(NEW.checkpoint_sequence::TEXT,'UTF8')) + || account_security_state_frame(capture_bytes); + change_bytes := account_security_state_frame(convert_to('account-draft-source-change/v1','UTF8')) + || account_security_state_frame(convert_to(NEW.source_change_id::TEXT,'UTF8')) + || account_security_state_frame(convert_to(CASE WHEN 'GLOBAL_ROLE_CHANGED' = ANY(kinds) THEN '2' ELSE '1' END,'UTF8')) + || account_security_state_frame(account_source_bytes); + IF 'GLOBAL_ROLE_CHANGED' = ANY(kinds) THEN + role_source_bytes := account_security_state_frame(convert_to('account-draft-source-evidence/v1','UTF8')) + || account_security_state_frame(convert_to('GLOBAL_ROLES','UTF8')) + || account_security_state_frame(convert_to(NEW.account_uuid::TEXT,'UTF8')) + || account_security_state_frame(convert_to('ABSENT','UTF8')) + || account_security_state_frame(convert_to(NEW.global_role_source_version::TEXT,'UTF8')) + || account_security_state_frame(convert_to('ABSENT','UTF8')) + || account_security_state_frame(capture_bytes); + change_bytes := change_bytes || account_security_state_frame(role_source_bytes); + END IF; + change_bytes := change_bytes || account_security_state_frame(capture_bytes); + IF change_bytes <> NEW.source_change_binding THEN + RAISE EXCEPTION 'Security-state exact V57 participation binding differs' USING ERRCODE = '23514'; + END IF; + SELECT * INTO account_row FROM accounts WHERE id = NEW.account_id FOR UPDATE; + IF NOT FOUND OR account_row.account_uuid <> NEW.account_uuid + OR account_row.account_uuid_source_numeric_id <> NEW.account_id + OR account_row.account_uuid_provenance <> NEW.account_provenance THEN + RAISE EXCEPTION 'Security-state Account association differs' USING ERRCODE = '23514'; + END IF; + SELECT * INTO source_row FROM account_draft_authorization_source_changes + WHERE change_id = NEW.source_change_id FOR SHARE; + IF NOT FOUND OR source_row.binding <> NEW.source_change_binding + OR source_row.status <> (CASE WHEN TG_OP = 'INSERT' THEN 'WAITING' ELSE 'SOURCE_COMMITTED' END) THEN + RAISE EXCEPTION 'Security-state V57 source change differs' USING ERRCODE = '23514'; + END IF; + SELECT * INTO authority_row FROM account_authority_generations + WHERE scope_kind = 'ACCOUNT' AND account_uuid = NEW.account_uuid FOR SHARE; + SELECT * INTO fence_row FROM account_authority_issuance_fences WHERE account_uuid = NEW.account_uuid FOR SHARE; + SELECT * INTO role_row FROM account_global_role_sources WHERE account_uuid = NEW.account_uuid FOR SHARE; + IF authority_row IS NULL OR fence_row IS NULL OR role_row IS NULL THEN + RAISE EXCEPTION 'Security-state current source evidence is missing' USING ERRCODE = '23514'; + END IF; + key := 'account:auth-authority:v1:account/' || NEW.account_uuid::TEXT; + IF TG_OP = 'INSERT' THEN + IF NEW.expected_generation = 9223372036854775807 OR NEW.expected_source_version = 9223372036854775807 + OR NEW.expected_fence = 9223372036854775807 OR NEW.expected_fence_source_version = 9223372036854775807 + OR NEW.checkpoint_sequence = 9223372036854775807 + OR ('GLOBAL_ROLE_CHANGED' = ANY(kinds) AND NEW.global_role_source_version = 9223372036854775807) THEN + RAISE EXCEPTION 'Account source counter overflow' USING ERRCODE = '23514'; + END IF; + IF authority_row.generation <> NEW.expected_generation OR authority_row.source_version <> NEW.expected_source_version + OR fence_row.issuance_fence <> NEW.expected_fence OR fence_row.source_version <> NEW.expected_fence_source_version + OR role_row.global_role_source_version <> NEW.global_role_source_version THEN + RAISE EXCEPTION 'Security-state original source capture is stale' USING ERRCODE = '23514'; + END IF; + IF NEW.checkpoint_sequence = 0 THEN + SELECT * INTO baseline_row FROM account_authority_source_records + WHERE outbox_stream_key = key FOR SHARE; + SELECT * INTO stream_row FROM account_authority_outbox_streams + WHERE outbox_stream_key = key FOR SHARE; + -- V40 retains an explicit zero stream; counters alone never prove fresh provenance. + IF NEW.expected_generation <> 1 OR NEW.expected_source_version <> 1 + OR NEW.expected_fence <> 1 OR NEW.expected_fence_source_version <> 1 + OR octet_length(NEW.checkpoint_payload) <> 0 + OR baseline_row IS NULL OR stream_row IS NULL + OR stream_row.last_sequence IS DISTINCT FROM 0 + OR baseline_row.scope_kind IS DISTINCT FROM 'ACCOUNT' + OR baseline_row.issuer_id IS NOT NULL + OR baseline_row.account_uuid IS DISTINCT FROM NEW.account_uuid + OR baseline_row.baseline_generation IS DISTINCT FROM 1 + OR baseline_row.baseline_source_version IS DISTINCT FROM 1 + OR baseline_row.baseline_issuance_fence IS DISTINCT FROM 1 + OR baseline_row.current_generation IS DISTINCT FROM 1 + OR baseline_row.current_source_version IS DISTINCT FROM 1 + OR baseline_row.current_issuance_fence IS DISTINCT FROM 1 + OR baseline_row.current_issuance_fence_source_version IS DISTINCT FROM 1 + OR baseline_row.last_outbox_sequence IS DISTINCT FROM 0 + OR baseline_row.last_event_id IS NOT NULL OR baseline_row.last_event_digest IS NOT NULL + OR baseline_row.cutoff_generation IS NOT NULL OR baseline_row.cutoff_stream_key IS NOT NULL + OR baseline_row.cutoff_sequence IS NOT NULL + OR baseline_row.initialization_provenance IS DISTINCT FROM 'ACCOUNT_REPOSITORY_INSERT' + OR baseline_row.account_uuid_provenance IS DISTINCT FROM NEW.account_provenance + OR baseline_row.account_source_numeric_id IS DISTINCT FROM NEW.account_id + OR baseline_row.initialization_transaction_id <= 0 + OR baseline_row.initialization_transaction_id IS DISTINCT FROM authority_row.created_transaction_id + OR baseline_row.initialization_transaction_id IS DISTINCT FROM account_row.account_repository_insert_transaction_id + OR baseline_row.account_repository_insert_transaction_id IS DISTINCT FROM account_row.account_repository_insert_transaction_id + OR EXISTS (SELECT 1 FROM account_authority_outbox_events WHERE outbox_stream_key = key) THEN + RAISE EXCEPTION 'Security-state pristine baseline is not proved' USING ERRCODE = '23514'; + END IF; + ELSE + SELECT * INTO stream_row FROM account_authority_outbox_streams WHERE outbox_stream_key = key; + SELECT * INTO outbox_row FROM account_authority_outbox_events + WHERE outbox_stream_key = key AND outbox_sequence = NEW.checkpoint_sequence; + IF stream_row IS NULL OR outbox_row IS NULL OR stream_row.last_sequence <> NEW.checkpoint_sequence + OR outbox_row.payload <> NEW.checkpoint_payload THEN + RAISE EXCEPTION 'Security-state original checkpoint differs' USING ERRCODE = '23514'; + END IF; + checkpoint_text := convert_from(NEW.checkpoint_payload,'UTF8'); + checkpoint_json := checkpoint_text::JSONB; + checkpoint_preimage := replace(checkpoint_text, + '"eventDigest":"' || outbox_row.event_digest || '",', ''); + IF COALESCE(checkpoint_json->>'schemaVersion','') NOT IN ('account-auth-password-reset-event/v1', + 'account-auth-logout-all-event/v1', 'account-auth-account-security-state-event/v1') + OR checkpoint_json->>'accountId' IS DISTINCT FROM NEW.account_uuid::TEXT + OR checkpoint_json->>'sourceScope' IS DISTINCT FROM 'account/' || NEW.account_uuid::TEXT + OR checkpoint_json->>'outboxStreamKey' IS DISTINCT FROM key + OR checkpoint_json->>'outboxSequence' IS DISTINCT FROM NEW.checkpoint_sequence::TEXT + OR checkpoint_json->>'accountAuthorityGeneration' IS DISTINCT FROM NEW.expected_generation::TEXT + OR checkpoint_json->>'sourceVersion' IS DISTINCT FROM NEW.expected_source_version::TEXT + OR checkpoint_json->>'requestId' IS DISTINCT FROM outbox_row.request_id + OR checkpoint_json->>'eventId' IS DISTINCT FROM outbox_row.event_id + OR checkpoint_json->>'eventDigest' IS DISTINCT FROM outbox_row.event_digest + OR checkpoint_json->'accountSecurityCutoff'->>'accountAuthorityGeneration' IS DISTINCT FROM NEW.expected_generation::TEXT + OR checkpoint_json->'accountSecurityCutoff'->>'outboxStreamKey' IS DISTINCT FROM key + OR checkpoint_json->'accountSecurityCutoff'->>'outboxSequence' IS DISTINCT FROM NEW.checkpoint_sequence::TEXT + OR outbox_row.event_digest IS DISTINCT FROM 'sha256:' || encode(sha256(convert_to(checkpoint_preimage,'UTF8')),'hex') + OR checkpoint_preimage = checkpoint_text THEN + RAISE EXCEPTION 'Security-state checkpoint identity/counters/digest differ' USING ERRCODE = '23514'; + END IF; + END IF; + ELSE + IF NEW.result_generation::NUMERIC <> NEW.expected_generation::NUMERIC + 1 + OR NEW.result_source_version::NUMERIC <> NEW.expected_source_version::NUMERIC + 1 + OR NEW.result_fence::NUMERIC <> NEW.expected_fence::NUMERIC + 1 + OR NEW.result_fence_source_version::NUMERIC <> NEW.expected_fence_source_version::NUMERIC + 1 + OR NEW.event_sequence::NUMERIC <> NEW.checkpoint_sequence::NUMERIC + 1 + OR NEW.result_global_role_source_version::NUMERIC <> NEW.global_role_source_version::NUMERIC + + (CASE WHEN 'GLOBAL_ROLE_CHANGED' = ANY(kinds) THEN 1 ELSE 0 END) + OR authority_row.generation <> NEW.result_generation OR authority_row.source_version <> NEW.result_source_version + OR fence_row.issuance_fence <> NEW.result_fence OR fence_row.source_version <> NEW.result_fence_source_version + OR role_row.global_role_source_version <> NEW.result_global_role_source_version THEN + RAISE EXCEPTION 'Security-state producer result counters differ' USING ERRCODE = '23514'; + END IF; + SELECT * INTO outbox_row FROM account_authority_outbox_events + WHERE outbox_stream_key = key AND request_id = NEW.request_id::TEXT; + SELECT * INTO stream_row FROM account_authority_outbox_streams WHERE outbox_stream_key = key; + IF outbox_row IS NULL OR stream_row IS NULL OR outbox_row.outbox_sequence <> NEW.event_sequence + OR outbox_row.event_id <> NEW.event_id OR outbox_row.event_digest <> NEW.event_digest + OR outbox_row.payload <> NEW.event_payload OR stream_row.last_sequence <> NEW.event_sequence THEN + RAISE EXCEPTION 'Security-state exact outbox receipt differs' USING ERRCODE = '23514'; + END IF; + preimage := '{"accountAuthorityGeneration":"' || NEW.result_generation::TEXT + || '","accountId":"' || NEW.account_uuid::TEXT + || '","accountSecurityCutoff":{"accountAuthorityGeneration":"' || NEW.result_generation::TEXT + || '","outboxSequence":"' || NEW.event_sequence::TEXT || '","outboxStreamKey":"' || key + || '"},"accountState":' || convert_from(NEW.after_state,'UTF8') + || ',"eventId":"account-security-state-event-v1:' || NEW.request_id::TEXT + || '","eventType":"ACCOUNT_SECURITY_STATE_CHANGED","mutationKinds":' + || replace(to_jsonb(kinds)::TEXT, ', ', ',') + || ',"outboxSequence":"' || NEW.event_sequence::TEXT || '","outboxStreamKey":"' || key + || '","requestId":"' || NEW.request_id::TEXT + || '","schemaVersion":"account-auth-account-security-state-event/v1","sourceScope":"account/' + || NEW.account_uuid::TEXT || '","sourceVersion":"' || NEW.result_source_version::TEXT || '"}'; + expected_digest := 'sha256:' || encode(sha256(convert_to(preimage,'UTF8')),'hex'); + expected_wire := replace(preimage, ',"eventId":', ',"eventDigest":"' || expected_digest || '","eventId":'); + IF NEW.event_digest IS DISTINCT FROM expected_digest OR NEW.event_payload IS DISTINCT FROM convert_to(expected_wire,'UTF8') THEN + RAISE EXCEPTION 'Security-state canonical event/digest differs' USING ERRCODE = '23514'; + END IF; + before_json := after_json; + END IF; + IF (before_json->'emailVerified')::BOOLEAN IS DISTINCT FROM account_row.email_verified + OR before_json->>'lifecycleState' IS DISTINCT FROM upper(account_row.lifecycle_state) + OR before_json->'globalRoles' IS DISTINCT FROM to_jsonb(role_row.global_roles) + OR before_json->'loginAuthModes' IS DISTINCT FROM (SELECT jsonb_agg(v ORDER BY v) + FROM unnest(string_to_array(account_row.login_auth_modes, ',')) v) THEN + RAISE EXCEPTION 'Security-state exact owner-state readback differs' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER account_security_state_operation_guard BEFORE INSERT OR UPDATE + ON account_security_state_operations FOR EACH ROW EXECUTE FUNCTION account_security_state_operation_guard(); + +CREATE FUNCTION account_security_state_retention_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + RAISE EXCEPTION 'Security-state operation evidence must be retained' USING ERRCODE = '23514'; + RETURN OLD; +END; +$$; +CREATE TRIGGER account_security_state_delete_denied BEFORE DELETE ON account_security_state_operations + FOR EACH ROW EXECUTE FUNCTION account_security_state_retention_guard(); +CREATE TRIGGER account_security_state_truncate_denied BEFORE TRUNCATE ON account_security_state_operations + FOR EACH STATEMENT EXECUTE FUNCTION account_security_state_retention_guard(); +-- [jooq ignore stop] diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountSecurityStateOperationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountSecurityStateOperationPostgresIntegrationTest.java new file mode 100644 index 0000000000..00842039a6 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountSecurityStateOperationPostgresIntegrationTest.java @@ -0,0 +1,984 @@ +package integration.net.firedevops.firemud.accountservice; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.function.Supplier; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository.SourceChange; +import net.firedevops.firemud.accountservice.dto.AccountSecurityStateMutationRequest; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeState; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Event; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.EventEvidence; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository; +import net.firedevops.firemud.accountservice.repository.AccountLogoutAllOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountPasswordResetOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.repository.AccountSecurityStateOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountSecurityStateOperationRepository.Capture; +import net.firedevops.firemud.accountservice.service.AccountAuthoritySourceEventReadback; +import net.firedevops.firemud.accountservice.service.AccountAuthoritySourceReader; +import net.firedevops.firemud.common.account.authority.AccountSecurityStateAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.AccountSecurityStateAuthorityEventV1Codec.AccountState; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** Synthetic owner producer/correlation fixtures; these are not authenticated runtime mutations. */ +@Testcontainers(disabledWithoutDocker = true) +class AccountSecurityStateOperationPostgresIntegrationTest { + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Test + void pendingClaimAndExactRetryRetainOneOriginalCaptureWithoutSourceMutation() { + Fixture fixture = fixture("78"); + Seed seed = seed(fixture); + var actualSource = + tx( + fixture, + () -> { + var sources = + new net.firedevops.firemud.accountservice.repository + .AccountAuthoritySourceEvidenceRepository( + fixture.dsl(), fixture.generations(), fixture.outbox()); + sources.initializeIssuerIfAbsent("firemud-account-service"); + return sources + .readCurrentIssuerAccountSources( + "firemud-account-service", seed.account().getAccountUuid()) + .account(); + }); + assertThat(actualSource.initializationProvenance()).isEqualTo("ACCOUNT_REPOSITORY_INSERT"); + assertThat(actualSource.checkpoint().sequence()).isZero(); + assertThat(actualSource.initializationTransactionId()) + .isEqualTo(actualSource.accountRepositoryInsertTransactionId()); + assertThat( + fixture + .dsl() + .fetchOne( + "SELECT last_sequence FROM account_authority_outbox_streams WHERE outbox_stream_key = ?", + stream(seed.account().getAccountUuid())) + .get(0, Long.class)) + .isZero(); + Pending pending = pending(fixture, seed, state(false), state(true), 0L, new byte[0]); + var first = tx(fixture, () -> fixture.operations().claim(pending.request(), pending.capture())); + var retry = tx(fixture, () -> fixture.operations().claim(pending.request(), pending.capture())); + assertThat(first.claimed()).isTrue(); + assertThat(retry.claimed()).isFalse(); + assertThat(retry.operation().receipt()).isEmpty(); + assertThat( + AccountSecurityStateOperationRepository.captureBytes( + pending.request(), retry.operation().capture())) + .isEqualTo( + AccountSecurityStateOperationRepository.captureBytes( + pending.request(), pending.capture())); + assertThat( + tx( + fixture, + () -> + fixture + .generations() + .read(AuthorityScope.account(seed.account().getAccountUuid())))) + .isEqualTo(seed.source()); + assertThat( + Objects.requireNonNull( + fixture + .dsl() + .fetchOne( + "SELECT email_verified FROM accounts WHERE id = ?", + seed.account().getId()), + "Expected persisted Account row") + .get(0, Boolean.class)) + .isFalse(); + assertThat(fixture.dsl().fetchCount(DSL.table("account_authority_outbox_events"))).isZero(); + } + + @Test + void zeroReceiptRejectsAbsentMismatchedAndFabricatedV40BaselineWithoutMutation() { + for (String corruption : + List.of( + "DELETE FROM account_authority_source_records WHERE account_uuid = ?", + "UPDATE account_authority_source_records SET account_source_numeric_id = account_source_numeric_id + 1 WHERE account_uuid = ?", + "UPDATE account_authority_source_records SET initialization_transaction_id = initialization_transaction_id + 1, account_repository_insert_transaction_id = account_repository_insert_transaction_id + 1 WHERE account_uuid = ?")) { + Fixture fixture = fixture("78"); + Seed seed = seed(fixture); + Pending pending = pending(fixture, seed, state(false), state(true), 0L, new byte[0]); + // Fault injection only after genuine owner insertion: never create a passing raw baseline. + fixture.dsl().execute("ALTER TABLE account_authority_source_records DISABLE TRIGGER USER"); + try { + fixture.dsl().execute(corruption, seed.account().getAccountUuid()); + } finally { + fixture.dsl().execute("ALTER TABLE account_authority_source_records ENABLE TRIGGER USER"); + } + assertThatThrownBy( + () -> + tx( + fixture, + () -> fixture.operations().claim(pending.request(), pending.capture()))) + .isInstanceOf(org.jooq.exception.DataAccessException.class) + .hasMessageContaining("Security-state pristine baseline is not proved"); + assertThat(fixture.dsl().fetchCount(DSL.table("account_security_state_operations"))).isZero(); + assertThat(fixture.dsl().fetchCount(DSL.table("account_authority_outbox_events"))).isZero(); + assertThat(tx(fixture, () -> fixture.generations().read(seed.source().scope()))) + .isEqualTo(seed.source()); + assertThat( + fixture + .dsl() + .fetchOne( + "SELECT email_verified FROM accounts WHERE id = ?", seed.account().getId()) + .get(0, Boolean.class)) + .isFalse(); + } + } + + @Test + void accountRepositoryRoleSavePersistsGenericHistoryButNotCanonicalRoleAuthority() { + Fixture fixture = fixture("78"); + Seed seed = seed(fixture); + var roleSourceBefore = + fixture + .dsl() + .fetchOne( + "SELECT * FROM account_global_role_sources WHERE account_uuid = ?", + seed.account().getAccountUuid()); + assertThat(roleSourceBefore).isNotNull(); + assertThat(roleSourceBefore.get("global_roles", String[].class)).isEmpty(); + assertThat(roleSourceBefore.get("global_role_source_version", Long.class)).isEqualTo(1L); + + Account saved = + tx( + fixture, + () -> { + Account owner = + new AccountRepository(fixture.dsl()) + .findById(seed.account().getId()) + .orElseThrow(); + owner.setRole("player"); + return new AccountRepository(fixture.dsl()).save(owner); + }); + assertThat(saved.getRole()).isEqualTo("player"); + assertThat( + fixture + .dsl() + .fetchOne( + "SELECT role FROM accounts WHERE account_uuid = ?", saved.getAccountUuid()) + .get("role", String.class)) + .isEqualTo("player"); + + ScopeState current = + tx( + fixture, + () -> fixture.generations().read(AuthorityScope.account(saved.getAccountUuid()))); + assertThat(current.generation()).isEqualTo(2L); + assertThat(current.sourceVersion()).isEqualTo(2L); + assertThat(current.issuanceFence().value()).isEqualTo(2L); + assertThat(current.issuanceFence().sourceVersion()).isEqualTo(2L); + Event genericEvent = + fixture.outbox().findEvent(stream(saved.getAccountUuid()), 1L).orElseThrow(); + var verifiedGenericEvent = + (net.firedevops.firemud.common.account.authority.AccountAuthoritySourceEventV1Codec + .AccountEvent) + net.firedevops.firemud.common.account.authority.AccountAuthoritySourceEventV1Codec + .verify(new String(genericEvent.payload(), StandardCharsets.UTF_8)); + assertThat(verifiedGenericEvent.accountState().globalRole()).isEqualTo("player"); + assertThat(verifiedGenericEvent.mutationKinds()).containsExactly("GLOBAL_ROLE_CHANGED"); + assertThat(verifiedGenericEvent.accountAuthorityGeneration()) + .isEqualTo(Long.toString(current.generation())); + assertThat(verifiedGenericEvent.sourceVersion()) + .isEqualTo(Long.toString(current.sourceVersion())); + assertThat(verifiedGenericEvent.issuanceFence()) + .isEqualTo(Long.toString(current.issuanceFence().value())); + assertThat(verifiedGenericEvent.issuanceFenceSourceVersion()) + .isEqualTo(Long.toString(current.issuanceFence().sourceVersion())); + var currentSourceRecord = + fixture + .dsl() + .fetchOne( + "SELECT current_generation, current_source_version, current_issuance_fence, " + + "current_issuance_fence_source_version, last_outbox_sequence, last_event_id, " + + "last_event_digest FROM account_authority_source_records " + + "WHERE scope_kind = 'ACCOUNT' AND account_uuid = ?", + saved.getAccountUuid()); + assertThat(currentSourceRecord.get("current_generation", Long.class)).isEqualTo(2L); + assertThat(currentSourceRecord.get("current_source_version", Long.class)).isEqualTo(2L); + assertThat(currentSourceRecord.get("current_issuance_fence", Long.class)).isEqualTo(2L); + assertThat(currentSourceRecord.get("current_issuance_fence_source_version", Long.class)) + .isEqualTo(2L); + assertThat(currentSourceRecord.get("last_outbox_sequence", Long.class)).isEqualTo(1L); + assertThat(currentSourceRecord.get("last_event_id", String.class)) + .isEqualTo(genericEvent.eventId()); + assertThat(currentSourceRecord.get("last_event_digest", String.class)) + .isEqualTo(genericEvent.eventDigest()); + + var roleSourceAfter = + fixture + .dsl() + .fetchOne( + "SELECT * FROM account_global_role_sources WHERE account_uuid = ?", + saved.getAccountUuid()); + assertThat(roleSourceAfter).isEqualTo(roleSourceBefore); + assertThat(roleSourceAfter.get("global_roles", String[].class)).isEmpty(); + assertThat(roleSourceAfter.get("global_role_source_version", Long.class)).isEqualTo(1L); + assertThatThrownBy(() -> sourceReadback(fixture).requireCurrentLatest(saved, current)) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy(() -> sourceReader(fixture).readCurrent(saved.getAccountUuid())) + .isInstanceOf(IllegalStateException.class); + } + + @Test + void originalCallerAndFamilyBindingsCannotBeChangedOnRetry() { + Fixture fixture = fixture("78"); + Seed seed = seed(fixture); + Pending pending = pending(fixture, seed, state(false), state(true), 0L, new byte[0]); + tx(fixture, () -> fixture.operations().claim(pending.request(), pending.capture())); + var request = pending.request(); + var changed = + new AccountSecurityStateMutationRequest( + request.requestId(), + request.accountUuid(), + correlation(UUID.randomUUID(), request.requestId()), + request.expectedGeneration(), + request.expectedSourceVersion(), + request.mutationKinds(), + request.desiredState()); + assertThatThrownBy( + () -> tx(fixture, () -> fixture.operations().claim(changed, pending.capture()))) + .isInstanceOf(AccountSecurityStateOperationRepository.OperationConflictException.class); + var wrongKinds = + new AccountSecurityStateMutationRequest( + UUID.randomUUID(), + request.accountUuid(), + request.callerProofBinding(), + 1L, + 1L, + List.of("LOGIN_AUTH_MODES_CHANGED"), + state(true)); + assertThatThrownBy( + () -> tx(fixture, () -> fixture.operations().claim(wrongKinds, pending.capture()))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("capture differs"); + assertThat(fixture.dsl().fetchCount(DSL.table("account_security_state_operations"))) + .isEqualTo(1); + } + + @Test + void concurrentExactClaimsSerializeToOneOriginalRequest() throws Exception { + Fixture fixture = fixture("78"); + Seed seed = seed(fixture); + Pending pending = pending(fixture, seed, state(false), state(true), 0L, new byte[0]); + CountDownLatch ready = new CountDownLatch(2); + try (var executor = Executors.newFixedThreadPool(2)) { + var tasks = + List.of(1, 2).stream() + .map( + ignored -> + executor.submit( + () -> + tx( + fixture, + () -> { + ready.countDown(); + try { + if (!ready.await(10, TimeUnit.SECONDS)) + throw new IllegalStateException( + "Concurrent claims did not start"); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException(interrupted); + } + return fixture + .operations() + .claim(pending.request(), pending.capture()) + .claimed(); + }))) + .toList(); + assertThat( + List.of( + tasks.get(0).get(20, TimeUnit.SECONDS), tasks.get(1).get(20, TimeUnit.SECONDS))) + .containsExactlyInAnyOrder(true, false); + } + assertThat(fixture.dsl().fetchCount(DSL.table("account_security_state_operations"))) + .isEqualTo(1); + } + + @Test + void exactExistingOutboxReceiptCompletesOnceAndHistoricalImagesSurviveLaterAdvance() { + Fixture fixture = fixture("78"); + Seed seed = seed(fixture); + Pending first = pending(fixture, seed, state(false), state(true), 0L, new byte[0]); + tx(fixture, () -> fixture.operations().claim(first.request(), first.capture())); + Event event = producerFixture(fixture, first, false); + var sourceHead = + fixture + .dsl() + .fetchOne( + "SELECT last_outbox_sequence, last_event_id, last_event_digest " + + "FROM account_authority_source_records WHERE account_uuid = ?", + seed.account().getAccountUuid()); + assertThat(sourceHead.get("last_outbox_sequence", Long.class)) + .isEqualTo(event.outboxSequence()); + assertThat(sourceHead.get("last_event_id", String.class)).isEqualTo(event.eventId()); + assertThat(sourceHead.get("last_event_digest", String.class)).isEqualTo(event.eventDigest()); + assertThat(sourceReader(fixture).readCurrent(seed.account().getAccountUuid()).latestEvent()) + .contains(event); + tx( + fixture, + () -> { + var latest = + sourceReadback(fixture) + .requireCurrentLatest( + new AccountRepository(fixture.dsl()) + .findById(seed.account().getId()) + .orElseThrow(), + fixture.generations().read(seed.source().scope())); + assertThat(latest.latestEvent()).contains(event); + return null; + }); + var retained = + tx( + fixture, + () -> fixture.operations().findByRequestId(first.request().requestId()).orElseThrow()); + assertThat(retained.receipt().orElseThrow().event()).isEqualTo(event); + ScopeState current = + tx( + fixture, + () -> + fixture + .generations() + .read(AuthorityScope.account(seed.account().getAccountUuid()))); + Seed newer = new Seed(seed.account(), current); + AccountState after = new AccountState(true, List.of("PASSWORD"), List.of(), "ACTIVE"); + Pending second = pending(fixture, newer, state(true), after, 1L, event.payload()); + tx(fixture, () -> fixture.operations().claim(second.request(), second.capture())); + producerFixture(fixture, second, false); + assertThat( + sourceReader(fixture) + .readCommittedEvent(seed.account().getAccountUuid(), 1L) + .requestedEvent()) + .isEqualTo(event); + tx( + fixture, + () -> { + var account = + new AccountRepository(fixture.dsl()).findById(seed.account().getId()).orElseThrow(); + var source = fixture.generations().read(seed.source().scope()); + sourceReadback(fixture).requireRetainedEvent(account, event, source); + assertThat(sourceReadback(fixture).requireCurrentLatest(account, source).outboxSequence()) + .isEqualTo(2L); + return null; + }); + var retry = tx(fixture, () -> fixture.operations().claim(first.request(), second.capture())); + assertThat(retry.claimed()).isFalse(); + assertThat(retry.operation().receipt().orElseThrow().event().payload()) + .isEqualTo(event.payload()); + assertThat(retry.operation().capture().beforeState()).isEqualTo(state(false)); + assertThat(retry.operation().request().desiredState()).isEqualTo(state(true)); + assertThat(fixture.dsl().fetchCount(DSL.table("account_authority_outbox_events"))).isEqualTo(2); + } + + @Test + void lawfulPrivateFenceAdvanceKeepsLatestSourceEventAndOriginalReceiptUnchanged() { + Fixture fixture = fixture("78"); + Seed seed = seed(fixture); + Pending pending = pending(fixture, seed, state(false), state(true), 0L, new byte[0]); + tx(fixture, () -> fixture.operations().claim(pending.request(), pending.capture())); + Event event = producerFixture(fixture, pending, false); + var original = + tx( + fixture, + () -> + fixture.operations().findByRequestId(pending.request().requestId()).orElseThrow()); + var originalRow = + fixture + .dsl() + .fetchOne( + "SELECT * FROM account_security_state_operations WHERE request_id = ?", + pending.request().requestId()); + ScopeState advanced = + tx( + fixture, + () -> { + new AccountRepository(fixture.dsl()) + .findByIdForUpdate(seed.account().getId()) + .orElseThrow(); + var source = fixture.generations().read(seed.source().scope()); + // Fixture-only private-fence CAS follows the existing guarded counters, without a + // source advance. + assertThat( + fixture + .dsl() + .execute( + "UPDATE account_authority_issuance_fences " + + "SET issuance_fence = issuance_fence + 1, source_version = source_version + 1, updated_at = CURRENT_TIMESTAMP " + + "WHERE account_uuid = ? AND issuance_fence = ? AND source_version = ?", + seed.account().getAccountUuid(), + source.issuanceFence().value(), + source.issuanceFence().sourceVersion())) + .isEqualTo(1); + return fixture.generations().read(seed.source().scope()); + }); + var snapshot = sourceReader(fixture).readCurrent(seed.account().getAccountUuid()); + assertThat(snapshot.latestEvent()).contains(event); + assertThat(snapshot.sourceState()).isEqualTo(advanced); + assertThat(advanced.generation()) + .isEqualTo(original.receipt().orElseThrow().sourceState().generation()); + assertThat(advanced.sourceVersion()) + .isEqualTo(original.receipt().orElseThrow().sourceState().sourceVersion()); + assertThat(advanced.issuanceFence().value()) + .isEqualTo(original.receipt().orElseThrow().sourceState().issuanceFence().value() + 1); + var retained = + tx( + fixture, + () -> + fixture.operations().findByRequestId(pending.request().requestId()).orElseThrow()); + assertThat(retained.receipt()).isEqualTo(original.receipt()); + assertThat( + fixture + .dsl() + .fetchOne( + "SELECT * FROM account_security_state_operations WHERE request_id = ?", + pending.request().requestId())) + .isEqualTo(originalRow); + assertThat(fixture.dsl().fetchCount(DSL.table("account_authority_outbox_events"))).isEqualTo(1); + } + + @Test + void lateReceiptFailureRollsBackEntireFixtureProducerButRetainsOriginalWaitingIntent() { + Fixture fixture = fixture("78"); + Seed seed = seed(fixture); + Pending pending = pending(fixture, seed, state(false), state(true), 0L, new byte[0]); + tx(fixture, () -> fixture.operations().claim(pending.request(), pending.capture())); + assertThatThrownBy(() -> producerFixture(fixture, pending, true)) + .isInstanceOf(IllegalStateException.class); + assertThat( + tx( + fixture, + () -> + fixture + .operations() + .findByRequestId(pending.request().requestId()) + .orElseThrow()) + .receipt()) + .isEmpty(); + assertThat( + tx( + fixture, + () -> + fixture + .generations() + .read(AuthorityScope.account(seed.account().getAccountUuid())))) + .isEqualTo(seed.source()); + assertThat(fixture.dsl().fetchCount(DSL.table("account_authority_outbox_events"))).isZero(); + assertThat( + Objects.requireNonNull( + fixture + .dsl() + .fetchOne( + "SELECT email_verified FROM accounts WHERE id = ?", + seed.account().getId()), + "Expected persisted Account row after rollback") + .get(0, Boolean.class)) + .isFalse(); + assertThat( + Objects.requireNonNull( + fixture + .dsl() + .fetchOne( + "SELECT status FROM account_draft_authorization_source_changes WHERE change_id = ?", + pending.capture().sourceChange().changeId()), + "Expected original V76 source-change row after rollback") + .get(0, String.class)) + .isEqualTo("WAITING"); + } + + @Test + void requestCaptureResultsDeletesAndTruncationRemainGuarded() { + Fixture fixture = fixture("78"); + Seed seed = seed(fixture); + Pending pending = pending(fixture, seed, state(false), state(true), 0L, new byte[0]); + tx(fixture, () -> fixture.operations().claim(pending.request(), pending.capture())); + for (String sql : + List.of( + "UPDATE account_security_state_operations SET request_digest = repeat('b',64)", + "UPDATE account_security_state_operations SET expected_generation = 2", + "DELETE FROM account_security_state_operations", + "TRUNCATE account_security_state_operations")) { + assertThatThrownBy(() -> fixture.dsl().execute(sql)) + .isInstanceOf(org.jooq.exception.DataAccessException.class); + } + producerFixture(fixture, pending, false); + assertThatThrownBy( + () -> + fixture + .dsl() + .execute("UPDATE account_security_state_operations SET event_id = 'changed'")) + .isInstanceOf(org.jooq.exception.DataAccessException.class); + assertThat(fixture.dsl().fetchCount(DSL.table("account_security_state_operations"))) + .isEqualTo(1); + } + + @Test + void substitutedEventStateCannotBecomeTheOriginalReceipt() { + Fixture fixture = fixture("78"); + Seed seed = seed(fixture); + Pending pending = pending(fixture, seed, state(false), state(true), 0L, new byte[0]); + tx(fixture, () -> fixture.operations().claim(pending.request(), pending.capture())); + assertThatThrownBy( + () -> + tx( + fixture, + () -> { + var wrong = + AccountSecurityStateAuthorityEventV1Codec.seal( + AccountSecurityStateMutationRequest.eventPreimage( + pending.request().requestId(), + pending.request().accountUuid(), + "2", + "2", + "1", + pending.request().mutationKinds(), + state(false))); + var event = + fixture + .outbox() + .append( + stream(seed), + pending.request().requestId().toString(), + sequence -> + new EventEvidence( + wrong.eventId(), + wrong.eventDigest(), + wrong.canonicalJsonUtf8())); + fixture + .operations() + .complete( + pending.request(), + event, + new ScopeState( + seed.source().scope(), + 2L, + 2L, + new AccountAuthorityGenerationRepository.IssuanceFence( + seed.account().getAccountUuid(), 2L, 2L)), + 1L); + return null; + })) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("receipt differs"); + assertThat(fixture.dsl().fetchCount(DSL.table("account_authority_outbox_events"))).isZero(); + } + + @Test + void corruptPositiveCheckpointMetadataAndPayloadDenyBeforeNewIntentOrSourceMutation() { + for (String corruption : + List.of( + "event_id = 'substituted'", + "request_id = 'substituted'", + "event_digest = 'sha256:' || repeat('b',64)", + "payload = convert_to('{}','UTF8')")) { + Fixture fixture = fixture("78"); + Seed seed = seed(fixture); + Pending first = pending(fixture, seed, state(false), state(true), 0L, new byte[0]); + tx(fixture, () -> fixture.operations().claim(first.request(), first.capture())); + Event event = producerFixture(fixture, first, false); + ScopeState current = + tx( + fixture, + () -> + fixture + .generations() + .read(AuthorityScope.account(seed.account().getAccountUuid()))); + Pending second = + pending( + fixture, + new Seed(seed.account(), current), + state(true), + new AccountState(true, List.of("PASSWORD"), List.of(), "ACTIVE"), + 1L, + event.payload()); + // Deliberately corrupt immutable storage as a superuser fixture, not a production operation. + fixture.dsl().execute("ALTER TABLE account_authority_outbox_events DISABLE TRIGGER USER"); + fixture.dsl().execute("UPDATE account_authority_outbox_events SET " + corruption); + fixture.dsl().execute("ALTER TABLE account_authority_outbox_events ENABLE TRIGGER USER"); + assertThatThrownBy( + () -> + tx(fixture, () -> fixture.operations().claim(second.request(), second.capture()))) + .isInstanceOf(RuntimeException.class); + assertThat(fixture.dsl().fetchCount(DSL.table("account_security_state_operations"))) + .isEqualTo(1); + assertThat( + tx( + fixture, + () -> + fixture + .generations() + .read(AuthorityScope.account(seed.account().getAccountUuid())))) + .isEqualTo(current); + } + } + + @Test + void retainedReceiptCannotLeadRegressedCurrentAuthorityOrCheckpoint() { + for (String table : + List.of("account_authority_generations", "account_authority_outbox_streams")) { + Fixture fixture = fixture("78"); + Seed seed = seed(fixture); + Pending pending = pending(fixture, seed, state(false), state(true), 0L, new byte[0]); + tx(fixture, () -> fixture.operations().claim(pending.request(), pending.capture())); + producerFixture(fixture, pending, false); + fixture.dsl().execute("ALTER TABLE " + table + " DISABLE TRIGGER USER"); + fixture + .dsl() + .execute( + table.equals("account_authority_generations") + ? "UPDATE account_authority_generations SET generation = 1, source_version = 1" + : "UPDATE account_authority_outbox_streams SET last_sequence = 0"); + fixture.dsl().execute("ALTER TABLE " + table + " ENABLE TRIGGER USER"); + assertThatThrownBy( + () -> + tx( + fixture, + () -> fixture.operations().findByRequestId(pending.request().requestId()))) + .isInstanceOf(RuntimeException.class); + } + } + + @Test + void missingSecurityReceiptAndChangedCurrentPoststateCannotCommit() { + Fixture missing = fixture("78"); + Seed seed = seed(missing); + Pending pending = pending(missing, seed, state(false), state(true), 0L, new byte[0]); + tx(missing, () -> missing.operations().claim(pending.request(), pending.capture())); + assertThatThrownBy(() -> producerFixture(missing, pending, false, false)) + .isInstanceOf(RuntimeException.class); + assertThat(missing.dsl().fetchCount(DSL.table("account_authority_outbox_events"))).isZero(); + assertThat( + missing + .dsl() + .fetchOne( + "SELECT email_verified FROM accounts WHERE id = ?", seed.account().getId()) + .get(0, Boolean.class)) + .isFalse(); + + Fixture changed = fixture("78"); + Seed other = seed(changed); + Pending original = pending(changed, other, state(false), state(true), 0L, new byte[0]); + tx(changed, () -> changed.operations().claim(original.request(), original.capture())); + producerFixture(changed, original, false); + assertThatThrownBy( + () -> + changed + .dsl() + .execute( + "UPDATE accounts SET email_verified = false WHERE id = ?", + other.account().getId())) + .isInstanceOf(RuntimeException.class); + assertThat( + changed + .dsl() + .fetchOne( + "SELECT email_verified FROM accounts WHERE id = ?", other.account().getId()) + .get(0, Boolean.class)) + .isTrue(); + tx( + changed, + () -> { + sourceReadback(changed) + .requireCurrentLatest( + new AccountRepository(changed.dsl()) + .findById(other.account().getId()) + .orElseThrow(), + changed.generations().read(other.source().scope())); + return null; + }); + } + + @Test + void forwardMigrationRetainsOriginalAccountAuthorityAndRoleImagesWithoutBackfill() { + Fixture fixture = fixture("77"); + Seed seed = seed(fixture); + var before = + fixture + .dsl() + .fetch( + "SELECT account_uuid, account_uuid_source_numeric_id, account_uuid_provenance, email_verified, login_auth_modes, lifecycle_state, password_hash FROM accounts"); + var authority = fixture.dsl().fetch("SELECT * FROM account_authority_generations"); + var roles = fixture.dsl().fetch("SELECT * FROM account_global_role_sources"); + migrate(fixture.dataSource(), fixture.schema(), "78"); + assertThat( + fixture + .dsl() + .fetch( + "SELECT account_uuid, account_uuid_source_numeric_id, account_uuid_provenance, email_verified, login_auth_modes, lifecycle_state, password_hash FROM accounts")) + .isEqualTo(before); + assertThat(fixture.dsl().fetch("SELECT * FROM account_authority_generations")) + .isEqualTo(authority); + assertThat(fixture.dsl().fetch("SELECT * FROM account_global_role_sources")).isEqualTo(roles); + assertThat(fixture.dsl().fetchCount(DSL.table("account_security_state_operations"))).isZero(); + assertThat(seed.account().getAccountUuid()).isNotNull(); + } + + private Event producerFixture(Fixture fixture, Pending pending, boolean lateFailure) { + return producerFixture(fixture, pending, lateFailure, true); + } + + private Event producerFixture( + Fixture fixture, Pending pending, boolean lateFailure, boolean retainReceipt) { + return tx( + fixture, + () -> { + // Fixture-only sole mutation writer. Storage itself never calls these operations. + if (!fixture.fences().sourceMutationPermitted(pending.capture().sourceChange())) + throw new IllegalStateException("Fixture source is not settled"); + var sources = + new AccountAuthoritySourceEvidenceRepository( + fixture.dsl(), fixture.generations(), fixture.outbox()); + var currentSource = + sources + .readCurrentIssuerAccountSources( + "firemud-account-service", pending.request().accountUuid()) + .account(); + var retained = pending.capture().sourceState(); + if (!currentSource.scope().equals(retained.scope()) + || currentSource.generation() != retained.generation() + || currentSource.sourceVersion() != retained.sourceVersion() + || !currentSource.issuanceFence().equals(retained.issuanceFence())) { + throw new IllegalStateException( + "Fixture retained source differs from actual owner readback"); + } + ScopeState advanced = + sources.prepareClosedAccountAdvance(pending.request().accountUuid(), currentSource); + fixture + .dsl() + .execute( + "UPDATE accounts SET email_verified = ?, login_auth_modes = ?, lifecycle_state = ? WHERE account_uuid = ?", + pending.request().desiredState().emailVerified(), + String.join(",", pending.request().desiredState().loginAuthModes()), + pending + .request() + .desiredState() + .lifecycleState() + .toLowerCase(java.util.Locale.ROOT), + pending.request().accountUuid()); + Event event = + fixture + .outbox() + .append( + stream(pending.request().accountUuid()), + pending.request().requestId().toString(), + sequence -> { + var sealed = + AccountSecurityStateAuthorityEventV1Codec.seal( + AccountSecurityStateMutationRequest.eventPreimage( + pending.request().requestId(), + pending.request().accountUuid(), + Long.toString(advanced.generation()), + Long.toString(advanced.sourceVersion()), + Long.toString(sequence), + pending.request().mutationKinds(), + pending.request().desiredState())); + return new EventEvidence( + sealed.eventId(), sealed.eventDigest(), sealed.canonicalJsonUtf8()); + }); + fixture.fences().markSourceCommitted(pending.capture().sourceChange()); + if (retainReceipt) fixture.operations().complete(pending.request(), event, advanced, 1L); + if (lateFailure) + throw new IllegalStateException("Late fixture failure after receipt completion"); + return event; + }); + } + + private Pending pending( + Fixture fixture, + Seed seed, + AccountState before, + AccountState after, + long checkpointSequence, + byte[] checkpointPayload) { + UUID requestId = UUID.randomUUID(); + UUID account = seed.account().getAccountUuid(); + var request = + new AccountSecurityStateMutationRequest( + requestId, + account, + correlation(account, requestId), + seed.source().generation(), + seed.source().sourceVersion(), + AccountSecurityStateOperationRepository.detectedKinds(before, after), + after); + var draft = + new Capture( + seed.account().getId(), + seed.account().getAccountUuidProvenance(), + before, + seed.source(), + checkpointSequence, + checkpointPayload, + 1L, + null); + byte[] captureBytes = AccountSecurityStateOperationRepository.captureBytes(request, draft); + var source = + new SourceEvidence( + SourceKind.ACCOUNT, + account.toString(), + Long.toString(seed.source().generation()), + Long.toString(seed.source().sourceVersion()), + stream(account), + Long.toString(checkpointSequence), + captureBytes); + var change = new SourceChange(UUID.randomUUID(), List.of(source), captureBytes); + var capture = + new Capture( + draft.accountId(), + draft.provenance(), + before, + seed.source(), + checkpointSequence, + checkpointPayload, + 1L, + change); + tx( + fixture, + () -> { + fixture.fences().requestSourceChange(change); + return null; + }); + return new Pending(request, capture); + } + + private AccountAuthoritySourceEventReadback sourceReadback(Fixture fixture) { + return new AccountAuthoritySourceEventReadback( + fixture.outbox(), + new AccountPasswordResetOperationRepository(fixture.dsl()), + new AccountLogoutAllOperationRepository(fixture.dsl()), + fixture.operations()); + } + + private AccountAuthoritySourceReader sourceReader(Fixture fixture) { + return new AccountAuthoritySourceReader( + new AccountRepository(fixture.dsl()), + fixture.generations(), + fixture.outbox(), + sourceReadback(fixture), + fixture.transaction().getTransactionManager()); + } + + private Fixture fixture(String version) { + String schema = "security_state_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setUrl( + postgres.getJdbcUrl() + + (postgres.getJdbcUrl().contains("?") ? "&" : "?") + + "currentSchema=" + + schema); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + migrate(dataSource, schema, version); + DSLContext dsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + return new Fixture( + schema, + dataSource, + dsl, + new TransactionTemplate(new DataSourceTransactionManager(dataSource)), + new AccountAuthorityGenerationRepository(dsl), + new AccountAuthorityOutboxRepository(dsl), + new DraftAuthorizationFenceRepository(dsl), + new AccountSecurityStateOperationRepository(dsl)); + } + + private Seed seed(Fixture fixture) { + return tx( + fixture, + () -> { + Account account = new Account(); + String id = UUID.randomUUID().toString().substring(0, 12); + account.setUsername("security-" + id); + account.setEmail(id + "@example.test"); + account.setPasswordHash("synthetic-verifier"); + account = new AccountRepository(fixture.dsl()).save(account); + new AccountAuthoritySourceEvidenceRepository( + fixture.dsl(), fixture.generations(), fixture.outbox()) + .initializeIssuerIfAbsent("firemud-account-service"); + ScopeState source = + fixture.generations().read(AuthorityScope.account(account.getAccountUuid())); + return new Seed(account, source); + }); + } + + private void migrate(DriverManagerDataSource dataSource, String schema, String version) { + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .target(version) + .load() + .migrate(); + } + + private static T tx(Fixture fixture, Supplier work) { + return fixture.transaction().execute(status -> work.get()); + } + + private static AccountState state(boolean verified) { + return new AccountState(verified, List.of("EMAIL_OTP", "PASSWORD"), List.of(), "ACTIVE"); + } + + private static String stream(Seed seed) { + return stream(seed.account().getAccountUuid()); + } + + private static String stream(UUID account) { + return "account:auth-authority:v1:account/" + account; + } + + private static byte[] correlation(UUID actor, UUID operation) { + return ("{\"actorAccountUuid\":\"" + + actor + + "\",\"ownerEvidenceDigest\":\"sha256:" + + "a".repeat(64) + + "\",\"ownerOperationId\":\"" + + operation + + "\",\"schemaVersion\":\"account-security-state-caller-correlation/v1\"}") + .getBytes(StandardCharsets.UTF_8); + } + + private record Fixture( + String schema, + DriverManagerDataSource dataSource, + DSLContext dsl, + TransactionTemplate transaction, + AccountAuthorityGenerationRepository generations, + AccountAuthorityOutboxRepository outbox, + DraftAuthorizationFenceRepository fences, + AccountSecurityStateOperationRepository operations) {} + + private record Seed(Account account, ScopeState source) {} + + private record Pending(AccountSecurityStateMutationRequest request, Capture capture) {} +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFencePostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFencePostgresIntegrationTest.java new file mode 100644 index 0000000000..c1e9720f24 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFencePostgresIntegrationTest.java @@ -0,0 +1,661 @@ +package integration.net.firedevops.firemud.accountservice.authordraft; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.function.Supplier; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceBinding.Outcome; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceBinding.Owner; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceBinding.OwnerReadback; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository.Ordering; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository.Settlement; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository.SourceChange; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.exception.DataAccessException; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * Component fixtures stipulate authenticated current-source capture and authenticated definitive + * owner readback. They do not implement or prove those absent producers, RPC or source-writer + * gates. + */ +@Testcontainers(disabledWithoutDocker = true) +class DraftAuthorizationFencePostgresIntegrationTest { + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Test + void revokeBeforeCommitDeniesDelayedRequestsUntilBothDefinitiveAborts() { + Context context = context(); + DraftAuthorizationFenceBinding binding = binding(); + SourceChange change = change(binding); + tx(context, () -> context.repository().reserve(binding)); + assertThat(tx(context, () -> context.repository().requestSourceChange(change))).isFalse(); + assertThat(tx(context, () -> context.repository().read(binding)).ordering()) + .isEqualTo(Ordering.REVOKE_ORDER); + assertThatThrownBy(() -> tx(context, () -> context.repository().claimCommitOrder(binding))) + .isInstanceOf(IllegalStateException.class); + owner(context, binding, Owner.WORLD, Outcome.DEFINITIVELY_ABORTED, new byte[] {1}); + assertThat(tx(context, () -> context.repository().sourceMutationPermitted(change))).isFalse(); + owner(context, binding, Owner.GAME_DESIGN, Outcome.DEFINITIVELY_ABORTED, new byte[] {2}); + assertThat(tx(context, () -> context.repository().sourceMutationPermitted(change))).isTrue(); + tx( + context, + () -> { + context.repository().markSourceCommitted(change); + return null; + }); + assertThatThrownBy(() -> tx(context, () -> context.repository().claimCommitOrder(binding))) + .isInstanceOf(IllegalStateException.class); + } + + @Test + void worldCommittedAndGameDesignUnknownSurviveRestartAndBlockSourceUntilExactBothReadbacks() { + Context context = context(); + DraftAuthorizationFenceBinding binding = binding(); + tx(context, () -> context.repository().reserve(binding)); + var ordered = tx(context, () -> context.repository().claimCommitOrder(binding)); + SourceChange change = change(binding); + assertThat(tx(context, () -> context.repository().requestSourceChange(change))).isFalse(); + owner(context, binding, Owner.WORLD, Outcome.COMMITTED, new byte[] {4}); + Context restarted = + new Context( + context.dsl(), + new DraftAuthorizationFenceRepository(context.dsl()), + context.transaction()); + assertThat(tx(restarted, () -> restarted.repository().sourceMutationPermitted(change))) + .isFalse(); + assertThat(tx(restarted, () -> restarted.repository().readSettlement(binding))) + .isEqualTo(Settlement.PENDING); + assertThat( + tx(restarted, () -> restarted.repository().readOwnerResult(binding, Owner.GAME_DESIGN))) + .isEmpty(); + assertSourceGuardBlocked(restarted, change); + // Missing GD evidence models timeout/unavailable/absent owner row: no terminality is + // synthesized. + assertThat(tx(restarted, () -> restarted.repository().read(binding)).orderedAt()) + .isEqualTo(ordered.orderedAt()); + owner(restarted, binding, Owner.GAME_DESIGN, Outcome.COMMITTED, new byte[] {5}); + assertThat(tx(restarted, () -> restarted.repository().readSettlement(binding))) + .isEqualTo(Settlement.COMMITTED); + assertThat(tx(restarted, () -> restarted.repository().sourceMutationPermitted(change))) + .isTrue(); + tx( + restarted, + () -> { + restarted.repository().markSourceCommitted(change); + return null; + }); + assertThat(tx(restarted, () -> restarted.repository().requestSourceChange(change))).isTrue(); + assertThat(tx(restarted, () -> restarted.repository().claimCommitOrder(binding)).orderedAt()) + .isEqualTo(ordered.orderedAt()); + owner(restarted, binding, Owner.WORLD, Outcome.COMMITTED, new byte[] {4}); + assertThatThrownBy( + () -> owner(restarted, binding, Owner.WORLD, Outcome.COMMITTED, new byte[] {9})) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void commitOrderWithBothDefinitiveAbortsReleasesOriginalWaitingIntentWithoutReopening() { + Context context = context(); + DraftAuthorizationFenceBinding binding = binding(); + tx(context, () -> context.repository().reserve(binding)); + var ordered = tx(context, () -> context.repository().claimCommitOrder(binding)); + SourceChange change = change(binding); + assertThat(tx(context, () -> context.repository().requestSourceChange(change))).isFalse(); + owner(context, binding, Owner.WORLD, Outcome.DEFINITIVELY_ABORTED, new byte[] {21}); + assertThat(tx(context, () -> context.repository().sourceMutationPermitted(change))).isFalse(); + owner(context, binding, Owner.GAME_DESIGN, Outcome.DEFINITIVELY_ABORTED, new byte[] {22}); + assertThat(tx(context, () -> context.repository().readSettlement(binding))) + .isEqualTo(Settlement.FAILED_NONPUBLICATION); + assertThat(tx(context, () -> context.repository().sourceMutationPermitted(change))).isTrue(); + var waiting = tx(context, () -> context.repository().readSourceChange(change)); + tx( + context, + () -> { + context.repository().markSourceCommitted(change); + return null; + }); + var committed = tx(context, () -> context.repository().readSourceChange(change)); + assertThat(committed.status()).isEqualTo("SOURCE_COMMITTED"); + assertThat(committed.requestedAt()).isEqualTo(waiting.requestedAt()); + assertThat(committed.binding()).containsExactly(waiting.binding()); + tx( + context, + () -> { + context.repository().markSourceCommitted(change); + return null; + }); + var replay = tx(context, () -> context.repository().readSourceChange(change)); + assertThat(replay.committedAt()).isEqualTo(committed.committedAt()); + assertThat(tx(context, () -> context.repository().sourceMutationPermitted(change))).isFalse(); + assertThat(tx(context, () -> context.repository().read(binding)).ordering()) + .isEqualTo(Ordering.COMMIT_ORDER); + assertThat(tx(context, () -> context.repository().read(binding)).orderedAt()) + .isEqualTo(ordered.orderedAt()); + owner(context, binding, Owner.WORLD, Outcome.DEFINITIVELY_ABORTED, new byte[] {21}); + assertThatThrownBy( + () -> owner(context, binding, Owner.WORLD, Outcome.COMMITTED, new byte[] {23})) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void bothMixedDirectionsFailNonpublicationAndReleaseOnlyAfterBothExactReadbacks() { + for (Outcome worldOutcome : List.of(Outcome.COMMITTED, Outcome.DEFINITIVELY_ABORTED)) { + Context context = context(); + DraftAuthorizationFenceBinding binding = binding(); + tx(context, () -> context.repository().reserve(binding)); + var ordered = tx(context, () -> context.repository().claimCommitOrder(binding)); + SourceChange change = change(binding); + assertThat(tx(context, () -> context.repository().requestSourceChange(change))).isFalse(); + var waiting = tx(context, () -> context.repository().readSourceChange(change)); + owner(context, binding, Owner.WORLD, worldOutcome, new byte[] {1}); + var originalWorld = + tx(context, () -> context.repository().readOwnerResult(binding, Owner.WORLD)) + .orElseThrow(); + assertThat(tx(context, () -> context.repository().readSettlement(binding))) + .isEqualTo(Settlement.PENDING); + assertThat(tx(context, () -> context.repository().sourceMutationPermitted(change))).isFalse(); + assertSourceGuardBlocked(context, change); + Outcome gameDesignOutcome = + worldOutcome == Outcome.COMMITTED ? Outcome.DEFINITIVELY_ABORTED : Outcome.COMMITTED; + owner(context, binding, Owner.GAME_DESIGN, gameDesignOutcome, new byte[] {2}); + assertThat(tx(context, () -> context.repository().readSettlement(binding))) + .isEqualTo(Settlement.FAILED_NONPUBLICATION); + assertThat(tx(context, () -> context.repository().requestSourceChange(change))).isTrue(); + assertThat(tx(context, () -> context.repository().sourceMutationPermitted(change))).isTrue(); + tx( + context, + () -> { + context.repository().markSourceCommitted(change); + return null; + }); + var committed = tx(context, () -> context.repository().readSourceChange(change)); + assertThat(committed.status()).isEqualTo("SOURCE_COMMITTED"); + assertThat(committed.binding()).containsExactly(waiting.binding()); + assertThat(committed.requestedAt()).isEqualTo(waiting.requestedAt()); + assertThat(tx(context, () -> context.repository().sourceMutationPermitted(change))).isFalse(); + assertThat(tx(context, () -> context.repository().read(binding)).ordering()) + .isEqualTo(Ordering.COMMIT_ORDER); + assertThat(tx(context, () -> context.repository().read(binding)).orderedAt()) + .isEqualTo(ordered.orderedAt()); + owner(context, binding, Owner.WORLD, worldOutcome, new byte[] {1}); + var replay = + tx(context, () -> context.repository().readOwnerResult(binding, Owner.WORLD)) + .orElseThrow(); + assertThat(replay.outcome()).isEqualTo(originalWorld.outcome()); + assertThat(replay.readback()).containsExactly(originalWorld.readback()); + assertThat(replay.recordedAt()).isEqualTo(originalWorld.recordedAt()); + assertThatThrownBy(() -> owner(context, binding, Owner.WORLD, worldOutcome, new byte[] {9})) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> owner(context, binding, Owner.WORLD, gameDesignOutcome, new byte[] {1})) + .isInstanceOf(IllegalArgumentException.class); + } + } + + @Test + void revokeOrderWithEitherMixedDirectionCannotAuthorizeSourceMutation() { + for (Outcome worldOutcome : List.of(Outcome.COMMITTED, Outcome.DEFINITIVELY_ABORTED)) { + Context context = context(); + DraftAuthorizationFenceBinding binding = binding(); + tx(context, () -> context.repository().reserve(binding)); + SourceChange change = change(binding); + assertThat(tx(context, () -> context.repository().requestSourceChange(change))).isFalse(); + owner(context, binding, Owner.WORLD, worldOutcome, new byte[] {1}); + owner( + context, + binding, + Owner.GAME_DESIGN, + worldOutcome == Outcome.COMMITTED ? Outcome.DEFINITIVELY_ABORTED : Outcome.COMMITTED, + new byte[] {2}); + assertThat(tx(context, () -> context.repository().read(binding)).ordering()) + .isEqualTo(Ordering.REVOKE_ORDER); + assertThat(tx(context, () -> context.repository().readSettlement(binding))) + .isEqualTo(Settlement.PENDING); + assertThat(tx(context, () -> context.repository().requestSourceChange(change))).isFalse(); + assertThat(tx(context, () -> context.repository().sourceMutationPermitted(change))).isFalse(); + assertThatThrownBy( + () -> + tx( + context, + () -> { + context.repository().markSourceCommitted(change); + return null; + })) + .isInstanceOf(IllegalStateException.class); + assertSourceGuardBlocked(context, change); + } + } + + @Test + void changedCompleteBindingsConflictWithoutRewritingOriginal() { + Context context = context(); + DraftAuthorizationFenceBinding original = binding(); + var stored = tx(context, () -> context.repository().reserve(original)); + assertThat(tx(context, () -> context.repository().readSettlement(original))) + .isEqualTo(Settlement.PENDING); + for (int field = 0; field < 6; field++) { + DraftAuthorizationFenceBinding changed = changed(original, field); + assertThatThrownBy(() -> tx(context, () -> context.repository().reserve(changed))) + .isInstanceOf(IllegalArgumentException.class); + } + var replay = tx(context, () -> context.repository().reserve(original)); + assertThat(replay.binding()).containsExactly(stored.binding()); + assertThat(replay.reservedAt()).isEqualTo(stored.reservedAt()); + } + + @Test + void inconsistentOrMalformedCompleteBindingsFailBeforeReservationStorage() { + Context context = context(); + DraftAuthorizationFenceBinding b = binding(); + for (int field = 0; field < 9; field++) { + int changedField = field; + byte[] bytes = field == 6 ? new byte[] {11} : b.gameDesignBinding(); + if (field == 8) { + bytes = + new String(bytes, StandardCharsets.UTF_8) + .replace("\"revisionOrder\":\"0\"", "\"revisionOrder\":\"1\"") + .getBytes(StandardCharsets.UTF_8); + } + byte[] gameDesign = bytes; + byte[] input = field == 5 ? new byte[] {10} : gameDesign; + String digest = + field == 7 + ? DraftAuthorizationFenceBinding.digest(new byte[] {12}) + : DraftAuthorizationFenceBinding.digest(input); + assertThatThrownBy( + () -> + tx( + context, + () -> + context + .repository() + .reserve( + new DraftAuthorizationFenceBinding( + b.operationId(), + changedField == 0 ? UUID.randomUUID() : b.requestId(), + changedField == 1 ? UUID.randomUUID() : b.commitId(), + b.fenceId(), + b.actorAccountId(), + changedField == 2 ? UUID.randomUUID() : b.tenantId(), + changedField == 3 ? UUID.randomUUID() : b.versionId(), + changedField == 4 ? "different/base" : b.baseCommitId(), + b.expectedDraftEpoch(), + gameDesign, + input, + digest, + b.sources())))) + .isInstanceOf(IllegalArgumentException.class); + assertThat(context.dsl().fetchCount(DSL.table("account_draft_authorization_fences"))) + .isZero(); + assertThat(context.dsl().fetchCount(DSL.table("account_draft_authorization_sources"))) + .isZero(); + } + var stored = tx(context, () -> context.repository().reserve(b)); + assertThat(tx(context, () -> context.repository().reserve(b)).binding()) + .containsExactly(stored.binding()); + } + + @Test + void rollbackPreservesReservationAndIntentTogetherAndDisjointSourcesDoNotConflict() { + Context context = context(); + DraftAuthorizationFenceBinding original = binding(); + assertThatThrownBy( + () -> + tx( + context, + () -> { + context.repository().reserve(original); + context.repository().requestSourceChange(change(original)); + throw new IllegalStateException("injected rollback"); + })) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy(() -> tx(context, () -> context.repository().read(original))) + .isInstanceOf(IllegalArgumentException.class); + tx(context, () -> context.repository().reserve(original)); + tx(context, () -> context.repository().requestSourceChange(change(original))); + DraftAuthorizationFenceBinding independent = binding(); + tx(context, () -> context.repository().reserve(independent)); + assertThat(tx(context, () -> context.repository().claimCommitOrder(independent)).ordering()) + .isEqualTo(Ordering.COMMIT_ORDER); + } + + @Test + void distinctPendingChangesCannotRetainTwoOldCapturesForTheSameSource() { + Context context = context(); + DraftAuthorizationFenceBinding binding = binding(); + SourceChange first = change(binding); + SourceChange second = change(binding); + tx(context, () -> context.repository().reserve(binding)); + tx(context, () -> context.repository().claimCommitOrder(binding)); + assertThat(tx(context, () -> context.repository().requestSourceChange(first))).isFalse(); + var original = tx(context, () -> context.repository().readSourceChange(first)); + + assertThatThrownBy(() -> tx(context, () -> context.repository().requestSourceChange(second))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("already pending"); + assertThat(context.dsl().fetchCount(DSL.table("account_draft_authorization_source_changes"))) + .isEqualTo(1); + assertThat(tx(context, () -> context.repository().requestSourceChange(first))).isFalse(); + var exactRetry = tx(context, () -> context.repository().readSourceChange(first)); + assertThat(exactRetry.binding()).containsExactly(original.binding()); + assertThat(exactRetry.requestedAt()).isEqualTo(original.requestedAt()); + + // This storage fixture stipulates definitive owner evidence; it does not authenticate it. + owner(context, binding, Owner.WORLD, Outcome.COMMITTED, new byte[] {1}); + owner(context, binding, Owner.GAME_DESIGN, Outcome.COMMITTED, new byte[] {2}); + tx( + context, + () -> { + context.repository().markSourceCommitted(first); + return null; + }); + assertThat(tx(context, () -> context.repository().requestSourceChange(second))).isTrue(); + assertThat(context.dsl().fetchCount(DSL.table("account_draft_authorization_source_changes"))) + .isEqualTo(2); + } + + @Test + void concurrentDistinctSourceClaimsAdmitOnlyOnePendingCaptureWithoutBlockingDisjointSources() + throws Exception { + Context context = context(); + DraftAuthorizationFenceBinding binding = binding(); + SourceChange first = change(binding); + SourceChange second = change(binding); + tx(context, () -> context.repository().reserve(binding)); + tx(context, () -> context.repository().claimCommitOrder(binding)); + CountDownLatch firstClaimed = new CountDownLatch(1); + CountDownLatch secondStarted = new CountDownLatch(1); + try (var executor = Executors.newFixedThreadPool(2)) { + var firstTask = + executor.submit( + () -> + tx( + context, + () -> { + boolean permitted = context.repository().requestSourceChange(first); + firstClaimed.countDown(); + await(secondStarted); + return permitted; + })); + var secondTask = + executor.submit( + () -> { + await(firstClaimed); + secondStarted.countDown(); + assertThatThrownBy( + () -> tx(context, () -> context.repository().requestSourceChange(second))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("already pending"); + }); + assertThat(firstTask.get(15, TimeUnit.SECONDS)).isFalse(); + secondTask.get(15, TimeUnit.SECONDS); + } + assertThat(context.dsl().fetchCount(DSL.table("account_draft_authorization_source_changes"))) + .isEqualTo(1); + assertThat(tx(context, () -> context.repository().requestSourceChange(first))).isFalse(); + SourceChange disjoint = change(binding()); + assertThat(tx(context, () -> context.repository().requestSourceChange(disjoint))).isTrue(); + assertThat(context.dsl().fetchCount(DSL.table("account_draft_authorization_source_changes"))) + .isEqualTo(2); + } + + @Test + void concurrentCommitOrderAndRevocationChooseExactlyOneDurableOrdering() throws Exception { + for (boolean commitWins : List.of(true, false)) { + Context context = context(); + DraftAuthorizationFenceBinding binding = binding(); + SourceChange change = change(binding); + tx(context, () -> context.repository().reserve(binding)); + CountDownLatch firstOrdered = new CountDownLatch(1); + CountDownLatch secondStarted = new CountDownLatch(1); + try (var executor = Executors.newFixedThreadPool(2)) { + var first = + executor.submit( + () -> + tx( + context, + () -> { + if (commitWins) { + context.repository().claimCommitOrder(binding); + } else { + context.repository().requestSourceChange(change); + } + firstOrdered.countDown(); + await(secondStarted); + return null; + })); + var second = + executor.submit( + () -> { + await(firstOrdered); + secondStarted.countDown(); + if (commitWins) { + return tx(context, () -> context.repository().requestSourceChange(change)); + } + assertThatThrownBy( + () -> tx(context, () -> context.repository().claimCommitOrder(binding))) + .isInstanceOf(IllegalStateException.class); + return false; + }); + first.get(15, TimeUnit.SECONDS); + assertThat(second.get(15, TimeUnit.SECONDS)).isFalse(); + } + assertThat(tx(context, () -> context.repository().read(binding)).ordering()) + .isEqualTo(commitWins ? Ordering.COMMIT_ORDER : Ordering.REVOKE_ORDER); + } + } + + private void assertSourceGuardBlocked(Context context, SourceChange change) { + assertThatThrownBy( + () -> + tx( + context, + () -> + context + .dsl() + .execute( + "UPDATE account_draft_authorization_source_changes" + + " SET status = 'SOURCE_COMMITTED', committed_at = CURRENT_TIMESTAMP" + + " WHERE change_id = ?", + change.changeId()))) + .isInstanceOf(DataAccessException.class); + } + + private Context context() { + String schema = "draft_fence_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource source = new DriverManagerDataSource(); + source.setUrl(postgres.getJdbcUrl()); + source.setUsername(postgres.getUsername()); + source.setPassword(postgres.getPassword()); + source.setSchema(schema); + Flyway.configure() + .dataSource(source) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .load() + .migrate(); + DSLContext dsl = DSL.using(new TransactionAwareDataSourceProxy(source), SQLDialect.POSTGRES); + TransactionTemplate transaction = + new TransactionTemplate(new DataSourceTransactionManager(source)); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + return new Context(dsl, new DraftAuthorizationFenceRepository(dsl), transaction); + } + + private DraftAuthorizationFenceBinding binding() { + UUID account = UUID.randomUUID(); + SourceEvidence source = + new SourceEvidence( + SourceKind.ACCOUNT, + account.toString(), + "3", + "5", + "stream/" + account, + "2", + new byte[] {7}); + DraftCommitBinding complete = + completeBinding( + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + "opaque/base:9007199254740993", + "world-payload", + UUID.randomUUID()); + return new DraftAuthorizationFenceBinding( + UUID.randomUUID(), + complete.requestId(), + complete.commitId(), + UUID.randomUUID(), + account, + complete.target().canonicalTenantId(), + complete.target().canonicalVersionId(), + complete.baseCommitId(), + "2", + complete.canonicalBytes(), + complete.canonicalBytes(), + complete.digest(), + List.of(source)); + } + + private DraftAuthorizationFenceBinding changed(DraftAuthorizationFenceBinding b, int field) { + SourceEvidence prior = b.sources().getFirst(); + SourceEvidence changedSource = + new SourceEvidence( + prior.kind(), + prior.scopeId(), + "4", + prior.sourceVersion(), + prior.checkpointStream(), + prior.checkpointSequence(), + prior.evidence()); + DraftCommitBinding priorComplete = + DraftCommitBinding.fromStored( + new String(b.gameDesignBinding(), StandardCharsets.UTF_8), b.inputDigest()); + DraftCommitBinding complete = + completeBinding( + field == 1 ? UUID.randomUUID() : b.tenantId(), + field == 2 ? UUID.randomUUID() : b.versionId(), + b.requestId(), + b.commitId(), + b.baseCommitId(), + field == 4 ? "changed-world-payload" : priorComplete.revisions().getFirst().payload(), + field == 5 ? UUID.randomUUID() : priorComplete.revisions().getFirst().revisionId()); + return new DraftAuthorizationFenceBinding( + b.operationId(), + b.requestId(), + b.commitId(), + b.fenceId(), + field == 0 ? UUID.randomUUID() : b.actorAccountId(), + complete.target().canonicalTenantId(), + complete.target().canonicalVersionId(), + b.baseCommitId(), + b.expectedDraftEpoch(), + complete.canonicalBytes(), + complete.canonicalBytes(), + complete.digest(), + field == 3 ? List.of(changedSource) : b.sources()); + } + + private DraftCommitBinding completeBinding( + UUID tenant, + UUID version, + UUID request, + UUID commit, + String base, + String payload, + UUID revision) { + return DraftCommitBinding.create( + new TargetProof(tenant, version, 1, "tenant-key", 2, "tenant-key", "NEW_GAME_ROW"), + request, + commit, + base, + List.of( + new RevisionPayload("0", revision, DraftCommitBinding.Owner.WORLD_MANAGEMENT, payload)), + List.of( + new AffectedUnit( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + "region", + "region-1", + "aggregate", + "region-1", + "9007199254740999"))); + } + + private SourceChange change(DraftAuthorizationFenceBinding binding) { + return new SourceChange(UUID.randomUUID(), binding.sources(), new byte[] {12}); + } + + private void owner( + Context context, + DraftAuthorizationFenceBinding b, + Owner owner, + Outcome outcome, + byte[] bytes) { + OwnerReadback readback = + new OwnerReadback( + owner, + outcome, + b.operationId(), + b.commitId(), + b.fenceId(), + b.inputDigest(), + b.canonicalBytes(), + bytes); + tx( + context, + () -> { + context.repository().recordOwnerReadback(b, readback); + return null; + }); + } + + private static T tx(Context context, Supplier work) { + return context.transaction().execute(status -> work.get()); + } + + private static void await(CountDownLatch latch) { + try { + if (!latch.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("Ordering fixture timed out"); + } + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException(interrupted); + } + } + + private record Context( + DSLContext dsl, + DraftAuthorizationFenceRepository repository, + TransactionTemplate transaction) {} +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountFirstJoinAuthorityStorageIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountFirstJoinAuthorityStorageIntegrationTest.java index 47724ddc5e..ea5c4af580 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountFirstJoinAuthorityStorageIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountFirstJoinAuthorityStorageIntegrationTest.java @@ -78,7 +78,7 @@ void appendsContiguousPerStreamAndReplaysOnlyExactRequestEvidence() { AccountAuthorityOutboxRepository repository = context.repository(); TransactionTemplate transaction = context.transaction(); String stream = membershipStream(UUID.randomUUID(), UUID.randomUUID()); - String unrelated = "account:auth-authority:v1:tenant/" + UUID.randomUUID(); + String unrelated = membershipStream(UUID.randomUUID(), UUID.randomUUID()); assertThat(inTransaction(transaction, () -> repository.readCheckpoint(stream))).isEmpty(); @@ -336,7 +336,7 @@ void missingHeadWithNoExactHistoryIsEmptyDespiteAnotherStreamsRetainedEvent() { TransactionTemplate transaction = context.transaction(); DSLContext dsl = context.dsl(); String missingStream = membershipStream(UUID.randomUUID(), UUID.randomUUID()); - String retainedStream = "account:auth-authority:v1:tenant/" + UUID.randomUUID(); + String retainedStream = membershipStream(UUID.randomUUID(), UUID.randomUUID()); byte[] retainedPayload = new byte[] {4, 5, 6}; Event retained = diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceBindingTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceBindingTest.java new file mode 100644 index 0000000000..14f50b6fd9 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceBindingTest.java @@ -0,0 +1,446 @@ +package unit.net.firedevops.firemud.accountservice.authordraft; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository.SourceChange; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import org.junit.jupiter.api.Test; + +class DraftAuthorizationFenceBindingTest { + @Test + void originalSourceChangeRoundTripsWithoutNarrowingIndependentCounters() { + SourceEvidence source = + new SourceEvidence( + SourceKind.MEMBERSHIP, + UUID.randomUUID() + "/" + UUID.randomUUID(), + "922337203685477580812345", + "922337203685477581812345", + "membership-stream", + "922337203685477583812345", + "unchanged-original-event".getBytes(StandardCharsets.UTF_8)); + SourceChange original = + new SourceChange(UUID.randomUUID(), List.of(source), new byte[] {1, 2, 3}); + SourceChange recovered = SourceChange.fromStored(original.canonicalBytes()); + assertThat(recovered.canonicalBytes()).containsExactly(original.canonicalBytes()); + assertThat(recovered.sources().getFirst().generation()).isEqualTo(source.generation()); + assertThat(recovered.sources().getFirst().sourceVersion()).isEqualTo(source.sourceVersion()); + assertThat(recovered.sources().getFirst().checkpointSequence()) + .isEqualTo(source.checkpointSequence()); + assertThat(recovered.mutation()).containsExactly(original.mutation()); + } + + @Test + void originalSourceChangeRejectsMalformedFramesAndNoncanonicalRecoveryBytes() { + SourceChange original = new SourceChange(UUID.randomUUID(), List.of(source()), new byte[] {1}); + byte[] stored = original.canonicalBytes(); + assertThatThrownBy( + () -> SourceChange.fromStored(java.util.Arrays.copyOf(stored, stored.length - 1))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> SourceChange.fromStored(java.util.Arrays.copyOf(stored, stored.length + 1))) + .isInstanceOf(IllegalArgumentException.class); + byte[] negativeSize = stored.clone(); + java.nio.ByteBuffer.wrap(negativeSize).putInt(-1); + assertThatThrownBy(() -> SourceChange.fromStored(negativeSize)) + .isInstanceOf(IllegalArgumentException.class); + byte[] impossibleSize = stored.clone(); + java.nio.ByteBuffer.wrap(impossibleSize).putInt(Integer.MAX_VALUE); + assertThatThrownBy(() -> SourceChange.fromStored(impossibleSize)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void copiedSourceListsAndEvidenceCannotRewriteBindingOrSourceChange() { + byte[] evidence = new byte[] {1, 2}; + SourceEvidence source = + new SourceEvidence( + SourceKind.ACCOUNT, UUID.randomUUID().toString(), "1", "2", "stream", "0", evidence); + List incoming = new ArrayList<>(List.of(source)); + DraftAuthorizationFenceBinding original = binding(source, "exact-payload"); + DraftAuthorizationFenceBinding captured = + new DraftAuthorizationFenceBinding( + original.operationId(), + original.requestId(), + original.commitId(), + original.fenceId(), + original.actorAccountId(), + original.tenantId(), + original.versionId(), + original.baseCommitId(), + original.expectedDraftEpoch(), + original.gameDesignBinding(), + original.normalizedInput(), + original.inputDigest(), + incoming); + SourceChange change = new SourceChange(UUID.randomUUID(), incoming, new byte[] {4}); + byte[] capturedBytes = captured.canonicalBytes(); + byte[] changedBytes = change.canonicalBytes(); + incoming.clear(); + evidence[0] = 99; + captured.sources().getFirst().evidence()[0] = 98; + change.sources().getFirst().evidence()[0] = 97; + assertThatThrownBy(() -> captured.sources().clear()) + .isInstanceOf(UnsupportedOperationException.class); + assertThatThrownBy(() -> change.sources().clear()) + .isInstanceOf(UnsupportedOperationException.class); + assertThat(captured.canonicalBytes()).containsExactly(capturedBytes); + assertThat(change.canonicalBytes()).containsExactly(changedBytes); + } + + @Test + void canonicalFramesPreserveIndependentCountersAndDefendExactBytes() { + byte[] evidence = "exact-source-proof".getBytes(StandardCharsets.UTF_8); + SourceEvidence source = + new SourceEvidence( + SourceKind.ACCOUNT, + UUID.randomUUID().toString(), + "9007199254740993", + "9007199254741007", + "account:source", + "17", + evidence); + DraftAuthorizationFenceBinding binding = binding(source, "normalized-input"); + byte[] gameDesign = binding.gameDesignBinding(); + byte[] input = binding.normalizedInput(); + DraftAuthorizationFenceBinding captured = + copy( + binding, + binding.requestId(), + binding.commitId(), + binding.tenantId(), + binding.versionId(), + binding.baseCommitId(), + gameDesign, + input, + binding.inputDigest()); + byte[] original = captured.canonicalBytes(); + evidence[0] = 0; + gameDesign[0] = 0; + input[0] = 0; + captured.normalizedInput()[0] = 0; + captured.gameDesignBinding()[0] = 0; + source.evidence()[0] = 0; + assertThat(captured.canonicalBytes()).containsExactly(original); + assertThat(captured.baseCommitId()).isEqualTo("opaque/base:9007199254740993"); + assertThat( + copy( + binding, + binding.requestId(), + binding.commitId(), + binding.tenantId(), + binding.versionId(), + binding.baseCommitId(), + binding.gameDesignBinding(), + binding.normalizedInput(), + binding.inputDigest()) + .canonicalBytes()) + .containsExactly(binding.canonicalBytes()); + assertThat(new String(original, StandardCharsets.UTF_8)) + .contains("9007199254740993", "9007199254741007", "17", binding.baseCommitId()); + } + + @Test + void nonexistentCounterApplicabilityIsNotManufacturedForGlobalRoleBirth() { + SourceEvidence source = + new SourceEvidence( + SourceKind.GLOBAL_ROLES, + UUID.randomUUID().toString(), + null, + "1", + null, + null, + new byte[] {1}); + assertThat(source.generation()).isNull(); + assertThat(source.checkpointSequence()).isNull(); + assertThat(source.canonicalBytes()).isNotEmpty(); + } + + @Test + void rejectsOversizedMultibyteParticipationKeyWithoutChangingCanonicalScopes() { + String exactLimit = "界".repeat(680) + "x"; + SourceEvidence retained = + new SourceEvidence(SourceKind.ISSUER, exactLimit, "1", "1", "stream", "0", new byte[] {1}); + assertThat(retained.scopeId()).isEqualTo(exactLimit); + assertThat(retained.key().getBytes(StandardCharsets.UTF_8)).hasSize(2048); + assertThatThrownBy( + () -> + new SourceEvidence( + SourceKind.ISSUER, exactLimit + "x", "1", "1", "stream", "0", new byte[] {1})) + .isInstanceOf(IllegalArgumentException.class); + String configuredIssuer = "界".repeat(512); + SourceEvidence exactIssuer = + new SourceEvidence( + SourceKind.ISSUER, configuredIssuer, "1", "1", "stream", "0", new byte[] {1}); + assertThat(exactIssuer.scopeId()).isEqualTo(configuredIssuer); + assertThat(exactIssuer.key()).isEqualTo("ISSUER:" + configuredIssuer); + UUID account = UUID.randomUUID(); + SourceEvidence canonical = + new SourceEvidence( + SourceKind.ACCOUNT, account.toString(), "1", "2", "stream", "0", new byte[] {1}); + assertThat(canonical.scopeId()).isEqualTo(account.toString()); + assertThat(canonical.key()).isEqualTo("ACCOUNT:" + account); + } + + @Test + void rejectsAliasesNoncanonicalCountersAndChangedInputDigest() { + UUID id = UUID.randomUUID(); + assertThatThrownBy( + () -> + new SourceEvidence( + SourceKind.ACCOUNT, + id.toString().toUpperCase(), + "1", + "2", + "stream", + "3", + new byte[] {1})) + .isInstanceOf(IllegalArgumentException.class); + for (String counter : List.of("01", "1e3", "-1", " 1", "1.0")) { + assertThatThrownBy( + () -> + new SourceEvidence( + SourceKind.ACCOUNT, + id.toString(), + counter, + "2", + "stream", + "3", + new byte[] {1})) + .isInstanceOf(IllegalArgumentException.class); + } + SourceEvidence source = + new SourceEvidence( + SourceKind.ACCOUNT, id.toString(), "1", "2", "stream", "3", new byte[] {1}); + DraftAuthorizationFenceBinding binding = binding(source, "payload"); + assertThatThrownBy( + () -> + new DraftAuthorizationFenceBinding( + binding.operationId(), + binding.requestId(), + binding.commitId(), + binding.fenceId(), + binding.actorAccountId(), + binding.tenantId(), + binding.versionId(), + binding.baseCommitId(), + "0", + binding.gameDesignBinding(), + new byte[] {2}, + binding.inputDigest(), + List.of(source))) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void rejectsChangedDuplicatedIdentitiesAndBaseBeforeStorage() { + DraftAuthorizationFenceBinding b = binding(source(), "payload"); + for (int field = 0; field < 5; field++) { + int changedField = field; + assertThatThrownBy( + () -> + copy( + b, + changedField == 0 ? UUID.randomUUID() : b.requestId(), + changedField == 1 ? UUID.randomUUID() : b.commitId(), + changedField == 2 ? UUID.randomUUID() : b.tenantId(), + changedField == 3 ? UUID.randomUUID() : b.versionId(), + changedField == 4 ? "changed/base" : b.baseCommitId(), + b.gameDesignBinding(), + b.normalizedInput(), + b.inputDigest())) + .isInstanceOf(IllegalArgumentException.class); + } + for (String invalidBase : List.of("", " ", "x".repeat(257), "界".repeat(86))) { + assertThatThrownBy( + () -> + copy( + b, + b.requestId(), + b.commitId(), + b.tenantId(), + b.versionId(), + invalidBase, + b.gameDesignBinding(), + b.normalizedInput(), + b.inputDigest())) + .isInstanceOf(IllegalArgumentException.class); + } + } + + @Test + void rejectsMalformedNoncanonicalOrReorderedGameDesignBytesAndAlternateInput() { + DraftAuthorizationFenceBinding b = binding(source(), "payload"); + DraftCommitBinding complete = + DraftCommitBinding.fromStored( + new String(b.gameDesignBinding(), StandardCharsets.UTF_8), b.inputDigest()); + List reordered = new ArrayList<>(complete.revisions()); + java.util.Collections.reverse(reordered); + List invalid = + List.of( + new byte[] {3}, + new byte[] {(byte) 0xff}, + (complete.canonicalJson() + " ").getBytes(StandardCharsets.UTF_8), + complete + .canonicalJson() + .replace("\"revisionOrder\":\"0\"", "\"revisionOrder\":\"1\"") + .getBytes(StandardCharsets.UTF_8)); + for (byte[] bytes : invalid) { + assertThatThrownBy( + () -> + copy( + b, + b.requestId(), + b.commitId(), + b.tenantId(), + b.versionId(), + b.baseCommitId(), + bytes, + bytes, + DraftAuthorizationFenceBinding.digest(bytes))) + .isInstanceOf(IllegalArgumentException.class); + } + assertThatThrownBy( + () -> + DraftCommitBinding.create( + complete.target(), + complete.requestId(), + complete.commitId(), + complete.baseCommitId(), + reordered, + complete.affectedUnits())) + .isInstanceOf(IllegalArgumentException.class); + byte[] alternate = "alternate-input".getBytes(StandardCharsets.UTF_8); + assertThatThrownBy( + () -> + copy( + b, + b.requestId(), + b.commitId(), + b.tenantId(), + b.versionId(), + b.baseCommitId(), + b.gameDesignBinding(), + alternate, + DraftAuthorizationFenceBinding.digest(alternate))) + .isInstanceOf(IllegalArgumentException.class); + DraftCommitBinding changed = + DraftCommitBinding.create( + complete.target(), + complete.requestId(), + complete.commitId(), + complete.baseCommitId(), + List.of( + new RevisionPayload( + "0", + complete.revisions().getFirst().revisionId(), + Owner.WORLD_MANAGEMENT, + "changed-payload"), + complete.revisions().get(1)), + complete.affectedUnits()); + assertThatThrownBy( + () -> + copy( + b, + b.requestId(), + b.commitId(), + b.tenantId(), + b.versionId(), + b.baseCommitId(), + changed.canonicalBytes(), + b.normalizedInput(), + changed.digest())) + .isInstanceOf(IllegalArgumentException.class); + } + + private SourceEvidence source() { + return new SourceEvidence( + SourceKind.ACCOUNT, UUID.randomUUID().toString(), "1", "2", "stream", "0", new byte[] {1}); + } + + private DraftAuthorizationFenceBinding copy( + DraftAuthorizationFenceBinding b, + UUID request, + UUID commit, + UUID tenant, + UUID version, + String base, + byte[] gameDesign, + byte[] input, + String digest) { + return new DraftAuthorizationFenceBinding( + b.operationId(), + request, + commit, + b.fenceId(), + b.actorAccountId(), + tenant, + version, + base, + b.expectedDraftEpoch(), + gameDesign, + input, + digest, + b.sources()); + } + + private DraftAuthorizationFenceBinding binding(SourceEvidence source, String payload) { + DraftCommitBinding complete = + DraftCommitBinding.create( + new TargetProof( + UUID.randomUUID(), + UUID.randomUUID(), + 1, + "tenant-key", + 2, + "tenant-key", + "NEW_GAME_ROW"), + UUID.randomUUID(), + UUID.randomUUID(), + "opaque/base:9007199254740993", + List.of( + new RevisionPayload("0", UUID.randomUUID(), Owner.WORLD_MANAGEMENT, payload), + new RevisionPayload( + "1", UUID.randomUUID(), Owner.GAME_DESIGN_CONTROL_PLANE, "control")), + List.of( + new AffectedUnit( + Owner.WORLD_MANAGEMENT, + "region", + "region-1", + "aggregate", + "region-1", + "9007199254740999"), + new AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + "version", + "version-1", + "aggregate", + "version-1", + "0"))); + return new DraftAuthorizationFenceBinding( + UUID.randomUUID(), + complete.requestId(), + complete.commitId(), + UUID.randomUUID(), + UUID.randomUUID(), + complete.target().canonicalTenantId(), + complete.target().canonicalVersionId(), + complete.baseCommitId(), + "9007199254741009", + complete.canonicalBytes(), + complete.canonicalBytes(), + complete.digest(), + List.of(source)); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountLogoutRequestDigestTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountLogoutRequestDigestTest.java new file mode 100644 index 0000000000..fc0fd83b27 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountLogoutRequestDigestTest.java @@ -0,0 +1,105 @@ +package unit.net.firedevops.firemud.accountservice.dto; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.AccountLogoutRequestDigest; +import org.junit.jupiter.api.Test; + +class AccountLogoutRequestDigestTest { + private static final UUID LOGOUT_ALL_ACCOUNT = + UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID TOKEN_LOGOUT_ACCOUNT = + UUID.fromString("22222222-2222-4222-8222-222222222222"); + + @Test + void accountLogoutAllMatchesFixedRequestDigestV1PreimageAndDigestVector() { + String tokenHash = "a".repeat(64); + + assertThat( + AccountLogoutRequestDigest.accountLogoutAllPreimageHex( + LOGOUT_ALL_ACCOUNT, "control-ui", tokenHash)) + .isEqualTo( + compactHex( + """ + 31363a726571756573744469676573742f763131333a6f7065726174696f6e4b696e64363a737472696e673131383a4143434f554e545f4c4f474f55545f414c4c31363a7375626a6563744163636f756e744964363a737472696e673133363a31313131313131312d313131312d343131312d383131312d31313131313131313131313131323a746f6b656e50726f66696c65363a737472696e673131303a636f6e74726f6c2d756931383a70726573656e746564546f6b656e48617368363a737472696e673136343a61616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161 + """)); + assertThat( + AccountLogoutRequestDigest.accountLogoutAll( + LOGOUT_ALL_ACCOUNT, "control-ui", tokenHash)) + .isEqualTo("78f999be5a5bdb0a5bc4517336ad6899b2383c8058b0bb8f76fe67eb67dea020"); + } + + @Test + void tokenLogoutMatchesFixedRequestDigestV1PreimageAndDigestVector() { + String tokenHash = "b".repeat(64); + + assertThat( + AccountLogoutRequestDigest.tokenLogoutPreimageHex( + TOKEN_LOGOUT_ACCOUNT, "player-bootstrap", tokenHash)) + .isEqualTo( + compactHex( + """ + 31363a726571756573744469676573742f763131333a6f7065726174696f6e4b696e64363a737472696e673131323a544f4b454e5f4c4f474f555431363a7375626a6563744163636f756e744964363a737472696e673133363a32323232323232322d323232322d343232322d383232322d32323232323232323232323231323a746f6b656e50726f66696c65363a737472696e673131363a706c617965722d626f6f747374726170393a746f6b656e48617368363a737472696e673136343a62626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262 + """)); + assertThat( + AccountLogoutRequestDigest.tokenLogout( + TOKEN_LOGOUT_ACCOUNT, "player-bootstrap", tokenHash)) + .isEqualTo("21c085ddf384d4ab3d32c04f37601e710240d11ffe1be64531ee780cf2fcdee0"); + } + + @Test + void eachClosedTupleFieldChangesTheDigest() { + String tokenHash = "a".repeat(64); + String original = + AccountLogoutRequestDigest.accountLogoutAll(LOGOUT_ALL_ACCOUNT, "control-ui", tokenHash); + + assertThat(AccountLogoutRequestDigest.tokenLogout(LOGOUT_ALL_ACCOUNT, "control-ui", tokenHash)) + .isNotEqualTo(original); + assertThat( + AccountLogoutRequestDigest.accountLogoutAll( + TOKEN_LOGOUT_ACCOUNT, "control-ui", tokenHash)) + .isNotEqualTo(original); + assertThat( + AccountLogoutRequestDigest.accountLogoutAll( + LOGOUT_ALL_ACCOUNT, "player-bootstrap", tokenHash)) + .isNotEqualTo(original); + assertThat( + AccountLogoutRequestDigest.accountLogoutAll( + LOGOUT_ALL_ACCOUNT, "control-ui", "b".repeat(64))) + .isNotEqualTo(original); + } + + @Test + void rejectsUnsupportedProfilesNoncanonicalAccountIdentityAndMalformedTokenHashes() { + assertThatThrownBy( + () -> + AccountLogoutRequestDigest.accountLogoutAll( + LOGOUT_ALL_ACCOUNT, "private-player-delegation", "a".repeat(64))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("token profile"); + assertThatThrownBy( + () -> + AccountLogoutRequestDigest.accountLogoutAll( + new UUID(0L, 0L), "control-ui", "a".repeat(64))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("non-nil Account UUID"); + assertThatThrownBy( + () -> + AccountLogoutRequestDigest.tokenLogout( + LOGOUT_ALL_ACCOUNT, "control-ui", "A".repeat(64))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("lowercase SHA-256 hex"); + assertThatThrownBy( + () -> + AccountLogoutRequestDigest.tokenLogout( + LOGOUT_ALL_ACCOUNT, "control-ui", "a".repeat(63))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("lowercase SHA-256 hex"); + } + + private static String compactHex(String hex) { + return hex.replaceAll("\\s+", ""); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountSecurityStateMutationRequestTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountSecurityStateMutationRequestTest.java new file mode 100644 index 0000000000..d1085cf5b3 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountSecurityStateMutationRequestTest.java @@ -0,0 +1,182 @@ +package unit.net.firedevops.firemud.accountservice.dto; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.AccountSecurityStateMutationRequest; +import net.firedevops.firemud.accountservice.dto.AccountSecurityStateRequestDigest; +import net.firedevops.firemud.common.account.authority.AccountSecurityStateAuthorityEventV1Codec.AccountState; +import org.junit.jupiter.api.Test; + +class AccountSecurityStateMutationRequestTest { + private static final UUID REQUEST = UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID ACCOUNT = UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final List KINDS = List.of("EMAIL_LOGIN_ELIGIBILITY_CHANGED"); + + @Test + void exactRequestFramesRetainCallerAndStateBytesAndFixedDigest() { + var request = + request( + REQUEST, ACCOUNT, caller(ACCOUNT, REQUEST, "a".repeat(64)), 1L, 1L, KINDS, state(true)); + ByteBuffer bytes = ByteBuffer.wrap(AccountSecurityStateRequestDigest.requestBytes(request)); + assertThat(readFrame(bytes)).isEqualTo("firemud/account/security-state/request/v1"); + assertThat(readFrame(bytes)).isEqualTo(REQUEST.toString()); + assertThat(readFrame(bytes)).isEqualTo(ACCOUNT.toString()); + assertThat(readFrame(bytes)) + .isEqualTo(new String(request.callerProofBinding(), StandardCharsets.UTF_8)); + assertThat(readFrame(bytes)).isEqualTo("1"); + assertThat(readFrame(bytes)).isEqualTo("1"); + assertThat(readFrame(bytes)).isEqualTo("1"); + assertThat(readFrame(bytes)).isEqualTo("EMAIL_LOGIN_ELIGIBILITY_CHANGED"); + assertThat(readFrame(bytes)) + .isEqualTo( + "{\"emailVerified\":true,\"globalRoles\":[],\"lifecycleState\":\"ACTIVE\",\"loginAuthModes\":[\"EMAIL_OTP\",\"PASSWORD\"]}"); + assertThat(bytes.hasRemaining()).isFalse(); + assertThat(AccountSecurityStateRequestDigest.digest(request)) + .isEqualTo("604a354594c3a0b5f882224d44ad40bc8a5ce67c2afa704e6f470f79d0e8ee30"); + } + + @Test + void everyOriginalSemanticBindingChangesDigestIncludingCallerTargetStateAndKinds() { + var original = + request( + REQUEST, ACCOUNT, caller(ACCOUNT, REQUEST, "a".repeat(64)), 1L, 1L, KINDS, state(true)); + UUID other = UUID.fromString("33333333-3333-4333-8333-333333333333"); + for (var changed : + List.of( + request(other, ACCOUNT, original.callerProofBinding(), 1L, 1L, KINDS, state(true)), + request(REQUEST, other, original.callerProofBinding(), 1L, 1L, KINDS, state(true)), + request( + REQUEST, + ACCOUNT, + caller(other, REQUEST, "a".repeat(64)), + 1L, + 1L, + KINDS, + state(true)), + request( + REQUEST, + ACCOUNT, + caller(ACCOUNT, other, "a".repeat(64)), + 1L, + 1L, + KINDS, + state(true)), + request( + REQUEST, + ACCOUNT, + caller(ACCOUNT, REQUEST, "b".repeat(64)), + 1L, + 1L, + KINDS, + state(true)), + request(REQUEST, ACCOUNT, original.callerProofBinding(), 2L, 1L, KINDS, state(true)), + request(REQUEST, ACCOUNT, original.callerProofBinding(), 1L, 2L, KINDS, state(true)), + request(REQUEST, ACCOUNT, original.callerProofBinding(), 1L, 1L, KINDS, state(false)), + request( + REQUEST, + ACCOUNT, + original.callerProofBinding(), + 1L, + 1L, + List.of("LOGIN_AUTH_MODES_CHANGED"), + state(true)))) { + assertThat(AccountSecurityStateRequestDigest.digest(changed)) + .isNotEqualTo(AccountSecurityStateRequestDigest.digest(original)); + } + } + + @Test + void closedCorrelationRejectsAssertionsCredentialsNullsAndUnknownFields() { + byte[] original = caller(ACCOUNT, REQUEST, "a".repeat(64)); + for (String extra : List.of("password", "token", "otp", "authenticated", "globalRoles")) { + String value = new String(original, StandardCharsets.UTF_8); + byte[] changed = + (value.substring(0, value.length() - 1) + ",\"" + extra + "\":\"asserted\"}") + .getBytes(StandardCharsets.UTF_8); + assertThatThrownBy(() -> request(REQUEST, ACCOUNT, changed, 1L, 1L, KINDS, state(true))) + .isInstanceOf(IllegalArgumentException.class); + } + assertThatThrownBy( + () -> + request( + REQUEST, + ACCOUNT, + "{}".getBytes(StandardCharsets.UTF_8), + 1L, + 1L, + KINDS, + state(true))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> request(REQUEST, ACCOUNT, original, 0L, 1L, KINDS, state(true))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + request(REQUEST, ACCOUNT, original, 1L, 1L, List.of("PASSWORD_RESET"), state(true))) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void requestCopiesInputsAndStateHasOnlySharedCodecPolicyVocabulary() { + byte[] bytes = caller(ACCOUNT, REQUEST, "a".repeat(64)); + var request = request(REQUEST, ACCOUNT, bytes, 1L, 1L, KINDS, state(true)); + byte[] retained = request.callerProofBinding(); + bytes[0] = 0; + retained[0] = 0; + assertThat(request.callerProofBinding()[0]).isEqualTo((byte) '{'); + assertThatThrownBy(() -> request.mutationKinds().clear()) + .isInstanceOf(UnsupportedOperationException.class); + assertThatThrownBy( + () -> + request( + REQUEST, + ACCOUNT, + request.callerProofBinding(), + 1L, + 1L, + KINDS, + new AccountState(true, List.of("PASSWORD"), List.of("admin"), "ACTIVE"))) + .isInstanceOf(IllegalArgumentException.class); + assertThat( + AccountSecurityStateMutationRequest.parseCanonicalState( + request.canonicalDesiredState())) + .isEqualTo(request.desiredState()); + } + + private static AccountSecurityStateMutationRequest request( + UUID request, + UUID account, + byte[] caller, + long generation, + long version, + List kinds, + AccountState state) { + return new AccountSecurityStateMutationRequest( + request, account, caller, generation, version, kinds, state); + } + + private static AccountState state(boolean verified) { + return new AccountState(verified, List.of("EMAIL_OTP", "PASSWORD"), List.of(), "ACTIVE"); + } + + private static byte[] caller(UUID actor, UUID operation, String digest) { + return ("{\"actorAccountUuid\":\"" + + actor + + "\",\"ownerEvidenceDigest\":\"sha256:" + + digest + + "\",\"ownerOperationId\":\"" + + operation + + "\",\"schemaVersion\":\"account-security-state-caller-correlation/v1\"}") + .getBytes(StandardCharsets.UTF_8); + } + + private static String readFrame(ByteBuffer bytes) { + byte[] field = new byte[bytes.getInt()]; + bytes.get(field); + return new String(field, StandardCharsets.UTF_8); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidenceRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidenceRepositoryTest.java index 320abd7d6a..02aa886a44 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidenceRepositoryTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidenceRepositoryTest.java @@ -26,6 +26,268 @@ import org.springframework.transaction.annotation.Transactional; class AccountAuthoritySourceEvidenceRepositoryTest { + @Test + void closedPreparationRequiresWritableOwnerTransactionAndExactAccountScope() { + var issuer = + new AccountAuthoritySourceEvidenceRepository.CurrentSourceEvidence( + AuthorityScope.issuer(ISSUER_ID), + 1L, + 1L, + null, + zeroCheckpoint("issuer/" + ISSUER_ID), + Optional.empty(), + "ISSUER_SCOPE_INSERT", + null, + null, + 7L, + null); + assertThatThrownBy(() -> repository.prepareClosedAccountAdvance(ACCOUNT_ID, issuer)) + .isInstanceOf( + AccountAuthoritySourceEvidenceRepository.SourceEvidenceUnavailableException.class); + org.springframework.transaction.support.TransactionSynchronizationManager + .setActualTransactionActive(true); + try { + assertThatThrownBy(() -> repository.prepareClosedAccountAdvance(ACCOUNT_ID, issuer)) + .isInstanceOf( + AccountAuthoritySourceEvidenceRepository.SourceEvidenceUnavailableException.class); + assertThatThrownBy(() -> repository.prepareClosedAccountAdvance(new UUID(0L, 0L), null)) + .isInstanceOf( + AccountAuthoritySourceEvidenceRepository.SourceEvidenceUnavailableException.class); + org.springframework.transaction.support.TransactionSynchronizationManager + .setCurrentTransactionReadOnly(true); + assertThatThrownBy( + () -> repository.prepareClosedAccountAdvance(ACCOUNT_ID, accountBaseline())) + .isInstanceOf( + AccountAuthoritySourceEvidenceRepository.SourceEvidenceUnavailableException.class); + verifyNoInteractions(dsl); + } finally { + org.springframework.transaction.support.TransactionSynchronizationManager.clear(); + } + } + + @Test + void closedPreparationCannotAdvanceFromCallerBaselineWhenOwnedSourceIsMissing() { + DSLContext ownerDsl = mock(DSLContext.class); + org.mockito.Mockito.doAnswer( + invocation -> { + String sql = invocation.getArgument(0); + if (sql.contains("FROM account_authority_generations")) + return record("generation", 1L, "source_version", 1L); + if (sql.contains("FROM account_authority_issuance_fences")) + return record("issuance_fence", 1L, "source_version", 1L); + return null; + }) + .when(ownerDsl) + .fetchOne( + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.any(Object[].class)); + var sourceOwner = + new AccountAuthoritySourceEvidenceRepository( + ownerDsl, + new AccountAuthorityGenerationRepository(ownerDsl), + new AccountAuthorityOutboxRepository(ownerDsl)); + org.springframework.transaction.support.TransactionSynchronizationManager + .setActualTransactionActive(true); + try { + assertThatThrownBy( + () -> sourceOwner.prepareClosedAccountAdvance(ACCOUNT_ID, accountBaseline())) + .isInstanceOf( + AccountAuthoritySourceEvidenceRepository.SourceEvidenceUnavailableException.class); + org.mockito.Mockito.verify(ownerDsl, org.mockito.Mockito.never()) + .fetchOne( + org.mockito.ArgumentMatchers.startsWith("UPDATE"), + org.mockito.ArgumentMatchers.any(Object[].class)); + } finally { + org.springframework.transaction.support.TransactionSynchronizationManager.clear(); + } + } + + private static AccountAuthoritySourceEvidenceRepository.CurrentSourceEvidence accountBaseline() { + return new AccountAuthoritySourceEvidenceRepository.CurrentSourceEvidence( + AuthorityScope.account(ACCOUNT_ID), + 1L, + 1L, + new IssuanceFence(ACCOUNT_ID, 1L, 1L), + zeroCheckpoint("account/" + ACCOUNT_ID), + Optional.empty(), + "ACCOUNT_REPOSITORY_INSERT", + 9L, + "ACCOUNT_REPOSITORY_INSERT", + 7L, + 7L); + } + + @Test + void closedReceiptStorageAndSourceConstructorsDoNotRecursivelyMintOrReadEvidence() { + DSLContext ownerDsl = mock(DSLContext.class); + new net.firedevops.firemud.accountservice.repository.AccountSecurityStateOperationRepository( + ownerDsl); + new AccountAuthoritySourceEvidenceRepository( + ownerDsl, + new AccountAuthorityGenerationRepository(ownerDsl), + new AccountAuthorityOutboxRepository(ownerDsl)); + verifyNoInteractions(ownerDsl); + } + + @Test + void canonicalIssuerReadRequiresActualWritableOwnerTransactionBeforeAccess() { + assertThatThrownBy(() -> repository.readCurrentCanonicalIssuerSource(ISSUER_ID)) + .isInstanceOf( + AccountAuthoritySourceEvidenceRepository.SourceEvidenceUnavailableException.class); + verifyNoInteractions(dsl); + org.springframework.transaction.support.TransactionSynchronizationManager + .setActualTransactionActive(true); + org.springframework.transaction.support.TransactionSynchronizationManager + .setCurrentTransactionReadOnly(true); + try { + assertThatThrownBy(() -> repository.readCurrentCanonicalIssuerSource(ISSUER_ID)) + .isInstanceOf( + AccountAuthoritySourceEvidenceRepository.SourceEvidenceUnavailableException.class); + verifyNoInteractions(dsl); + } finally { + org.springframework.transaction.support.TransactionSynchronizationManager.clear(); + } + } + + @Test + void closedAppendActuallyReadsImmutableReceiptAndDeniesMissingOwnerEvidence() { + DSLContext ownerDsl = mock(DSLContext.class); + var ownerOutbox = mock(AccountAuthorityOutboxRepository.class); + var source = + record( + "scope_kind", + "ACCOUNT", + "account_uuid", + ACCOUNT_ID, + "baseline_generation", + 1L, + "baseline_source_version", + 1L, + "baseline_issuance_fence", + 1L, + "initialization_provenance", + "ACCOUNT_REPOSITORY_INSERT", + "account_source_numeric_id", + 9L, + "account_uuid_provenance", + "ACCOUNT_REPOSITORY_INSERT", + "initialization_transaction_id", + 7L, + "account_repository_insert_transaction_id", + 7L, + "current_generation", + 1L, + "current_source_version", + 1L, + "current_issuance_fence", + 1L, + "current_issuance_fence_source_version", + 1L, + "last_outbox_sequence", + 0L); + var account = + record( + "id", + 9L, + "account_uuid", + ACCOUNT_ID, + "account_uuid_source_numeric_id", + 9L, + "account_uuid_provenance", + "ACCOUNT_REPOSITORY_INSERT", + "account_repository_insert_transaction_id", + 7L, + "password_hash", + "retained-verifier"); + org.mockito.Mockito.doAnswer( + invocation -> { + String sql = invocation.getArgument(0); + if (sql.contains("FROM account_authority_source_records")) return source; + if (sql.contains("FROM account_authority_outbox_streams")) + return record("last_sequence", 1L); + if (sql.contains("count(*)")) return record("event_count", 1L); + if (sql.contains("FROM accounts")) return account; + return null; + }) + .when(ownerDsl) + .fetchOne( + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.any(Object[].class)); + String stream = "account:auth-authority:v1:account/" + ACCOUNT_ID; + String request = "account-password-reset-request-v1:" + "a".repeat(64); + var wire = + net.firedevops.firemud.common.account.authority.PasswordResetAuthorityEventV1Codec.seal( + Map.ofEntries( + Map.entry( + "schemaVersion", + net.firedevops.firemud.common.account.authority + .PasswordResetAuthorityEventV1Codec.SCHEMA_VERSION), + Map.entry( + "eventType", + net.firedevops.firemud.common.account.authority + .PasswordResetAuthorityEventV1Codec.EVENT_TYPE), + Map.entry("eventId", "account-password-reset-event-v1:" + "a".repeat(64)), + Map.entry("requestId", request), + Map.entry("accountId", ACCOUNT_ID.toString()), + Map.entry("sourceScope", "account/" + ACCOUNT_ID), + Map.entry("outboxStreamKey", stream), + Map.entry("outboxSequence", "1"), + Map.entry("accountAuthorityGeneration", "2"), + Map.entry("sourceVersion", "2"), + Map.entry( + "accountSecurityCutoff", + Map.of( + "accountAuthorityGeneration", + "2", + "outboxStreamKey", + stream, + "outboxSequence", + "1")))); + var pending = + new AccountAuthorityOutboxRepository.Event( + stream, request, 1L, wire.eventId(), wire.eventDigest(), wire.canonicalJsonUtf8()); + org.mockito.Mockito.doReturn(Optional.of(pending)).when(ownerOutbox).findEvent(stream, 1L); + org.mockito.Mockito.doReturn(Optional.of(pending)).when(ownerOutbox).findEvent(stream, request); + org.mockito.Mockito.doReturn( + Optional.of( + new AccountAuthorityOutboxRepository.Checkpoint( + stream, 1L, pending.eventId(), pending.eventDigest()))) + .when(ownerOutbox) + .readCheckpoint(stream); + var sourceOwner = + new AccountAuthoritySourceEvidenceRepository( + ownerDsl, new AccountAuthorityGenerationRepository(ownerDsl), ownerOutbox); + var expected = + new AccountAuthorityGenerationRepository.ScopeState( + AuthorityScope.account(ACCOUNT_ID), 1L, 1L, new IssuanceFence(ACCOUNT_ID, 1L, 1L)); + var advanced = + new AccountAuthorityGenerationRepository.ScopeState( + AuthorityScope.account(ACCOUNT_ID), 2L, 2L, new IssuanceFence(ACCOUNT_ID, 2L, 2L)); + org.springframework.transaction.support.TransactionSynchronizationManager + .setActualTransactionActive(true); + try { + assertThatThrownBy( + () -> sourceOwner.advanceClosedAccountHead(ACCOUNT_ID, expected, advanced, pending)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("no immutable operation receipt"); + org.mockito.Mockito.verify(ownerDsl) + .fetchOne( + org.mockito.ArgumentMatchers.contains( + "FROM account_password_reset_operation_receipts"), + org.mockito.ArgumentMatchers.any(Object[].class)); + org.mockito.Mockito.verify(ownerDsl, org.mockito.Mockito.never()) + .fetchOne( + org.mockito.ArgumentMatchers.startsWith("UPDATE"), + org.mockito.ArgumentMatchers.any(Object[].class)); + org.mockito.Mockito.verify(ownerDsl, org.mockito.Mockito.never()) + .execute( + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.any(Object[].class)); + } finally { + org.springframework.transaction.support.TransactionSynchronizationManager.clear(); + } + } + private static final UUID ACCOUNT_ID = UUID.fromString("11111111-1111-4111-8111-111111111111"); private static final String ISSUER_ID = "firemud-account-service"; private static final String ISSUER_STREAM_KEY = "account:auth-authority:v1:issuer/" + ISSUER_ID; @@ -117,7 +379,34 @@ void accountSnapshotRequiresSameAccountFenceAndExactScopeKinds() { assertThat( new AccountAuthoritySourceEvidenceRepository.IssuerAccountSourceSnapshot( issuer, account, fence)) - .satisfies(snapshot -> assertThat(snapshot.account().issuanceFence()).isEqualTo(fence)); + .satisfies( + snapshot -> { + assertThat(snapshot.account().issuanceFence()).isEqualTo(fence); + assertThat(snapshot.canonicalAccountProjection().accountId()) + .isEqualTo(ACCOUNT_ID.toString()); + assertThat(snapshot.canonicalAccountProjection().outboxSequence()).isEqualTo("0"); + assertThat(snapshot.canonicalAccountProjection().sourceEvent()).isEmpty(); + assertThat(snapshot.canonicalIssuerProjection().issuerId()) + .isEqualTo("firemud-account-service"); + assertThat(snapshot.canonicalIssuerProjection().lastAppliedSourceOutboxSequence()) + .isEqualTo("0"); + assertThat(snapshot.canonicalIssuerProjection().sourceEvent()).isEmpty(); + }); + UUID otherAccount = UUID.randomUUID(); + var mismatchedProjection = + new net.firedevops.firemud.accountservice.service.AccountGenerationProjection( + otherAccount.toString(), + "1", + "1", + "account:auth-authority:v1:account/" + otherAccount, + "0", + Optional.empty()); + assertThatThrownBy( + () -> + new AccountAuthoritySourceEvidenceRepository.IssuerAccountSourceSnapshot( + issuer, account, fence, mismatchedProjection)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Canonical Account source projection differs from its snapshot"); assertThatThrownBy( () -> new AccountAuthoritySourceEvidenceRepository.IssuerAccountSourceSnapshot( diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepositoryTest.java new file mode 100644 index 0000000000..d3425b1e45 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepositoryTest.java @@ -0,0 +1,132 @@ +package net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; + +import java.time.LocalDateTime; +import java.util.UUID; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.IssuanceFence; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeState; +import org.jooq.DSLContext; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; + +class AccountPasswordResetOperationRepositoryTest { + private static final UUID ACCOUNT_UUID = UUID.fromString("c6ca3e35-9ba4-46a4-967b-f83ddb0d693e"); + private final DSLContext dsl = mock(DSLContext.class); + private final AccountPasswordResetOperationRepository repository = + new AccountPasswordResetOperationRepository(dsl); + + @Test + void lookupsAndInsertionRequireAnOwnerTransaction() throws ReflectiveOperationException { + assertMandatory( + AccountPasswordResetOperationRepository.class.getMethod("findByTokenHash", String.class)); + assertMandatory( + AccountPasswordResetOperationRepository.class.getMethod("findByRequestId", String.class)); + assertMandatory( + AccountPasswordResetOperationRepository.class.getMethod( + "insert", AccountPasswordResetOperationRepository.PasswordResetReceipt.class)); + + assertThatThrownBy(() -> repository.findByTokenHash("0".repeat(64))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("active Account transaction"); + verifyNoInteractions(dsl); + } + + @Test + void receiptEvidenceRejectsMalformedOrNonAccountBindingsBeforeStorageAccess() { + assertThatThrownBy(() -> receipt("not-a-hash", "0".repeat(64), "0".repeat(64))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> receipt("0".repeat(64), "bad-digest", "0".repeat(64))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> receipt("0".repeat(64), "0".repeat(64), "bad-verifier")) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new AccountPasswordResetOperationRepository.PasswordResetReceipt( + 9L, + ACCOUNT_UUID, + "0".repeat(64), + "PASSWORD_RESET", + "wrong-request-id", + 1, + "1".repeat(64), + LocalDateTime.of(2030, 1, 2, 3, 4, 5, 123456789), + "2".repeat(64), + streamKey(), + 1L, + "account-password-reset-event-v1:" + "0".repeat(64), + "sha256:" + "3".repeat(64), + 2L, + 2L, + 3L, + 3L)) + .isInstanceOf(IllegalArgumentException.class); + + verifyNoInteractions(dsl); + } + + @Test + void committedReceiptRetainsExactLocalDeadlineAndAccountFenceEvidence() { + ScopeState authority = + new ScopeState( + AuthorityScope.account(ACCOUNT_UUID), 2L, 2L, new IssuanceFence(ACCOUNT_UUID, 4L, 3L)); + LocalDateTime localDeadline = LocalDateTime.of(2030, 1, 2, 3, 4, 5, 123456789); + var receipt = + AccountPasswordResetOperationRepository.PasswordResetReceipt.committed( + 9L, + ACCOUNT_UUID, + "0".repeat(64), + "account-password-reset-request-v1:" + "0".repeat(64), + "1".repeat(64), + localDeadline, + "2".repeat(64), + streamKey(), + 7L, + "account-password-reset-event-v1:" + "0".repeat(64), + "sha256:" + "3".repeat(64), + authority, + authority.issuanceFence()); + + assertThat(receipt.tokenExpiresAt()).isEqualTo(localDeadline); + assertThat(receipt.issuanceFenceEvidence()).isEqualTo(new IssuanceFence(ACCOUNT_UUID, 4L, 3L)); + assertThat(receipt.outboxSequence()).isEqualTo(7L); + verifyNoInteractions(dsl); + } + + private static AccountPasswordResetOperationRepository.PasswordResetReceipt receipt( + String tokenHash, String requestDigest, String verifierDigest) { + return new AccountPasswordResetOperationRepository.PasswordResetReceipt( + 9L, + ACCOUNT_UUID, + tokenHash, + "PASSWORD_RESET", + "account-password-reset-request-v1:" + tokenHash, + 1, + requestDigest, + LocalDateTime.of(2030, 1, 2, 3, 4, 5), + verifierDigest, + streamKey(), + 1L, + "account-password-reset-event-v1:" + tokenHash, + "sha256:" + "3".repeat(64), + 2L, + 2L, + 3L, + 3L); + } + + private static String streamKey() { + return "account:auth-authority:v1:account/" + ACCOUNT_UUID; + } + + private void assertMandatory(java.lang.reflect.Method method) { + Transactional annotation = method.getAnnotation(Transactional.class); + assertThat(annotation).isNotNull(); + assertThat(annotation.propagation()).isEqualTo(Propagation.MANDATORY); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountRepositoryTest.java index ce2752573c..66d7200246 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountRepositoryTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountRepositoryTest.java @@ -1,5 +1,6 @@ package unit.net.firedevops.firemud.accountservice.repository; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verifyNoInteractions; @@ -11,6 +12,49 @@ import org.junit.jupiter.api.Test; class AccountRepositoryTest { + @Test + void lockedOwnerReadRejectsUnpersistedIdsBeforeAnySql() { + DSLContext dsl = mock(DSLContext.class); + AccountAuthoritySourceEvidenceRepository source = + mock(AccountAuthoritySourceEvidenceRepository.class); + AccountRepository repository = new AccountRepository(dsl, source); + for (Long id : new Long[] {null, 0L, -1L}) { + assertThatThrownBy(() -> repository.findByIdForUpdate(id)) + .isInstanceOf(IllegalArgumentException.class); + } + verifyNoInteractions(dsl, source); + } + + @Test + void lockedOwnerReadSelectsTheActualRowForUpdateWithoutSourceMutation() throws Exception { + java.util.List observed = new java.util.ArrayList<>(); + var connection = + new org.jooq.tools.jdbc.MockConnection( + context -> { + observed.add(context.sql()); + return new org.jooq.tools.jdbc.MockResult[] { + new org.jooq.tools.jdbc.MockResult( + 0, + org.jooq + .impl + .DSL + .using(org.jooq.SQLDialect.POSTGRES) + .newResult(net.firedevops.firemud.accountservice.jooq.Tables.ACCOUNTS.ID)) + }; + }); + AccountAuthoritySourceEvidenceRepository source = + mock(AccountAuthoritySourceEvidenceRepository.class); + try (connection) { + AccountRepository repository = + new AccountRepository( + org.jooq.impl.DSL.using(connection, org.jooq.SQLDialect.POSTGRES), source); + assertThat(repository.findByIdForUpdate(42L)).isEmpty(); + } + assertThat(observed).hasSize(1); + assertThat(observed.getFirst()).contains("accounts", "for update"); + verifyNoInteractions(source); + } + @Test void hardDeletionFailsClosedWithoutSqlOrSourceEvidenceMutation() { DSLContext dsl = mock(DSLContext.class); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountSecurityStateOperationRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountSecurityStateOperationRepositoryTest.java new file mode 100644 index 0000000000..38bb559393 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountSecurityStateOperationRepositoryTest.java @@ -0,0 +1,48 @@ +package unit.net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; + +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.accountservice.repository.AccountSecurityStateOperationRepository; +import net.firedevops.firemud.common.account.authority.AccountSecurityStateAuthorityEventV1Codec.AccountState; +import org.jooq.DSLContext; +import org.junit.jupiter.api.Test; + +class AccountSecurityStateOperationRepositoryTest { + @Test + void storageDeniesOutsideWritableOwnerTransactionBeforeDataAccess() { + DSLContext dsl = mock(DSLContext.class); + var repository = new AccountSecurityStateOperationRepository(dsl); + assertThatThrownBy(() -> repository.findByRequestId(UUID.randomUUID())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Writable Account owner transaction"); + verifyNoInteractions(dsl); + assertThat( + repository + .getClass() + .isAnnotationPresent(org.springframework.stereotype.Repository.class)) + .isTrue(); + assertThat( + repository.getClass().isAnnotationPresent(org.springframework.stereotype.Service.class)) + .isFalse(); + } + + @Test + void detectorExactlyCoversIndependentCredentialFreeChangedFamilies() { + var before = new AccountState(false, List.of("PASSWORD"), List.of(), "ACTIVE"); + var after = + new AccountState( + true, List.of("EMAIL_OTP", "PASSWORD"), List.of("support"), "SECURITY_LOCKED"); + assertThat(AccountSecurityStateOperationRepository.detectedKinds(before, after)) + .containsExactly( + "EMAIL_LOGIN_ELIGIBILITY_CHANGED", + "GLOBAL_ROLE_CHANGED", + "LIFECYCLE_STATE_CHANGED", + "LOGIN_AUTH_MODES_CHANGED"); + assertThat(AccountSecurityStateOperationRepository.detectedKinds(before, before)).isEmpty(); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepositoryTest.java new file mode 100644 index 0000000000..bd2a21e841 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepositoryTest.java @@ -0,0 +1,147 @@ +package unit.net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.UUID; +import java.util.function.LongFunction; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementEventV1Codec; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementRequest; +import net.firedevops.firemud.accountservice.dto.TenantAuthorityEventV1Codec; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeState; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantAuthorityEventRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantEntitlementOutboxRepository; +import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class AccountTenantAuthorityEventRepositoryTest { + private static final String NAMESPACE = "prod"; + private static final UUID TENANT_ID = UUID.fromString("44444444-4444-4444-8444-444444444444"); + private static final UUID REQUEST_ID = UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID SOURCE_REQUEST_ID = + UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final UUID SOURCE_OPERATION_ID = + UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final String SOURCE_REQUEST_DIGEST = "sha256:" + "a".repeat(64); + + @Test + void appendBindsBillingEventIdAsUuidAndAuthorityEventIdAsVarcharText() { + DSLContext dsl = mock(DSLContext.class); + AccountAuthorityOutboxRepository authorityOutbox = mock(AccountAuthorityOutboxRepository.class); + AccountTenantEntitlementOutboxRepository billingOutbox = + mock(AccountTenantEntitlementOutboxRepository.class); + FreshTenantIdentityAssociationRepository tenantIdentity = + mock(FreshTenantIdentityAssociationRepository.class); + AccountAuthorityGenerationRepository generations = + mock(AccountAuthorityGenerationRepository.class); + Record sourceHead = mock(Record.class); + when(sourceHead.get("current_generation", Long.class)).thenReturn(1L); + when(sourceHead.get("current_source_version", Long.class)).thenReturn(1L); + when(sourceHead.get("last_outbox_sequence", Long.class)).thenReturn(0L); + when(dsl.fetchOne(anyString(), any(Object[].class))).thenReturn(sourceHead); + when(dsl.execute(anyString(), any(Object[].class))).thenReturn(1); + + FreshTenantCreationEvidence source = freshTenantEvidence(); + DemoTenantEntitlementRequest request = + new DemoTenantEntitlementRequest( + REQUEST_ID, + TENANT_ID, + SOURCE_REQUEST_ID, + SOURCE_REQUEST_DIGEST, + null, + null, + null, + true, + false, + false, + true, + new DemoTenantEntitlementRequest.Quotas(3L, 2L, 4096L)); + DemoTenantEntitlementEventV1Codec.Event billingEvent = + DemoTenantEntitlementEventV1Codec.seal(request, source, 1L, 2L, 2L, 1L); + ScopeState nextAuthority = new ScopeState(AuthorityScope.tenant(TENANT_ID), 2L, 2L, null); + String streamKey = TenantAuthorityEventV1Codec.streamKey(TENANT_ID); + + doAnswer( + invocation -> { + LongFunction evidenceFactory = + invocation.getArgument(2); + AccountAuthorityOutboxRepository.EventEvidence evidence = evidenceFactory.apply(1L); + return new AccountAuthorityOutboxRepository.Event( + streamKey, + REQUEST_ID.toString(), + 1L, + evidence.eventId(), + evidence.eventDigest(), + evidence.payload()); + }) + .when(authorityOutbox) + .append(eq(streamKey), eq(REQUEST_ID.toString()), any()); + + AccountTenantAuthorityEventRepository repository = + new AccountTenantAuthorityEventRepository( + dsl, authorityOutbox, billingOutbox, tenantIdentity, generations); + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + TenantAuthorityEventV1Codec.Event appended = + repository.append(request, source, nextAuthority, billingEvent); + + assertThat(appended.tenantBillingEventId()).isEqualTo(billingEvent.eventId()); + assertThat(TenantAuthorityEventV1Codec.verify(appended.payload()).tenantBillingEventId()) + .isEqualTo(billingEvent.eventId()); + + ArgumentCaptor updateSql = ArgumentCaptor.forClass(String.class); + ArgumentCaptor updateBindings = ArgumentCaptor.forClass(Object[].class); + verify(dsl).execute(updateSql.capture(), updateBindings.capture()); + assertThat(updateSql.getValue()) + .contains("tenant_billing_sequence = ?, tenant_billing_event_id = ?"); + Object[] bindings = updateBindings.getValue(); + assertThat(bindings).hasSize(14); + assertThat(bindings[5]) + .isExactlyInstanceOf(String.class) + .isEqualTo(appended.eventId().toString()); + assertThat(bindings[8]).isExactlyInstanceOf(UUID.class).isEqualTo(billingEvent.eventId()); + } finally { + TransactionSynchronizationManager.clear(); + } + } + + private static FreshTenantCreationEvidence freshTenantEvidence() { + String sourceTenantKey = "tenant-source-44444444"; + String evidenceDigest = + GameTenantCreationDigest.evidenceDigest( + NAMESPACE, + SOURCE_REQUEST_ID, + SOURCE_OPERATION_ID, + SOURCE_REQUEST_DIGEST, + TENANT_ID, + 7001L, + sourceTenantKey, + "NEW_GAME_ROW"); + return new FreshTenantCreationEvidence( + 1, + NAMESPACE, + SOURCE_REQUEST_ID, + SOURCE_OPERATION_ID, + SOURCE_REQUEST_DIGEST, + TENANT_ID, + 7001L, + sourceTenantKey, + "NEW_GAME_ROW", + evidenceDigest); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountJwtReadinessTlsInterceptorTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountJwtReadinessTlsInterceptorTest.java index 3919c2f5ef..8b2627ec38 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountJwtReadinessTlsInterceptorTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountJwtReadinessTlsInterceptorTest.java @@ -51,8 +51,7 @@ void exactHarnessUriAndConfiguredSpkiPinEstablishOnlyAnInternalCallerContext() t ServerCallHandler next = mock(ServerCallHandler.class); SSLSession session = mock(SSLSession.class); java.security.cert.Certificate peer = cert(URI); - when(session.getPeerCertificates()) - .thenReturn(new java.security.cert.Certificate[] {peer}); + when(session.getPeerCertificates()).thenReturn(new java.security.cert.Certificate[] {peer}); when(call.getAttributes()) .thenReturn(Attributes.newBuilder().set(Grpc.TRANSPORT_ATTR_SSL_SESSION, session).build()); AtomicReference captured = diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadbackTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadbackTest.java new file mode 100644 index 0000000000..f03aa6bcd4 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadbackTest.java @@ -0,0 +1,775 @@ +package unit.net.firedevops.firemud.accountservice.service; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.LocalDateTime; +import java.util.HexFormat; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.AccountLogoutRequestDigest; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Checkpoint; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Event; +import net.firedevops.firemud.accountservice.repository.AccountLogoutAllOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountLogoutAllOperationRepository.LogoutAllReceipt; +import net.firedevops.firemud.accountservice.repository.AccountPasswordResetOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountPasswordResetOperationRepository.PasswordResetReceipt; +import net.firedevops.firemud.accountservice.service.AccountAuthoritySourceEventReadback; +import net.firedevops.firemud.accountservice.service.AccountAuthoritySourceReader.AccountSourceEventReadback; +import net.firedevops.firemud.accountservice.service.AccountAuthoritySourceReader.AccountSourceSnapshot; +import net.firedevops.firemud.common.account.authority.AccountAuthoritySourceEventV1Codec; +import net.firedevops.firemud.common.account.authority.AccountAuthoritySourceEventV1Codec.AccountPreimage; +import net.firedevops.firemud.common.account.authority.AccountAuthoritySourceEventV1Codec.AccountState; +import net.firedevops.firemud.common.account.authority.AccountLogoutAllAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.AccountSecurityStateAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.PasswordResetAuthorityEventV1Codec; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class AccountAuthoritySourceEventReadbackTest { + private static final UUID ACCOUNT_UUID = UUID.fromString("c980fa44-619e-4ca4-8ad6-75b0538a66a3"); + + @Test + void sequenceZeroRequiresTheOriginalPositiveBaselineAndNoCheckpoint() { + AccountAuthorityOutboxRepository outbox = mock(AccountAuthorityOutboxRepository.class); + AccountPasswordResetOperationRepository resets = + mock(AccountPasswordResetOperationRepository.class); + AccountLogoutAllOperationRepository logouts = mock(AccountLogoutAllOperationRepository.class); + AccountAuthoritySourceEventReadback readback = + new AccountAuthoritySourceEventReadback( + outbox, + resets, + logouts, + org.mockito.Mockito.mock( + net.firedevops.firemud.accountservice.repository + .AccountSecurityStateOperationRepository.class)); + when(outbox.readCheckpoint("account:auth-authority:v1:account/" + ACCOUNT_UUID)) + .thenReturn(Optional.empty()); + boolean previouslyActive = TransactionSynchronizationManager.isActualTransactionActive(); + TransactionSynchronizationManager.setActualTransactionActive(true); + + try { + var snapshot = + readback.requireCurrentLatest( + account(), + new AccountAuthorityGenerationRepository.ScopeState( + AccountAuthorityGenerationRepository.AuthorityScope.account(ACCOUNT_UUID), + 1L, + 1L, + new AccountAuthorityGenerationRepository.IssuanceFence(ACCOUNT_UUID, 4L, 3L))); + + assertThat(snapshot.outboxSequence()).isZero(); + assertThat(snapshot.latestEvent()).isEmpty(); + verifyNoInteractions(resets, logouts); + } finally { + TransactionSynchronizationManager.setActualTransactionActive(previouslyActive); + } + } + + @Test + void sequenceZeroNeverRepairsAProgressedSourceWithoutHistory() { + AccountAuthorityOutboxRepository outbox = mock(AccountAuthorityOutboxRepository.class); + AccountAuthoritySourceEventReadback readback = + new AccountAuthoritySourceEventReadback( + outbox, + mock(AccountPasswordResetOperationRepository.class), + mock(AccountLogoutAllOperationRepository.class), + org.mockito.Mockito.mock( + net.firedevops.firemud.accountservice.repository + .AccountSecurityStateOperationRepository.class)); + when(outbox.readCheckpoint("account:auth-authority:v1:account/" + ACCOUNT_UUID)) + .thenReturn(Optional.empty()); + boolean previouslyActive = TransactionSynchronizationManager.isActualTransactionActive(); + TransactionSynchronizationManager.setActualTransactionActive(true); + + try { + assertThatThrownBy( + () -> + readback.requireCurrentLatest( + account(), + new AccountAuthorityGenerationRepository.ScopeState( + AccountAuthorityGenerationRepository.AuthorityScope.account(ACCOUNT_UUID), + 2L, + 2L, + new AccountAuthorityGenerationRepository.IssuanceFence( + ACCOUNT_UUID, 5L, 4L)))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("original positive 1/1 baseline"); + } finally { + TransactionSynchronizationManager.setActualTransactionActive(previouslyActive); + } + } + + @Test + void presentCheckpointIsContradictoryAtPristineBaselineAndSingleCounterProgression() { + AccountAuthorityOutboxRepository outbox = mock(AccountAuthorityOutboxRepository.class); + AccountPasswordResetOperationRepository resets = + mock(AccountPasswordResetOperationRepository.class); + AccountLogoutAllOperationRepository logouts = mock(AccountLogoutAllOperationRepository.class); + AccountAuthoritySourceEventReadback readback = + new AccountAuthoritySourceEventReadback( + outbox, + resets, + logouts, + org.mockito.Mockito.mock( + net.firedevops.firemud.accountservice.repository + .AccountSecurityStateOperationRepository.class)); + String streamKey = "account:auth-authority:v1:account/" + ACCOUNT_UUID; + when(outbox.readCheckpoint(streamKey)) + .thenReturn( + Optional.of(new Checkpoint(streamKey, 1L, "event-id", "sha256:" + "a".repeat(64)))); + boolean previouslyActive = TransactionSynchronizationManager.isActualTransactionActive(); + TransactionSynchronizationManager.setActualTransactionActive(true); + + try { + assertRejectedCheckpoint(readback, 1L, 1L, "contradictory event history"); + assertRejectedCheckpoint(readback, 2L, 1L, "history is not proven"); + assertRejectedCheckpoint(readback, 1L, 2L, "history is not proven"); + + verify(outbox, never()).findEvent(streamKey, 1L); + verifyNoInteractions(resets, logouts); + } finally { + TransactionSynchronizationManager.setActualTransactionActive(previouslyActive); + } + } + + @Test + void retainedPasswordResetUsesImmutableReceiptWithoutMakingItsVerifierCurrent() { + AccountAuthorityOutboxRepository outbox = mock(AccountAuthorityOutboxRepository.class); + AccountPasswordResetOperationRepository resets = + mock(AccountPasswordResetOperationRepository.class); + AccountLogoutAllOperationRepository logouts = mock(AccountLogoutAllOperationRepository.class); + AccountAuthoritySourceEventReadback readback = + new AccountAuthoritySourceEventReadback( + outbox, + resets, + logouts, + org.mockito.Mockito.mock( + net.firedevops.firemud.accountservice.repository + .AccountSecurityStateOperationRepository.class)); + Account account = account(); + account.setPasswordHash("a-later-password-verifier"); + Event retained = passwordResetEvent(ACCOUNT_UUID, 1L, 2L, 2L, "a".repeat(64)); + PasswordResetReceipt receipt = passwordResetReceipt(retained, 2L, 2L); + String streamKey = "account:auth-authority:v1:account/" + ACCOUNT_UUID; + when(outbox.readCheckpoint(streamKey)) + .thenReturn( + Optional.of(new Checkpoint(streamKey, 2L, "later-event", "sha256:" + "c".repeat(64)))); + when(resets.findByRequestId(receipt.requestId())).thenReturn(Optional.of(receipt)); + AccountAuthorityGenerationRepository.ScopeState current = accountState(3L, 3L, 3L, 3L); + + var evidence = readback.requireRetainedEvent(account, retained, current); + assertThat(evidence.accountAuthorityGeneration()).isEqualTo(2L); + assertThat(evidence.sourceVersion()).isEqualTo(2L); + assertThat(evidence.issuanceFence()).isEqualTo(2L); + assertThat(evidence.issuanceFenceSourceVersion()).isEqualTo(2L); + assertThat(account.getPasswordHash()).isEqualTo("a-later-password-verifier"); + assertThat(current.generation()).isEqualTo(3L); + + verify(resets).findByRequestId(receipt.requestId()); + verifyNoInteractions(logouts); + } + + @Test + void latestPasswordResetStillRequiresItsRecordedVerifierToBeCurrent() { + AccountAuthorityOutboxRepository outbox = mock(AccountAuthorityOutboxRepository.class); + AccountPasswordResetOperationRepository resets = + mock(AccountPasswordResetOperationRepository.class); + AccountLogoutAllOperationRepository logouts = mock(AccountLogoutAllOperationRepository.class); + AccountAuthoritySourceEventReadback readback = + new AccountAuthoritySourceEventReadback( + outbox, + resets, + logouts, + org.mockito.Mockito.mock( + net.firedevops.firemud.accountservice.repository + .AccountSecurityStateOperationRepository.class)); + Account account = account(); + account.setPasswordHash("a-later-password-verifier"); + Event latest = passwordResetEvent(ACCOUNT_UUID, 1L, 2L, 2L, "b".repeat(64)); + PasswordResetReceipt receipt = passwordResetReceipt(latest, 7L, 6L); + String streamKey = "account:auth-authority:v1:account/" + ACCOUNT_UUID; + when(outbox.readCheckpoint(streamKey)) + .thenReturn( + Optional.of(new Checkpoint(streamKey, 1L, latest.eventId(), latest.eventDigest()))); + when(outbox.findEvent(streamKey, 1L)).thenReturn(Optional.of(latest)); + when(resets.findByRequestId(receipt.requestId())).thenReturn(Optional.of(receipt)); + + assertThatThrownBy(() -> readback.requireCurrentLatest(account, accountState(2L, 2L, 7L, 6L))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("does not match the current password verifier"); + } + + @Test + void currentReadRejectsEarlierGenericMutationEvenWhenTheStreamHasAdvancedPastIt() { + AccountAuthorityOutboxRepository outbox = mock(AccountAuthorityOutboxRepository.class); + AccountAuthoritySourceEventReadback readback = + new AccountAuthoritySourceEventReadback( + outbox, + mock(AccountPasswordResetOperationRepository.class), + mock(AccountLogoutAllOperationRepository.class), + org.mockito.Mockito.mock( + net.firedevops.firemud.accountservice.repository + .AccountSecurityStateOperationRepository.class)); + String streamKey = "account:auth-authority:v1:account/" + ACCOUNT_UUID; + var generic = + AccountAuthoritySourceEventV1Codec.sealAccount( + new AccountPreimage( + "legacy-event-1", + "legacy-request-1", + streamKey, + "1", + ACCOUNT_UUID.toString(), + "2", + "2", + "2", + "2", + List.of("EMAIL_LOGIN_ELIGIBILITY_CHANGED"), + new AccountState(true, List.of("PASSWORD"), "PLAYER", "ACTIVE"))); + Event retainedGenericEvent = + new Event( + streamKey, + generic.requestId(), + 1L, + generic.eventId(), + generic.eventDigest(), + generic.canonicalJsonUtf8()); + when(outbox.readCheckpoint(streamKey)) + .thenReturn( + Optional.of( + new Checkpoint(streamKey, 2L, "later-closed-event", "sha256:" + "c".repeat(64)))); + when(outbox.findEvent(streamKey, 1L)).thenReturn(Optional.of(retainedGenericEvent)); + boolean previouslyActive = TransactionSynchronizationManager.isActualTransactionActive(); + TransactionSynchronizationManager.setActualTransactionActive(true); + + try { + assertThatThrownBy( + () -> readback.requireCurrentLatest(account(), accountState(3L, 3L, 3L, 3L))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Account source event schema is unsupported"); + + verify(outbox, never()).findEvent(streamKey, 2L); + } finally { + TransactionSynchronizationManager.setActualTransactionActive(previouslyActive); + } + } + + @Test + void retainedLogoutAllEventRequiresItsExactImmutableReceipt() { + AccountAuthorityOutboxRepository outbox = mock(AccountAuthorityOutboxRepository.class); + AccountPasswordResetOperationRepository resets = + mock(AccountPasswordResetOperationRepository.class); + AccountLogoutAllOperationRepository logouts = mock(AccountLogoutAllOperationRepository.class); + AccountAuthoritySourceEventReadback readback = + new AccountAuthoritySourceEventReadback( + outbox, + resets, + logouts, + org.mockito.Mockito.mock( + net.firedevops.firemud.accountservice.repository + .AccountSecurityStateOperationRepository.class)); + Event retained = + logoutAllEvent( + ACCOUNT_UUID, UUID.fromString("a980fa44-619e-4ca4-8ad6-75b0538a66a3"), 1L, 2L, 2L); + LogoutAllReceipt receipt = logoutReceipt(retained, 2L, 2L); + String streamKey = "account:auth-authority:v1:account/" + ACCOUNT_UUID; + when(outbox.readCheckpoint(streamKey)) + .thenReturn( + Optional.of(new Checkpoint(streamKey, 2L, "later-event", "sha256:" + "d".repeat(64)))); + when(logouts.findByRequestId(receipt.requestId())).thenReturn(Optional.of(receipt)); + + var current = accountState(3L, 3L, 3L, 3L); + var evidence = readback.requireRetainedEvent(account(), retained, current); + assertThat(evidence.accountAuthorityGeneration()).isEqualTo(2L); + assertThat(evidence.sourceVersion()).isEqualTo(2L); + assertThat(evidence.issuanceFence()).isEqualTo(2L); + assertThat(evidence.issuanceFenceSourceVersion()).isEqualTo(2L); + assertThat(current.generation()).isEqualTo(3L); + + verify(logouts).findByRequestId(receipt.requestId()); + verifyNoInteractions(resets); + } + + @Test + void retainedReadRejectsChangedEventBytesAndMissingReceipts() { + AccountAuthorityOutboxRepository outbox = mock(AccountAuthorityOutboxRepository.class); + AccountPasswordResetOperationRepository resets = + mock(AccountPasswordResetOperationRepository.class); + AccountLogoutAllOperationRepository logouts = mock(AccountLogoutAllOperationRepository.class); + AccountAuthoritySourceEventReadback readback = + new AccountAuthoritySourceEventReadback( + outbox, + resets, + logouts, + org.mockito.Mockito.mock( + net.firedevops.firemud.accountservice.repository + .AccountSecurityStateOperationRepository.class)); + Event valid = passwordResetEvent(ACCOUNT_UUID, 1L, 2L, 2L, "e".repeat(64)); + String streamKey = "account:auth-authority:v1:account/" + ACCOUNT_UUID; + when(outbox.readCheckpoint(streamKey)) + .thenReturn( + Optional.of(new Checkpoint(streamKey, 2L, "later-event", "sha256:" + "f".repeat(64)))); + byte[] changedPayload = valid.payload(); + changedPayload[changedPayload.length - 2] ^= 1; + Event changedBytes = + new Event( + valid.outboxStreamKey(), + valid.requestId(), + valid.outboxSequence(), + valid.eventId(), + valid.eventDigest(), + changedPayload); + + assertThatThrownBy( + () -> + readback.requireRetainedEvent( + account(), changedBytes, accountState(3L, 3L, 8L, 7L))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Account source event is invalid"); + + Event changedDigest = + new Event( + valid.outboxStreamKey(), + valid.requestId(), + valid.outboxSequence(), + valid.eventId(), + "sha256:" + "0".repeat(64), + valid.payload()); + assertThatThrownBy( + () -> + readback.requireRetainedEvent( + account(), changedDigest, accountState(3L, 3L, 8L, 7L))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("readback is inconsistent"); + + Event unsupportedSchema = + new Event( + valid.outboxStreamKey(), + "unsupported-request", + 1L, + "unsupported-event", + "sha256:" + "1".repeat(64), + "{}".getBytes(StandardCharsets.UTF_8)); + assertThatThrownBy( + () -> + readback.requireRetainedEvent( + account(), unsupportedSchema, accountState(3L, 3L, 8L, 7L))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("schema is missing"); + + Event wrongAccount = + passwordResetEvent( + UUID.fromString("d980fa44-619e-4ca4-8ad6-75b0538a66a3"), 1L, 2L, 2L, "f".repeat(64)); + assertThatThrownBy( + () -> + readback.requireRetainedEvent( + account(), wrongAccount, accountState(3L, 3L, 8L, 7L))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("readback is inconsistent"); + + PasswordResetReceipt receipt = passwordResetReceipt(valid, 7L, 6L); + PasswordResetReceipt mismatchedReceipt = + new PasswordResetReceipt( + receipt.accountId(), + receipt.accountUuid(), + receipt.tokenHash(), + receipt.operationKind(), + receipt.requestId(), + receipt.requestDigestVersion(), + receipt.requestDigest(), + receipt.tokenExpiresAt(), + receipt.passwordVerifierDigest(), + receipt.outboxStreamKey(), + receipt.outboxSequence(), + receipt.eventId(), + "sha256:" + "2".repeat(64), + receipt.accountAuthorityGeneration(), + receipt.accountSourceVersion(), + receipt.issuanceFence(), + receipt.issuanceFenceSourceVersion()); + when(resets.findByRequestId(valid.requestId())) + .thenReturn(Optional.empty(), Optional.of(mismatchedReceipt)); + assertThatThrownBy( + () -> readback.requireRetainedEvent(account(), valid, accountState(3L, 3L, 8L, 7L))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("no immutable operation receipt"); + assertThatThrownBy( + () -> readback.requireRetainedEvent(account(), valid, accountState(3L, 3L, 8L, 7L))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("receipt does not match its source event"); + } + + @Test + void structuralSecurityStateSnapshotAcceptsCompleteCurrentAndRetainedEvents() { + Event original = securityStateEvent(ACCOUNT_UUID, 1L, "2", "2"); + AccountSourceSnapshot originalSnapshot = structuralSnapshot(original, 2L, 2L); + AccountSourceSnapshot newer = + structuralSnapshot(securityStateEvent(ACCOUNT_UUID, 2L, "3", "3"), 3L, 3L); + + assertThat(originalSnapshot.latestEvent()).contains(original); + assertThat(new AccountSourceEventReadback(newer, original).requestedEvent()) + .isEqualTo(original); + } + + @Test + void structuralSecurityStateSnapshotBindsEveryEventIndexAndCompleteCanonicalBytes() + throws Exception { + Event original = securityStateEvent(ACCOUNT_UUID, 1L, "2", "2"); + ObjectMapper json = new ObjectMapper(); + ObjectNode substituted = (ObjectNode) json.readTree(original.payload()); + ((ObjectNode) substituted.get("accountState")).put("emailVerified", false); + ObjectNode wrongScope = (ObjectNode) json.readTree(original.payload()); + wrongScope.put("sourceScope", "account/aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + for (Event invalid : + List.of( + new Event( + original.outboxStreamKey(), + "33333333-3333-4333-8333-333333333333", + 1L, + original.eventId(), + original.eventDigest(), + original.payload()), + new Event( + original.outboxStreamKey(), + original.requestId(), + 1L, + original.eventId() + "other", + original.eventDigest(), + original.payload()), + new Event( + original.outboxStreamKey(), + original.requestId(), + 1L, + original.eventId(), + "sha256:" + "a".repeat(64), + original.payload()), + new Event( + original.outboxStreamKey(), + original.requestId(), + 2L, + original.eventId(), + original.eventDigest(), + original.payload()), + withPayload(original, substituted.toString().getBytes(StandardCharsets.UTF_8)), + withPayload(original, wrongScope.toString().getBytes(StandardCharsets.UTF_8)), + withPayload( + original, + (" " + new String(original.payload(), StandardCharsets.UTF_8)) + .getBytes(StandardCharsets.UTF_8)))) { + assertThatThrownBy(() -> structuralSnapshot(invalid, 2L, 2L)) + .isInstanceOf(IllegalStateException.class); + } + Event foreign = + securityStateEvent(UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), 1L, "2", "2"); + assertThatThrownBy(() -> structuralSnapshot(foreign, 2L, 2L)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void structuralSecurityStateCountersRequireCurrentEqualityAndRetainedNotAhead() { + Event generationMismatch = securityStateEvent(ACCOUNT_UUID, 1L, "3", "2"); + Event versionMismatch = securityStateEvent(ACCOUNT_UUID, 1L, "2", "3"); + Event arbitraryPrecision = + securityStateEvent(ACCOUNT_UUID, 1L, "922337203685477580812345678901234567890", "2"); + AccountSourceSnapshot current = + structuralSnapshot(securityStateEvent(ACCOUNT_UUID, 2L, "3", "3"), 3L, 3L); + for (Event invalid : List.of(generationMismatch, versionMismatch, arbitraryPrecision)) { + assertThatThrownBy(() -> structuralSnapshot(invalid, 2L, 2L)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("counters contradict or lead"); + } + assertThatThrownBy(() -> new AccountSourceEventReadback(current, arbitraryPrecision)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("counters contradict or lead"); + } + + @Test + void structurallyValidSecurityStateWithoutReceiptCannotPassOwnerReadback() { + AccountAuthorityOutboxRepository outbox = mock(AccountAuthorityOutboxRepository.class); + AccountPasswordResetOperationRepository resets = + mock(AccountPasswordResetOperationRepository.class); + AccountLogoutAllOperationRepository logouts = mock(AccountLogoutAllOperationRepository.class); + AccountAuthoritySourceEventReadback readback = + new AccountAuthoritySourceEventReadback( + outbox, + resets, + logouts, + org.mockito.Mockito.mock( + net.firedevops.firemud.accountservice.repository + .AccountSecurityStateOperationRepository.class)); + Event event = securityStateEvent(ACCOUNT_UUID, 1L, "2", "2"); + assertThat(structuralSnapshot(event, 2L, 2L).latestEvent()).contains(event); + when(outbox.readCheckpoint(event.outboxStreamKey())) + .thenReturn( + Optional.of( + new Checkpoint(event.outboxStreamKey(), 1L, event.eventId(), event.eventDigest()))); + when(outbox.findEvent(event.outboxStreamKey(), 1L)).thenReturn(Optional.of(event)); + + assertThatThrownBy(() -> readback.requireCurrentLatest(account(), accountState(2L, 2L, 2L, 2L))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("no immutable operation receipt"); + assertThatThrownBy( + () -> readback.requireRetainedEvent(account(), event, accountState(3L, 3L, 3L, 3L))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("no immutable operation receipt"); + verifyNoInteractions(resets, logouts); + } + + private AccountSourceSnapshot structuralSnapshot( + Event event, long generation, long sourceVersion) { + return new AccountSourceSnapshot( + ACCOUNT_UUID, + accountState(generation, sourceVersion, 2L, 2L), + "account:auth-authority:v1:account/" + ACCOUNT_UUID, + event.outboxSequence(), + Optional.of(event)); + } + + private Event withPayload(Event original, byte[] payload) { + return new Event( + original.outboxStreamKey(), + original.requestId(), + original.outboxSequence(), + original.eventId(), + original.eventDigest(), + payload); + } + + private Event securityStateEvent( + UUID accountUuid, long sequence, String generation, String sourceVersion) { + String requestId = "11111111-1111-4111-8111-111111111111"; + String stream = "account:auth-authority:v1:account/" + accountUuid; + var event = + AccountSecurityStateAuthorityEventV1Codec.seal( + Map.ofEntries( + Map.entry( + "schemaVersion", AccountSecurityStateAuthorityEventV1Codec.SCHEMA_VERSION), + Map.entry("eventType", AccountSecurityStateAuthorityEventV1Codec.EVENT_TYPE), + Map.entry( + "eventId", + AccountSecurityStateAuthorityEventV1Codec.EVENT_ID_PREFIX + requestId), + Map.entry("requestId", requestId), + Map.entry("accountId", accountUuid.toString()), + Map.entry("sourceScope", "account/" + accountUuid), + Map.entry("outboxStreamKey", stream), + Map.entry("outboxSequence", Long.toString(sequence)), + Map.entry("accountAuthorityGeneration", generation), + Map.entry("sourceVersion", sourceVersion), + Map.entry( + "accountSecurityCutoff", + Map.of( + "accountAuthorityGeneration", + generation, + "outboxStreamKey", + stream, + "outboxSequence", + Long.toString(sequence))), + Map.entry("mutationKinds", List.of("EMAIL_LOGIN_ELIGIBILITY_CHANGED")), + Map.entry( + "accountState", + Map.of( + "emailVerified", + true, + "loginAuthModes", + List.of("PASSWORD"), + "globalRoles", + List.of(), + "lifecycleState", + "ACTIVE")))); + return new Event( + stream, + requestId, + sequence, + event.eventId(), + event.eventDigest(), + event.canonicalJsonUtf8()); + } + + private void assertRejectedCheckpoint( + AccountAuthoritySourceEventReadback readback, + long generation, + long sourceVersion, + String expectedMessage) { + assertThatThrownBy( + () -> + readback.requireCurrentLatest( + account(), + new AccountAuthorityGenerationRepository.ScopeState( + AccountAuthorityGenerationRepository.AuthorityScope.account(ACCOUNT_UUID), + generation, + sourceVersion, + new AccountAuthorityGenerationRepository.IssuanceFence( + ACCOUNT_UUID, 4L, 3L)))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining(expectedMessage); + } + + private Account account() { + Account account = new Account(); + account.setId(11L); + account.setAccountUuid(ACCOUNT_UUID); + account.setAccountUuidProvenance(AccountIdentityProvenance.ACCOUNT_DATABASE_INSERT); + account.setAccountUuidSourceNumericId(11L); + account.setPasswordHash("unused-on-sequence-zero"); + return account; + } + + private AccountAuthorityGenerationRepository.ScopeState accountState( + long generation, long sourceVersion, long fence, long fenceSourceVersion) { + return new AccountAuthorityGenerationRepository.ScopeState( + AccountAuthorityGenerationRepository.AuthorityScope.account(ACCOUNT_UUID), + generation, + sourceVersion, + new AccountAuthorityGenerationRepository.IssuanceFence( + ACCOUNT_UUID, fence, fenceSourceVersion)); + } + + private Event passwordResetEvent( + UUID accountUuid, long sequence, long generation, long sourceVersion, String tokenHash) { + String streamKey = "account:auth-authority:v1:account/" + accountUuid; + String requestId = "account-password-reset-request-v1:" + tokenHash; + String eventId = "account-password-reset-event-v1:" + tokenHash; + var sealed = + PasswordResetAuthorityEventV1Codec.seal( + Map.ofEntries( + Map.entry("schemaVersion", PasswordResetAuthorityEventV1Codec.SCHEMA_VERSION), + Map.entry("eventType", PasswordResetAuthorityEventV1Codec.EVENT_TYPE), + Map.entry("eventId", eventId), + Map.entry("requestId", requestId), + Map.entry("accountId", accountUuid.toString()), + Map.entry("sourceScope", "account/" + accountUuid), + Map.entry("outboxStreamKey", streamKey), + Map.entry("outboxSequence", Long.toString(sequence)), + Map.entry("accountAuthorityGeneration", Long.toString(generation)), + Map.entry("sourceVersion", Long.toString(sourceVersion)), + Map.entry( + "accountSecurityCutoff", + Map.of( + "accountAuthorityGeneration", Long.toString(generation), + "outboxStreamKey", streamKey, + "outboxSequence", Long.toString(sequence))))); + return new Event( + streamKey, requestId, sequence, eventId, sealed.eventDigest(), sealed.canonicalJsonUtf8()); + } + + private PasswordResetReceipt passwordResetReceipt( + Event event, long fence, long fenceSourceVersion) { + String tokenHash = event.requestId().substring("account-password-reset-request-v1:".length()); + LocalDateTime tokenDeadline = LocalDateTime.of(2030, 1, 2, 3, 4, 5); + String verifierDigest = "b".repeat(64); + return new PasswordResetReceipt( + 11L, + ACCOUNT_UUID, + tokenHash, + "PASSWORD_RESET", + event.requestId(), + 1, + passwordResetRequestDigest( + ACCOUNT_UUID, tokenHash, tokenDeadline.toString(), verifierDigest), + tokenDeadline, + verifierDigest, + event.outboxStreamKey(), + event.outboxSequence(), + event.eventId(), + event.eventDigest(), + 2L, + 2L, + fence, + fenceSourceVersion); + } + + private Event logoutAllEvent( + UUID accountUuid, UUID requestId, long sequence, long generation, long sourceVersion) { + String streamKey = "account:auth-authority:v1:account/" + accountUuid; + String eventId = "account-logout-all-event-v1:" + requestId; + var sealed = + AccountLogoutAllAuthorityEventV1Codec.seal( + Map.ofEntries( + Map.entry("schemaVersion", AccountLogoutAllAuthorityEventV1Codec.SCHEMA_VERSION), + Map.entry("eventType", AccountLogoutAllAuthorityEventV1Codec.EVENT_TYPE), + Map.entry("eventId", eventId), + Map.entry("requestId", requestId.toString()), + Map.entry("accountId", accountUuid.toString()), + Map.entry("sourceScope", "account/" + accountUuid), + Map.entry("outboxStreamKey", streamKey), + Map.entry("outboxSequence", Long.toString(sequence)), + Map.entry("accountAuthorityGeneration", Long.toString(generation)), + Map.entry("sourceVersion", Long.toString(sourceVersion)), + Map.entry( + "accountSecurityCutoff", + Map.of( + "accountAuthorityGeneration", Long.toString(generation), + "outboxStreamKey", streamKey, + "outboxSequence", Long.toString(sequence))))); + return new Event( + streamKey, + requestId.toString(), + sequence, + eventId, + sealed.eventDigest(), + sealed.canonicalJsonUtf8()); + } + + private LogoutAllReceipt logoutReceipt(Event event, long fence, long fenceSourceVersion) { + UUID requestId = UUID.fromString(event.requestId()); + String tokenHash = "c".repeat(64); + String tokenProfile = "control-ui"; + return new LogoutAllReceipt( + requestId, + 11L, + ACCOUNT_UUID, + "ACCOUNT_LOGOUT_ALL", + 1, + AccountLogoutRequestDigest.accountLogoutAll(ACCOUNT_UUID, tokenProfile, tokenHash), + tokenHash, + tokenProfile, + event.outboxStreamKey(), + event.outboxSequence(), + event.eventId(), + event.eventDigest(), + 2L, + 2L, + fence, + fenceSourceVersion, + "LOGOUT_ALL_COMMITTED"); + } + + private String passwordResetRequestDigest( + UUID accountUuid, String tokenHash, String tokenDeadline, String verifierDigest) { + try { + MessageDigest digest = MessageDigest.getInstance("SHA-256"); + updateLengthPrefixed(digest, "account-password-reset-request/v1"); + updateLengthPrefixed(digest, "PASSWORD_RESET"); + updateLengthPrefixed(digest, accountUuid.toString()); + updateLengthPrefixed(digest, tokenHash); + updateLengthPrefixed(digest, tokenDeadline); + updateLengthPrefixed(digest, verifierDigest); + return HexFormat.of().formatHex(digest.digest()); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + private void updateLengthPrefixed(MessageDigest digest, String value) { + byte[] encoded = value.getBytes(StandardCharsets.UTF_8); + digest.update(ByteBuffer.allocate(Integer.BYTES).putInt(encoded.length).array()); + digest.update(encoded); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountGenerationProjectionTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountGenerationProjectionTest.java new file mode 100644 index 0000000000..b0702a25ef --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountGenerationProjectionTest.java @@ -0,0 +1,334 @@ +package unit.net.firedevops.firemud.accountservice.service; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.IssuanceFence; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeState; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Event; +import net.firedevops.firemud.accountservice.service.AccountAuthoritySourceReader.AccountSourceSnapshot; +import net.firedevops.firemud.accountservice.service.AccountGenerationProjection; +import net.firedevops.firemud.common.account.authority.AccountLogoutAllAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.AccountSecurityStateAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.PasswordResetAuthorityEventV1Codec; +import org.junit.jupiter.api.Test; + +class AccountGenerationProjectionTest { + private static final UUID ACCOUNT_ID = UUID.fromString("c980fa44-619e-4ca4-8ad6-75b0538a66a3"); + private static final String ACCOUNT_TEXT = ACCOUNT_ID.toString(); + private static final String STREAM_KEY = "account:auth-authority:v1:account/" + ACCOUNT_TEXT; + + @Test + void emitsExactSequenceZeroBaselineWithoutAnEvent() { + AccountGenerationProjection projection = + projection(ACCOUNT_TEXT, "1", "1", "0", Optional.empty()); + + assertThat(projection.key()).isEqualTo("session:auth:generation:account:" + ACCOUNT_TEXT); + assertThat(projection.toJson()) + .isEqualTo( + "{\"schemaVersion\":\"account-auth-account-generation-projection/v1\"," + + "\"accountId\":\"" + + ACCOUNT_TEXT + + "\",\"accountAuthorityGeneration\":\"1\",\"sourceVersion\":\"1\"," + + "\"outboxStreamKey\":\"" + + STREAM_KEY + + "\",\"outboxSequence\":\"0\"}"); + assertThat(AccountGenerationProjection.parse(projection.toJson())).isEqualTo(projection); + } + + @Test + void preservesCanonicalClosedPasswordResetAndLogoutAllEventsAsStrings() { + AccountGenerationProjection resetProjection = + projection(ACCOUNT_TEXT, "4", "5", "3", Optional.of(resetEvent("4", "5", "3"))); + AccountGenerationProjection logoutProjection = + projection(ACCOUNT_TEXT, "6", "8", "5", Optional.of(logoutEvent("6", "8", "5"))); + + assertThat(AccountGenerationProjection.parse(resetProjection.toJson())) + .isEqualTo(resetProjection); + assertThat(AccountGenerationProjection.parse(logoutProjection.toJson())) + .isEqualTo(logoutProjection); + assertThat(resetProjection.sourceEvent()).contains(resetEvent("4", "5", "3")); + assertThat(logoutProjection.sourceEvent()).contains(logoutEvent("6", "8", "5")); + } + + @Test + void acceptsLargeCanonicalCountersWithoutLongConversion() { + String large = "922337203685477580812345678901234567890"; + AccountGenerationProjection projection = + projection( + ACCOUNT_TEXT, large, large, large, Optional.of(logoutEvent(large, large, large))); + + assertThat(projection.generationValue()).isEqualTo(new BigInteger(large)); + assertThat(projection.sourceVersionValue()).isEqualTo(new BigInteger(large)); + assertThat(projection.outboxSequenceValue()).isEqualTo(new BigInteger(large)); + assertThat(AccountGenerationProjection.parse(projection.toJson())).isEqualTo(projection); + } + + @Test + void closesTheProjectionShapeAndRejectsDuplicateUnknownNullAndNoncanonicalEvidence() { + String baseline = projection(ACCOUNT_TEXT, "1", "1", "0", Optional.empty()).toJson(); + String duplicateAccountId = + baseline.replace( + "\"accountId\":\"" + ACCOUNT_TEXT + "\"", + "\"accountId\":\"" + ACCOUNT_TEXT + "\",\"accountId\":\"" + ACCOUNT_TEXT + "\""); + String unknownField = + baseline.substring(0, baseline.length() - 1) + ",\"issuanceFence\":\"1\"}"; + String nullEvent = baseline.substring(0, baseline.length() - 1) + ",\"sourceEvent\":null}"; + String noncanonicalSequence = + baseline.replace("\"outboxSequence\":\"0\"", "\"outboxSequence\":\"00\""); + String reordered = + baseline.replace( + "\"schemaVersion\":\"account-auth-account-generation-projection/v1\"," + + "\"accountId\":\"" + + ACCOUNT_TEXT + + "\",", + "\"accountId\":\"" + + ACCOUNT_TEXT + + "\",\"schemaVersion\":\"account-auth-account-generation-projection/v1\","); + + assertThatThrownBy(() -> AccountGenerationProjection.parse(duplicateAccountId)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> AccountGenerationProjection.parse(unknownField)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> AccountGenerationProjection.parse(nullEvent)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> AccountGenerationProjection.parse(noncanonicalSequence)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> AccountGenerationProjection.parse(reordered)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void rejectsChangedEventCheckpointAndInvalidSequenceZeroRepresentations() { + String event = logoutEvent("2", "2", "1"); + + assertThatThrownBy(() -> projection(ACCOUNT_TEXT, "3", "2", "1", Optional.of(event))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("does not match"); + assertThatThrownBy(() -> projection(ACCOUNT_TEXT, "2", "2", "0", Optional.empty())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("sequence zero"); + assertThatThrownBy(() -> projection(ACCOUNT_TEXT, "2", "2", "1", Optional.empty())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("requires advanced counters"); + } + + @Test + void localIssuanceFenceIsNotSerializedOrComparedAsProjectionEvidence() { + AccountGenerationProjection first = + AccountGenerationProjection.fromSource(source(1L, 1L, 0L, Optional.empty(), 4L)); + AccountGenerationProjection withNewerLocalFence = + AccountGenerationProjection.fromSource(source(1L, 1L, 0L, Optional.empty(), 99L)); + + assertThat(withNewerLocalFence).isEqualTo(first); + assertThat(first.toJson()).doesNotContain("issuanceFence"); + } + + @Test + void preservesTheCompleteSecurityStateEventWithTheOriginalProjectionSchema() { + String event = securityEvent(ACCOUNT_TEXT, "2", "2", "1"); + AccountGenerationProjection projection = + projection(ACCOUNT_TEXT, "2", "2", "1", Optional.of(event)); + + assertThat(AccountGenerationProjection.parse(projection.toJson())).isEqualTo(projection); + assertThat(projection.sourceEvent()).contains(event); + assertThat(projection.toJson()) + .startsWith("{\"schemaVersion\":\"account-auth-account-generation-projection/v1\""); + assertThat(projection.key()).isEqualTo("session:auth:generation:account:" + ACCOUNT_TEXT); + assertThat(projection.toJson()).doesNotContain("issuanceFence"); + } + + @Test + void securityStateCountersRetainArbitraryPrecisionThroughProjectionRoundtrip() { + String large = "18446744073709551616000000000000000001"; + String event = securityEvent(ACCOUNT_TEXT, large, large, large); + AccountGenerationProjection projection = + projection(ACCOUNT_TEXT, large, large, large, Optional.of(event)); + + assertThat(AccountGenerationProjection.parse(projection.toJson())).isEqualTo(projection); + assertThat(projection.generationValue()).isEqualTo(new BigInteger(large)); + assertThat(projection.sourceVersionValue()).isEqualTo(new BigInteger(large)); + assertThat(projection.outboxSequenceValue()).isEqualTo(new BigInteger(large)); + assertThat(projection.sourceEvent()).contains(event); + } + + @Test + void securityStateRequiresExactAccountCountersAndCheckpoint() { + String event = securityEvent(ACCOUNT_TEXT, "2", "3", "4"); + String foreign = securityEvent("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa", "2", "3", "4"); + for (AccountGenerationProjectionRequest request : + List.of( + new AccountGenerationProjectionRequest("3", "3", "4", event), + new AccountGenerationProjectionRequest("2", "4", "4", event), + new AccountGenerationProjectionRequest("2", "3", "5", event), + new AccountGenerationProjectionRequest("2", "3", "4", foreign))) { + assertThatThrownBy( + () -> + projection( + ACCOUNT_TEXT, + request.generation(), + request.sourceVersion(), + request.sequence(), + Optional.of(request.event()))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("does not match its current projection checkpoint"); + } + } + + @Test + void securityStateRejectsSubstitutedStateNoncanonicalBytesGenericSchemasAndFences() + throws Exception { + String event = securityEvent(ACCOUNT_TEXT, "2", "2", "1"); + ObjectMapper json = new ObjectMapper(); + ObjectNode changedState = (ObjectNode) json.readTree(event); + ((ObjectNode) changedState.get("accountState")).put("emailVerified", false); + ObjectNode generic = (ObjectNode) json.readTree(event); + generic.put("schemaVersion", "account-auth-authority-source-event/v1"); + ObjectNode fence = (ObjectNode) json.readTree(event); + fence.put("issuanceFence", "2"); + ObjectNode wrongStream = (ObjectNode) json.readTree(event); + wrongStream.put("outboxStreamKey", STREAM_KEY + "other"); + for (String invalid : + List.of( + changedState.toString(), + generic.toString(), + fence.toString(), + wrongStream.toString(), + " " + event, + event.replace( + "\"emailVerified\":true", "\"emailVerified\":true,\"emailVerified\":true"))) { + assertThatThrownBy(() -> projection(ACCOUNT_TEXT, "2", "2", "1", Optional.of(invalid))) + .isInstanceOf(IllegalArgumentException.class); + } + assertThatThrownBy(() -> projection(ACCOUNT_TEXT, "1", "1", "0", Optional.of(event))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("sequence zero"); + } + + private record AccountGenerationProjectionRequest( + String generation, String sourceVersion, String sequence, String event) {} + + private static String securityEvent( + String accountId, String generation, String sourceVersion, String sequence) { + String requestId = "11111111-1111-4111-8111-111111111111"; + String stream = "account:auth-authority:v1:account/" + accountId; + return AccountSecurityStateAuthorityEventV1Codec.seal( + Map.ofEntries( + Map.entry( + "schemaVersion", AccountSecurityStateAuthorityEventV1Codec.SCHEMA_VERSION), + Map.entry("eventType", AccountSecurityStateAuthorityEventV1Codec.EVENT_TYPE), + Map.entry( + "eventId", + AccountSecurityStateAuthorityEventV1Codec.EVENT_ID_PREFIX + requestId), + Map.entry("requestId", requestId), + Map.entry("accountId", accountId), + Map.entry("sourceScope", "account/" + accountId), + Map.entry("outboxStreamKey", stream), + Map.entry("outboxSequence", sequence), + Map.entry("accountAuthorityGeneration", generation), + Map.entry("sourceVersion", sourceVersion), + Map.entry( + "accountSecurityCutoff", + Map.of( + "accountAuthorityGeneration", + generation, + "outboxStreamKey", + stream, + "outboxSequence", + sequence)), + Map.entry("mutationKinds", List.of("EMAIL_LOGIN_ELIGIBILITY_CHANGED")), + Map.entry( + "accountState", + Map.of( + "emailVerified", + true, + "loginAuthModes", + List.of("EMAIL_OTP", "PASSWORD"), + "globalRoles", + List.of(), + "lifecycleState", + "ACTIVE")))) + .canonicalJson(); + } + + private static AccountGenerationProjection projection( + String accountId, + String generation, + String sourceVersion, + String sequence, + Optional sourceEvent) { + return new AccountGenerationProjection( + accountId, generation, sourceVersion, STREAM_KEY, sequence, sourceEvent); + } + + private static String resetEvent(String generation, String sourceVersion, String sequence) { + var evidence = + PasswordResetAuthorityEventV1Codec.seal( + Map.ofEntries( + Map.entry("schemaVersion", PasswordResetAuthorityEventV1Codec.SCHEMA_VERSION), + Map.entry("eventType", PasswordResetAuthorityEventV1Codec.EVENT_TYPE), + Map.entry("eventId", "account-password-reset-event-v1:sample"), + Map.entry("requestId", "account-password-reset-request-v1:sample"), + Map.entry("accountId", ACCOUNT_TEXT), + Map.entry("sourceScope", "account/" + ACCOUNT_TEXT), + Map.entry("outboxStreamKey", STREAM_KEY), + Map.entry("outboxSequence", sequence), + Map.entry("accountAuthorityGeneration", generation), + Map.entry("sourceVersion", sourceVersion), + Map.entry( + "accountSecurityCutoff", + Map.of( + "accountAuthorityGeneration", generation, + "outboxStreamKey", STREAM_KEY, + "outboxSequence", sequence)))); + return new String(evidence.canonicalJsonUtf8(), StandardCharsets.UTF_8); + } + + private static String logoutEvent(String generation, String sourceVersion, String sequence) { + String requestId = "11111111-1111-4111-8111-111111111111"; + var evidence = + AccountLogoutAllAuthorityEventV1Codec.seal( + Map.ofEntries( + Map.entry("schemaVersion", AccountLogoutAllAuthorityEventV1Codec.SCHEMA_VERSION), + Map.entry("eventType", AccountLogoutAllAuthorityEventV1Codec.EVENT_TYPE), + Map.entry( + "eventId", AccountLogoutAllAuthorityEventV1Codec.EVENT_ID_PREFIX + requestId), + Map.entry("requestId", requestId), + Map.entry("accountId", ACCOUNT_TEXT), + Map.entry("sourceScope", "account/" + ACCOUNT_TEXT), + Map.entry("outboxStreamKey", STREAM_KEY), + Map.entry("outboxSequence", sequence), + Map.entry("accountAuthorityGeneration", generation), + Map.entry("sourceVersion", sourceVersion), + Map.entry( + "accountSecurityCutoff", + Map.of( + "accountAuthorityGeneration", generation, + "outboxStreamKey", STREAM_KEY, + "outboxSequence", sequence)))); + return new String(evidence.canonicalJsonUtf8(), StandardCharsets.UTF_8); + } + + private static AccountSourceSnapshot source( + long generation, long sourceVersion, long sequence, Optional event, long fenceValue) { + return new AccountSourceSnapshot( + ACCOUNT_ID, + new ScopeState( + AuthorityScope.account(ACCOUNT_ID), + generation, + sourceVersion, + new IssuanceFence(ACCOUNT_ID, fenceValue, 1L)), + STREAM_KEY, + sequence, + event); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/IssuerGenerationProjectionTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/IssuerGenerationProjectionTest.java new file mode 100644 index 0000000000..b33285952f --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/IssuerGenerationProjectionTest.java @@ -0,0 +1,122 @@ +package unit.net.firedevops.firemud.accountservice.service; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.math.BigInteger; +import java.util.Map; +import java.util.Optional; +import net.firedevops.firemud.accountservice.service.IssuerGenerationProjection; +import net.firedevops.firemud.common.account.authority.IssuerGenerationAuthorityEventV1Codec; +import org.junit.jupiter.api.Test; + +class IssuerGenerationProjectionTest { + @Test + void ownedAdvancedSourceKeepsCanonicalOriginalBytesAndRejectsCheckpointContradiction() { + String issuer = "firemud-account-service"; + String request = java.util.UUID.randomUUID().toString(); + String stream = "account:auth-authority:v1:issuer/" + issuer; + var event = + IssuerGenerationAuthorityEventV1Codec.seal( + Map.ofEntries( + Map.entry("schemaVersion", IssuerGenerationAuthorityEventV1Codec.SCHEMA_VERSION), + Map.entry("eventType", IssuerGenerationAuthorityEventV1Codec.EVENT_TYPE), + Map.entry("eventId", "account-issuer-authority-event-v1:" + request), + Map.entry("requestId", request), + Map.entry("issuerId", issuer), + Map.entry("sourceScope", "issuer/" + issuer), + Map.entry("outboxStreamKey", stream), + Map.entry("outboxSequence", "1"), + Map.entry("issuerAuthGeneration", "2"), + Map.entry("sourceVersion", "2"))); + var source = + new net.firedevops.firemud.accountservice.repository + .AccountAuthoritySourceEvidenceRepository.CurrentSourceEvidence( + net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository + .AuthorityScope.issuer(issuer), + 2L, + 2L, + null, + new net.firedevops.firemud.accountservice.repository + .AccountAuthoritySourceEvidenceRepository.SourceCheckpoint( + stream, 1L, Optional.of(event.eventId()), Optional.of(event.eventDigest())), + Optional.empty(), + "ISSUER_SCOPE_INSERT", + null, + null, + 7L, + null); + var stored = + new net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Event( + stream, request, 1L, event.eventId(), event.eventDigest(), event.canonicalJsonUtf8()); + var snapshot = + new net.firedevops.firemud.accountservice.repository + .AccountAuthoritySourceEvidenceRepository.CanonicalIssuerSourceSnapshot( + source, Optional.of(stored)); + assertThat(IssuerGenerationProjection.fromSource(snapshot).sourceEvent()) + .contains(event.canonicalJson()); + assertThatThrownBy(() -> IssuerGenerationProjection.fromSource(source)) + .isInstanceOf(IllegalArgumentException.class); + var contradictory = + new net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Event( + stream, + request, + 1L, + event.eventId(), + "sha256:" + "0".repeat(64), + event.canonicalJsonUtf8()); + assertThatThrownBy( + () -> + IssuerGenerationProjection.fromSource( + new net.firedevops.firemud.accountservice.repository + .AccountAuthoritySourceEvidenceRepository.CanonicalIssuerSourceSnapshot( + source, Optional.of(contradictory)))) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void exactCanonicalEventAndArbitraryPrecisionCountersSurviveOwnerRoundTrip() { + String issuer = "firemud-account-service"; + String generation = "92233720368547758081234567890"; + String sequence = "92233720368547758081234567889"; + String stream = "account:auth-authority:v1:issuer/" + issuer; + var event = + IssuerGenerationAuthorityEventV1Codec.seal( + Map.ofEntries( + Map.entry("schemaVersion", IssuerGenerationAuthorityEventV1Codec.SCHEMA_VERSION), + Map.entry("eventType", IssuerGenerationAuthorityEventV1Codec.EVENT_TYPE), + Map.entry("eventId", "canonical-issuer-event"), + Map.entry("requestId", "original-request"), + Map.entry("issuerId", issuer), + Map.entry("sourceScope", "issuer/" + issuer), + Map.entry("outboxStreamKey", stream), + Map.entry("outboxSequence", sequence), + Map.entry("issuerAuthGeneration", generation), + Map.entry("sourceVersion", generation))); + var projection = + new IssuerGenerationProjection( + issuer, + generation, + generation, + stream, + sequence, + Optional.of(event.eventId()), + Optional.of(event.eventDigest()), + Optional.of(event.canonicalJson())); + var parsed = IssuerGenerationProjection.parse(projection.toJson()); + assertThat(parsed).isEqualTo(projection); + assertThat(new BigInteger(parsed.issuerAuthGeneration())).isEqualTo(new BigInteger(generation)); + assertThatThrownBy( + () -> + IssuerGenerationProjection.parse( + projection.toJson().replace(event.eventDigest(), "sha256:" + "0".repeat(64)))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + IssuerGenerationProjection.parse( + projection + .toJson() + .replace("lastAppliedSourceOutboxSequence", "outboxSequence"))) + .isInstanceOf(IllegalArgumentException.class); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/AccountLogoutAllAuthorityEventV1Codec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/AccountLogoutAllAuthorityEventV1Codec.java new file mode 100644 index 0000000000..a9234264b4 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/AccountLogoutAllAuthorityEventV1Codec.java @@ -0,0 +1,355 @@ +package net.firedevops.firemud.common.account.authority; + +import com.fasterxml.jackson.core.JsonFactory; +import com.fasterxml.jackson.core.StreamReadFeature; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; + +/** Strict codec for committed Account logout-all authority events. */ +public final class AccountLogoutAllAuthorityEventV1Codec { + public static final String SCHEMA_VERSION = "account-auth-logout-all-event/v1"; + public static final String EVENT_TYPE = "LOGOUT_ALL_COMMITTED"; + public static final String EVENT_STREAM_PREFIX = "account:auth-authority:v1:"; + public static final String EVENT_ID_PREFIX = "account-logout-all-event-v1:"; + + private static final Set PREIMAGE_FIELDS = + Set.of( + "schemaVersion", + "eventType", + "eventId", + "requestId", + "accountId", + "sourceScope", + "outboxStreamKey", + "outboxSequence", + "accountAuthorityGeneration", + "sourceVersion", + "accountSecurityCutoff"); + private static final Set WIRE_FIELDS; + private static final Set ACCOUNT_CUTOFF_FIELDS = + Set.of("accountAuthorityGeneration", "outboxStreamKey", "outboxSequence"); + private static final Pattern UUID_PATTERN = + Pattern.compile("[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"); + private static final String NIL_UUID = "00000000-0000-0000-0000-000000000000"; + private static final Pattern POSITIVE_DECIMAL_PATTERN = Pattern.compile("[1-9][0-9]*"); + private static final Pattern DIGEST_PATTERN = Pattern.compile("sha256:[0-9a-f]{64}"); + private static final ObjectMapper JSON = + new ObjectMapper( + JsonFactory.builder().enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION).build()) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS); + + static { + var wireFields = new java.util.HashSet<>(PREIMAGE_FIELDS); + wireFields.add("eventDigest"); + WIRE_FIELDS = Set.copyOf(wireFields); + } + + private AccountLogoutAllAuthorityEventV1Codec() {} + + /** Validates a preimage and returns immutable evidence sealed with its canonical digest. */ + public static AccountLogoutAllAuthorityEvent seal(Map preimage) { + Objects.requireNonNull(preimage, "preimage must not be null"); + JsonNode tree = JSON.valueToTree(preimage); + if (!(tree instanceof ObjectNode object)) { + throw invalid("event", "must be a JSON object"); + } + validatePreimage(object); + String digest = digest(object); + ObjectNode wire = object.deepCopy(); + wire.put("eventDigest", digest); + return toEvidence(wire, digest, canonicalJson(wire)); + } + + /** Validates and verifies one wire event from JSON, rejecting duplicate properties. */ + public static AccountLogoutAllAuthorityEvent verify(String wireJson) { + Objects.requireNonNull(wireJson, "wireJson must not be null"); + final JsonNode tree; + try { + // Canonicalization rejects duplicate JSON object properties before Jackson builds a tree. + Rfc8785CanonicalJson.canonicalizeUtf8(wireJson); + tree = JSON.readTree(wireJson); + } catch (IOException exception) { + throw new IllegalArgumentException("event JSON is malformed", exception); + } + if (!(tree instanceof ObjectNode wire)) { + throw invalid("event", "must be a JSON object"); + } + return verifyWireNode(wire); + } + + private static AccountLogoutAllAuthorityEvent verifyWireNode(ObjectNode wire) { + requireExactFields(wire, WIRE_FIELDS, "event"); + String suppliedDigest = requireText(wire, "eventDigest", "event"); + if (!DIGEST_PATTERN.matcher(suppliedDigest).matches()) { + throw invalid("eventDigest", "must be lowercase sha256: followed by 64 lowercase hex digits"); + } + ObjectNode preimage = wire.deepCopy(); + preimage.remove("eventDigest"); + validatePreimage(preimage); + String expectedDigest = digest(preimage); + if (!MessageDigest.isEqual( + suppliedDigest.getBytes(StandardCharsets.US_ASCII), + expectedDigest.getBytes(StandardCharsets.US_ASCII))) { + throw invalid("eventDigest", "does not match the canonical event preimage"); + } + return toEvidence(wire, suppliedDigest, canonicalJson(wire)); + } + + private static void validatePreimage(ObjectNode event) { + requireExactFields(event, PREIMAGE_FIELDS, "event preimage"); + requireExactText(event, "schemaVersion", SCHEMA_VERSION, "event"); + requireExactText(event, "eventType", EVENT_TYPE, "event"); + + String requestId = requireUuid(event, "requestId", "event"); + requireExactText(event, "eventId", EVENT_ID_PREFIX + requestId, "event"); + String accountId = requireUuid(event, "accountId", "event"); + String sourceScope = "account/" + accountId; + String streamKey = EVENT_STREAM_PREFIX + sourceScope; + requireExactText(event, "sourceScope", sourceScope, "event"); + requireExactText(event, "outboxStreamKey", streamKey, "event"); + + String outboxSequence = requirePositiveDecimal(event, "outboxSequence", "event"); + String accountAuthorityGeneration = + requirePositiveDecimal(event, "accountAuthorityGeneration", "event"); + requirePositiveDecimal(event, "sourceVersion", "event"); + + JsonNode cutoffNode = event.get("accountSecurityCutoff"); + if (!(cutoffNode instanceof ObjectNode cutoff)) { + throw invalid("accountSecurityCutoff", "must be a required JSON object"); + } + requireExactFields(cutoff, ACCOUNT_CUTOFF_FIELDS, "accountSecurityCutoff"); + String cutoffGeneration = + requirePositiveDecimal(cutoff, "accountAuthorityGeneration", "accountSecurityCutoff"); + String cutoffStream = requireText(cutoff, "outboxStreamKey", "accountSecurityCutoff"); + String cutoffSequence = + requirePositiveDecimal(cutoff, "outboxSequence", "accountSecurityCutoff"); + if (!accountAuthorityGeneration.equals(cutoffGeneration)) { + throw invalid( + "accountSecurityCutoff.accountAuthorityGeneration", + "must equal event.accountAuthorityGeneration"); + } + if (!streamKey.equals(cutoffStream)) { + throw invalid("accountSecurityCutoff.outboxStreamKey", "must equal event.outboxStreamKey"); + } + if (!outboxSequence.equals(cutoffSequence)) { + throw invalid("accountSecurityCutoff.outboxSequence", "must equal event.outboxSequence"); + } + } + + private static AccountLogoutAllAuthorityEvent toEvidence( + ObjectNode wire, String digest, String canonicalJson) { + ObjectNode cutoff = (ObjectNode) wire.get("accountSecurityCutoff"); + return new AccountLogoutAllAuthorityEvent( + wire.path("schemaVersion").textValue(), + wire.path("eventType").textValue(), + wire.path("eventId").textValue(), + wire.path("requestId").textValue(), + wire.path("accountId").textValue(), + wire.path("sourceScope").textValue(), + wire.path("outboxStreamKey").textValue(), + wire.path("outboxSequence").textValue(), + wire.path("accountAuthorityGeneration").textValue(), + wire.path("sourceVersion").textValue(), + new AccountSecurityCutoff( + cutoff.path("accountAuthorityGeneration").textValue(), + cutoff.path("outboxStreamKey").textValue(), + cutoff.path("outboxSequence").textValue()), + digest, + canonicalJson); + } + + private static void requireExactFields(ObjectNode object, Set required, String path) { + Set actual = new java.util.HashSet<>(); + object.fieldNames().forEachRemaining(actual::add); + if (!actual.equals(required)) { + Set missing = new java.util.HashSet<>(required); + missing.removeAll(actual); + Set unexpected = new java.util.HashSet<>(actual); + unexpected.removeAll(required); + StringBuilder message = new StringBuilder("must contain exactly the declared fields"); + if (!missing.isEmpty()) { + message.append("; missing ").append(missing); + } + if (!unexpected.isEmpty()) { + message.append("; unexpected ").append(unexpected); + } + throw invalid(path, message.toString()); + } + } + + private static String requireExactText( + ObjectNode object, String field, String expected, String path) { + String value = requireText(object, field, path); + if (!expected.equals(value)) { + throw invalid(path + "." + field, "must equal " + expected); + } + return value; + } + + private static String requireText(ObjectNode object, String field, String path) { + JsonNode value = object.get(field); + if (value == null || !value.isTextual()) { + throw invalid(path + "." + field, "must be a required string"); + } + return value.textValue(); + } + + private static String requireUuid(ObjectNode object, String field, String path) { + String value = requireText(object, field, path); + if (!UUID_PATTERN.matcher(value).matches() || NIL_UUID.equals(value)) { + throw invalid(path + "." + field, "must be a canonical lowercase non-nil UUID"); + } + return value; + } + + private static String requirePositiveDecimal(ObjectNode object, String field, String path) { + String value = requireText(object, field, path); + if (!POSITIVE_DECIMAL_PATTERN.matcher(value).matches()) { + throw invalid(path + "." + field, "must be a positive canonical decimal string"); + } + return value; + } + + private static String digest(ObjectNode preimage) { + try { + byte[] canonical = Rfc8785CanonicalJson.canonicalizeUtf8(preimage.toString()); + byte[] hash = MessageDigest.getInstance("SHA-256").digest(canonical); + return "sha256:" + java.util.HexFormat.of().formatHex(hash); + } catch (IOException exception) { + throw new IllegalArgumentException("event preimage cannot be canonicalized", exception); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + private static String canonicalJson(ObjectNode wire) { + try { + return new String( + Rfc8785CanonicalJson.canonicalizeUtf8(wire.toString()), StandardCharsets.UTF_8); + } catch (IOException exception) { + throw new IllegalArgumentException("event cannot be canonicalized", exception); + } + } + + private static IllegalArgumentException invalid(String path, String message) { + return new IllegalArgumentException(path + " " + message); + } + + /** Immutable verified or producer-sealed logout-all event evidence. */ + public static final class AccountLogoutAllAuthorityEvent { + private final String schemaVersion; + private final String eventType; + private final String eventId; + private final String requestId; + private final String accountId; + private final String sourceScope; + private final String outboxStreamKey; + private final String outboxSequence; + private final String accountAuthorityGeneration; + private final String sourceVersion; + private final AccountSecurityCutoff accountSecurityCutoff; + private final String eventDigest; + private final String canonicalJson; + + private AccountLogoutAllAuthorityEvent( + String schemaVersion, + String eventType, + String eventId, + String requestId, + String accountId, + String sourceScope, + String outboxStreamKey, + String outboxSequence, + String accountAuthorityGeneration, + String sourceVersion, + AccountSecurityCutoff accountSecurityCutoff, + String eventDigest, + String canonicalJson) { + this.schemaVersion = schemaVersion; + this.eventType = eventType; + this.eventId = eventId; + this.requestId = requestId; + this.accountId = accountId; + this.sourceScope = sourceScope; + this.outboxStreamKey = outboxStreamKey; + this.outboxSequence = outboxSequence; + this.accountAuthorityGeneration = accountAuthorityGeneration; + this.sourceVersion = sourceVersion; + this.accountSecurityCutoff = accountSecurityCutoff; + this.eventDigest = eventDigest; + this.canonicalJson = canonicalJson; + } + + public String schemaVersion() { + return schemaVersion; + } + + public String eventType() { + return eventType; + } + + public String eventId() { + return eventId; + } + + public String requestId() { + return requestId; + } + + public String accountId() { + return accountId; + } + + public String sourceScope() { + return sourceScope; + } + + public String outboxStreamKey() { + return outboxStreamKey; + } + + public String outboxSequence() { + return outboxSequence; + } + + public String accountAuthorityGeneration() { + return accountAuthorityGeneration; + } + + public String sourceVersion() { + return sourceVersion; + } + + public AccountSecurityCutoff accountSecurityCutoff() { + return accountSecurityCutoff; + } + + public String eventDigest() { + return eventDigest; + } + + public String canonicalJson() { + return canonicalJson; + } + + /** Returns a caller-owned copy of the canonical complete wire event bytes. */ + public byte[] canonicalJsonUtf8() { + return canonicalJson.getBytes(StandardCharsets.UTF_8); + } + } + + /** Immutable Account security cutoff checkpoint. */ + public record AccountSecurityCutoff( + String accountAuthorityGeneration, String outboxStreamKey, String outboxSequence) {} +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1Codec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1Codec.java new file mode 100644 index 0000000000..c9ebc30d2f --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1Codec.java @@ -0,0 +1,391 @@ +package net.firedevops.firemud.common.account.authority; + +import com.fasterxml.jackson.core.JsonFactory; +import com.fasterxml.jackson.core.StreamReadFeature; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; +import java.util.HexFormat; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; + +/** Closed source evidence for one Account-owned, non-password security-state mutation. */ +public final class AccountSecurityStateAuthorityEventV1Codec { + public static final String SCHEMA_VERSION = "account-auth-account-security-state-event/v1"; + public static final String EVENT_TYPE = "ACCOUNT_SECURITY_STATE_CHANGED"; + public static final String EVENT_ID_PREFIX = "account-security-state-event-v1:"; + public static final String EVENT_STREAM_PREFIX = "account:auth-authority:v1:"; + + private static final Set PREIMAGE_FIELDS = + Set.of( + "schemaVersion", + "eventType", + "eventId", + "requestId", + "accountId", + "sourceScope", + "outboxStreamKey", + "outboxSequence", + "accountAuthorityGeneration", + "sourceVersion", + "accountSecurityCutoff", + "mutationKinds", + "accountState"); + private static final Set WIRE_FIELDS; + private static final Set CUTOFF_FIELDS = + Set.of("accountAuthorityGeneration", "outboxStreamKey", "outboxSequence"); + private static final Set STATE_FIELDS = + Set.of("emailVerified", "loginAuthModes", "globalRoles", "lifecycleState"); + private static final Set MUTATION_KINDS = + Set.of( + "EMAIL_LOGIN_ELIGIBILITY_CHANGED", + "LOGIN_AUTH_MODES_CHANGED", + "GLOBAL_ROLE_CHANGED", + "LIFECYCLE_STATE_CHANGED"); + private static final Set LOGIN_MODES = Set.of("EMAIL_OTP", "PASSWORD"); + private static final Set GLOBAL_ROLES = + Set.of("platformAdmin", "support", "billingAdmin"); + private static final Set LIFECYCLE_STATES = + Set.of("ACTIVE", "SECURITY_LOCKED", "DEACTIVATED_PENDING_DELETE", "DELETED"); + private static final Pattern UUID_PATTERN = + Pattern.compile("[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"); + private static final Pattern POSITIVE_DECIMAL = Pattern.compile("[1-9][0-9]*"); + private static final Pattern DIGEST_PATTERN = Pattern.compile("sha256:[0-9a-f]{64}"); + private static final String NIL_UUID = "00000000-0000-0000-0000-000000000000"; + private static final ObjectMapper JSON = + new ObjectMapper( + JsonFactory.builder().enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION).build()) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS); + + static { + var fields = new java.util.HashSet<>(PREIMAGE_FIELDS); + fields.add("eventDigest"); + WIRE_FIELDS = Set.copyOf(fields); + } + + private AccountSecurityStateAuthorityEventV1Codec() {} + + /** Seals the complete declared preimage; caller authorization and receipt proof are separate. */ + public static AccountSecurityStateAuthorityEvent seal(Map preimage) { + Objects.requireNonNull(preimage, "event preimage is required"); + JsonNode tree = JSON.valueToTree(preimage); + if (!(tree instanceof ObjectNode object)) { + throw invalid("event preimage must be an object"); + } + validatePreimage(object); + String digest = digest(object); + ObjectNode wire = object.deepCopy(); + wire.put("eventDigest", digest); + return evidence(wire, digest); + } + + /** Verifies the closed payload and digest, returning complete immutable canonical evidence. */ + public static AccountSecurityStateAuthorityEvent verify(String wireJson) { + Objects.requireNonNull(wireJson, "event JSON is required"); + final JsonNode tree; + try { + Rfc8785CanonicalJson.canonicalizeUtf8(wireJson); + tree = JSON.readTree(wireJson); + } catch (IOException exception) { + throw new IllegalArgumentException("event JSON is malformed", exception); + } + if (!(tree instanceof ObjectNode wire)) { + throw invalid("event must be an object"); + } + exactFields(wire, WIRE_FIELDS); + String supplied = text(wire, "eventDigest"); + if (!DIGEST_PATTERN.matcher(supplied).matches()) { + throw invalid("eventDigest must be canonical sha256 hexadecimal"); + } + ObjectNode preimage = wire.deepCopy(); + preimage.remove("eventDigest"); + validatePreimage(preimage); + if (!MessageDigest.isEqual( + supplied.getBytes(StandardCharsets.US_ASCII), + digest(preimage).getBytes(StandardCharsets.US_ASCII))) { + throw invalid("eventDigest does not match the complete canonical preimage"); + } + return evidence(wire, supplied); + } + + private static void validatePreimage(ObjectNode event) { + exactFields(event, PREIMAGE_FIELDS); + equalText(event, "schemaVersion", SCHEMA_VERSION); + equalText(event, "eventType", EVENT_TYPE); + String requestId = uuid(event, "requestId"); + equalText(event, "eventId", EVENT_ID_PREFIX + requestId); + String scope = "account/" + uuid(event, "accountId"); + equalText(event, "sourceScope", scope); + equalText(event, "outboxStreamKey", EVENT_STREAM_PREFIX + scope); + positive(event, "outboxSequence"); + positive(event, "accountAuthorityGeneration"); + positive(event, "sourceVersion"); + ObjectNode cutoff = object(event, "accountSecurityCutoff"); + exactFields(cutoff, CUTOFF_FIELDS); + positive(cutoff, "accountAuthorityGeneration"); + positive(cutoff, "outboxSequence"); + for (String field : CUTOFF_FIELDS) { + equalText(cutoff, field, text(event, field)); + } + orderedValues(event.get("mutationKinds"), MUTATION_KINDS, "mutationKinds"); + ObjectNode state = object(event, "accountState"); + exactFields(state, STATE_FIELDS); + if (!state.get("emailVerified").isBoolean()) { + throw invalid("accountState.emailVerified must be a boolean"); + } + orderedValues(state.get("loginAuthModes"), LOGIN_MODES, "accountState.loginAuthModes"); + orderedValues(state.get("globalRoles"), GLOBAL_ROLES, "accountState.globalRoles", true); + if (!LIFECYCLE_STATES.contains(text(state, "lifecycleState"))) { + throw invalid("accountState.lifecycleState is unsupported"); + } + } + + private static List orderedValues(JsonNode array, Set allowed, String field) { + return orderedValues(array, allowed, field, false); + } + + private static List orderedValues( + JsonNode array, Set allowed, String field, boolean allowEmpty) { + if (array == null || !array.isArray() || (!allowEmpty && array.isEmpty())) { + throw invalid(field + " must be a declared array with supported cardinality"); + } + List values = new ArrayList<>(); + String previous = null; + for (JsonNode item : array) { + if (!item.isTextual() || !allowed.contains(item.textValue())) { + throw invalid(field + " contains an unsupported value"); + } + String value = item.textValue(); + if (previous != null && previous.compareTo(value) >= 0) { + throw invalid(field + " must be sorted and unique"); + } + values.add(value); + previous = value; + } + return List.copyOf(values); + } + + private static ObjectNode object(ObjectNode parent, String field) { + if (!(parent.get(field) instanceof ObjectNode value)) { + throw invalid(field + " must be a required object"); + } + return value; + } + + private static void exactFields(ObjectNode object, Set expected) { + Set actual = new java.util.HashSet<>(); + object.fieldNames().forEachRemaining(actual::add); + if (!actual.equals(expected)) { + throw invalid("object must contain exactly the declared fields"); + } + } + + private static String text(ObjectNode object, String field) { + JsonNode value = object.get(field); + if (value == null || !value.isTextual()) { + throw invalid(field + " must be a required string"); + } + return value.textValue(); + } + + private static void equalText(ObjectNode object, String field, String expected) { + if (!expected.equals(text(object, field))) { + throw invalid(field + " does not match its exact binding"); + } + } + + private static String uuid(ObjectNode object, String field) { + String value = text(object, field); + if (!UUID_PATTERN.matcher(value).matches() || NIL_UUID.equals(value)) { + throw invalid(field + " must be a canonical lowercase non-nil UUID"); + } + return value; + } + + private static void positive(ObjectNode object, String field) { + if (!POSITIVE_DECIMAL.matcher(text(object, field)).matches()) { + throw invalid(field + " must be a positive canonical decimal string"); + } + } + + private static String canonicalJson(ObjectNode object) { + try { + return new String( + Rfc8785CanonicalJson.canonicalizeUtf8(object.toString()), StandardCharsets.UTF_8); + } catch (IOException exception) { + throw new IllegalArgumentException("event cannot be canonicalized", exception); + } + } + + private static String digest(ObjectNode object) { + try { + return "sha256:" + + HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256") + .digest(canonicalJson(object).getBytes(StandardCharsets.UTF_8))); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + private static AccountSecurityStateAuthorityEvent evidence(ObjectNode wire, String digest) { + ObjectNode state = object(wire, "accountState"); + ObjectNode cutoff = object(wire, "accountSecurityCutoff"); + return new AccountSecurityStateAuthorityEvent( + text(wire, "eventId"), + text(wire, "requestId"), + text(wire, "accountId"), + text(wire, "outboxStreamKey"), + text(wire, "outboxSequence"), + text(wire, "accountAuthorityGeneration"), + text(wire, "sourceVersion"), + new AccountSecurityCutoff( + text(cutoff, "accountAuthorityGeneration"), + text(cutoff, "outboxStreamKey"), + text(cutoff, "outboxSequence")), + orderedValues(wire.get("mutationKinds"), MUTATION_KINDS, "mutationKinds"), + new AccountState( + state.get("emailVerified").booleanValue(), + orderedValues(state.get("loginAuthModes"), LOGIN_MODES, "loginAuthModes"), + orderedValues(state.get("globalRoles"), GLOBAL_ROLES, "globalRoles", true), + text(state, "lifecycleState")), + digest, + canonicalJson(wire)); + } + + private static IllegalArgumentException invalid(String message) { + return new IllegalArgumentException(message); + } + + public record AccountSecurityCutoff( + String accountAuthorityGeneration, String outboxStreamKey, String outboxSequence) {} + + public record AccountState( + boolean emailVerified, + List loginAuthModes, + List globalRoles, + String lifecycleState) { + public AccountState { + loginAuthModes = List.copyOf(loginAuthModes); + globalRoles = List.copyOf(globalRoles); + } + } + + /** Immutable evidence constructible only by sealing or verifying this exact schema. */ + public static final class AccountSecurityStateAuthorityEvent { + private final String eventId; + private final String requestId; + private final String accountId; + private final String outboxStreamKey; + private final String outboxSequence; + private final String accountAuthorityGeneration; + private final String sourceVersion; + private final AccountSecurityCutoff accountSecurityCutoff; + private final List mutationKinds; + private final AccountState accountState; + private final String eventDigest; + private final String canonicalJson; + + private AccountSecurityStateAuthorityEvent( + String eventId, + String requestId, + String accountId, + String outboxStreamKey, + String outboxSequence, + String accountAuthorityGeneration, + String sourceVersion, + AccountSecurityCutoff accountSecurityCutoff, + List mutationKinds, + AccountState accountState, + String eventDigest, + String canonicalJson) { + this.eventId = eventId; + this.requestId = requestId; + this.accountId = accountId; + this.outboxStreamKey = outboxStreamKey; + this.outboxSequence = outboxSequence; + this.accountAuthorityGeneration = accountAuthorityGeneration; + this.sourceVersion = sourceVersion; + this.accountSecurityCutoff = accountSecurityCutoff; + this.mutationKinds = List.copyOf(mutationKinds); + this.accountState = accountState; + this.eventDigest = eventDigest; + this.canonicalJson = canonicalJson; + } + + public String schemaVersion() { + return SCHEMA_VERSION; + } + + public String eventType() { + return EVENT_TYPE; + } + + public String eventId() { + return eventId; + } + + public String requestId() { + return requestId; + } + + public String accountId() { + return accountId; + } + + public String sourceScope() { + return "account/" + accountId; + } + + public String outboxStreamKey() { + return outboxStreamKey; + } + + public String outboxSequence() { + return outboxSequence; + } + + public String accountAuthorityGeneration() { + return accountAuthorityGeneration; + } + + public String sourceVersion() { + return sourceVersion; + } + + public AccountSecurityCutoff accountSecurityCutoff() { + return accountSecurityCutoff; + } + + public List mutationKinds() { + return mutationKinds; + } + + public AccountState accountState() { + return accountState; + } + + public String eventDigest() { + return eventDigest; + } + + public String canonicalJson() { + return canonicalJson; + } + + public byte[] canonicalJsonUtf8() { + return canonicalJson.getBytes(StandardCharsets.UTF_8); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/IssuerGenerationAuthorityEventV1Codec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/IssuerGenerationAuthorityEventV1Codec.java new file mode 100644 index 0000000000..257c34bef4 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/IssuerGenerationAuthorityEventV1Codec.java @@ -0,0 +1,327 @@ +package net.firedevops.firemud.common.account.authority; + +import com.fasterxml.jackson.core.JsonFactory; +import com.fasterxml.jackson.core.StreamReadFeature; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; + +/** Strict codec for committed Account issuer-generation authority events. */ +public final class IssuerGenerationAuthorityEventV1Codec { + public static final String SCHEMA_VERSION = "account-auth-issuer-generation-event/v1"; + public static final String EVENT_TYPE = "ISSUER_GENERATION_ADVANCED"; + public static final String EVENT_STREAM_PREFIX = "account:auth-authority:v1:"; + + private static final Set PREIMAGE_FIELDS = + Set.of( + "schemaVersion", + "eventType", + "eventId", + "requestId", + "issuerId", + "sourceScope", + "outboxStreamKey", + "outboxSequence", + "issuerAuthGeneration", + "sourceVersion"); + private static final Set WIRE_FIELDS; + private static final Pattern POSITIVE_DECIMAL_PATTERN = Pattern.compile("[1-9][0-9]*"); + private static final Pattern DIGEST_PATTERN = Pattern.compile("sha256:[0-9a-f]{64}"); + private static final ObjectMapper JSON = + new ObjectMapper( + JsonFactory.builder().enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION).build()) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS); + + static { + var wireFields = new java.util.HashSet<>(PREIMAGE_FIELDS); + wireFields.add("eventDigest"); + WIRE_FIELDS = Set.copyOf(wireFields); + } + + private IssuerGenerationAuthorityEventV1Codec() {} + + /** Validates a preimage and returns immutable evidence sealed with its canonical digest. */ + public static IssuerGenerationAuthorityEvent seal(Map preimage) { + Objects.requireNonNull(preimage, "preimage must not be null"); + JsonNode tree = JSON.valueToTree(preimage); + if (!(tree instanceof ObjectNode object)) { + throw invalid("event", "must be a JSON object"); + } + validatePreimage(object); + String digest = digest(object); + ObjectNode wire = object.deepCopy(); + wire.put("eventDigest", digest); + return toEvidence(wire, digest, canonicalJson(wire)); + } + + /** Validates and verifies one wire event from JSON, rejecting duplicate properties. */ + public static IssuerGenerationAuthorityEvent verify(String wireJson) { + Objects.requireNonNull(wireJson, "wireJson must not be null"); + final JsonNode tree; + try { + // JCS parsing rejects duplicate JSON object properties before Jackson builds a tree. + Rfc8785CanonicalJson.canonicalizeUtf8(wireJson); + tree = JSON.readTree(wireJson); + } catch (IOException exception) { + throw new IllegalArgumentException("event JSON is malformed", exception); + } + if (!(tree instanceof ObjectNode wire)) { + throw invalid("event", "must be a JSON object"); + } + return verifyWireNode(wire); + } + + /** Validates and verifies one wire event supplied as JSON-compatible map data. */ + public static IssuerGenerationAuthorityEvent verify(Map wireEvent) { + Objects.requireNonNull(wireEvent, "wireEvent must not be null"); + JsonNode tree = JSON.valueToTree(wireEvent); + if (!(tree instanceof ObjectNode wire)) { + throw invalid("event", "must be a JSON object"); + } + return verifyWireNode(wire); + } + + private static IssuerGenerationAuthorityEvent verifyWireNode(ObjectNode wire) { + requireExactFields(wire, WIRE_FIELDS, "event"); + String suppliedDigest = requireText(wire, "eventDigest", "event"); + if (!DIGEST_PATTERN.matcher(suppliedDigest).matches()) { + throw invalid("eventDigest", "must be lowercase sha256: followed by 64 lowercase hex digits"); + } + ObjectNode preimage = wire.deepCopy(); + preimage.remove("eventDigest"); + validatePreimage(preimage); + String expectedDigest = digest(preimage); + if (!MessageDigest.isEqual( + suppliedDigest.getBytes(StandardCharsets.US_ASCII), + expectedDigest.getBytes(StandardCharsets.US_ASCII))) { + throw invalid("eventDigest", "does not match the canonical event preimage"); + } + return toEvidence(wire, suppliedDigest, canonicalJson(wire)); + } + + private static void validatePreimage(ObjectNode event) { + requireExactFields(event, PREIMAGE_FIELDS, "event preimage"); + requireExactText(event, "schemaVersion", SCHEMA_VERSION, "event"); + requireExactText(event, "eventType", EVENT_TYPE, "event"); + requireNonEmptyText(event, "eventId", "event"); + requireNonEmptyText(event, "requestId", "event"); + + String issuerId = requireNonBlankText(event, "issuerId", "event"); + String sourceScope = "issuer/" + issuerId; + String streamKey = EVENT_STREAM_PREFIX + sourceScope; + requireExactText(event, "sourceScope", sourceScope, "event"); + requireExactText(event, "outboxStreamKey", streamKey, "event"); + + requirePositiveDecimal(event, "outboxSequence", "event"); + requirePositiveDecimal(event, "issuerAuthGeneration", "event"); + requirePositiveDecimal(event, "sourceVersion", "event"); + } + + private static IssuerGenerationAuthorityEvent toEvidence( + ObjectNode wire, String digest, String canonicalJson) { + return new IssuerGenerationAuthorityEvent( + wire.path("schemaVersion").textValue(), + wire.path("eventType").textValue(), + wire.path("eventId").textValue(), + wire.path("requestId").textValue(), + wire.path("issuerId").textValue(), + wire.path("sourceScope").textValue(), + wire.path("outboxStreamKey").textValue(), + wire.path("outboxSequence").textValue(), + wire.path("issuerAuthGeneration").textValue(), + wire.path("sourceVersion").textValue(), + digest, + canonicalJson); + } + + private static void requireExactFields(ObjectNode object, Set required, String path) { + Set actual = new java.util.HashSet<>(); + object.fieldNames().forEachRemaining(actual::add); + if (!actual.equals(required)) { + Set missing = new java.util.HashSet<>(required); + missing.removeAll(actual); + Set unexpected = new java.util.HashSet<>(actual); + unexpected.removeAll(required); + StringBuilder message = new StringBuilder("must contain exactly the declared fields"); + if (!missing.isEmpty()) { + message.append("; missing ").append(missing); + } + if (!unexpected.isEmpty()) { + message.append("; unexpected ").append(unexpected); + } + throw invalid(path, message.toString()); + } + } + + private static String requireExactText( + ObjectNode object, String field, String expected, String path) { + String value = requireText(object, field, path); + if (!expected.equals(value)) { + throw invalid(path + "." + field, "must equal " + expected); + } + return value; + } + + private static String requireNonEmptyText(ObjectNode object, String field, String path) { + String value = requireText(object, field, path); + if (value.isEmpty()) { + throw invalid(path + "." + field, "must be nonempty"); + } + return value; + } + + private static String requireNonBlankText(ObjectNode object, String field, String path) { + String value = requireText(object, field, path); + if (value.isBlank()) { + throw invalid(path + "." + field, "must be nonblank"); + } + return value; + } + + private static String requireText(ObjectNode object, String field, String path) { + JsonNode value = object.get(field); + if (value == null || !value.isTextual()) { + throw invalid(path + "." + field, "must be a required string"); + } + return value.textValue(); + } + + private static String requirePositiveDecimal(ObjectNode object, String field, String path) { + String value = requireText(object, field, path); + if (!POSITIVE_DECIMAL_PATTERN.matcher(value).matches()) { + throw invalid(path + "." + field, "must be a positive canonical decimal string"); + } + return value; + } + + private static String digest(ObjectNode preimage) { + try { + byte[] canonical = Rfc8785CanonicalJson.canonicalizeUtf8(preimage.toString()); + byte[] hash = MessageDigest.getInstance("SHA-256").digest(canonical); + return "sha256:" + java.util.HexFormat.of().formatHex(hash); + } catch (IOException exception) { + throw new IllegalArgumentException("event preimage cannot be canonicalized", exception); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + private static String canonicalJson(ObjectNode wire) { + try { + return new String( + Rfc8785CanonicalJson.canonicalizeUtf8(wire.toString()), StandardCharsets.UTF_8); + } catch (IOException exception) { + throw new IllegalArgumentException("event cannot be canonicalized", exception); + } + } + + private static IllegalArgumentException invalid(String path, String message) { + return new IllegalArgumentException(path + " " + message); + } + + /** Immutable verified or producer-sealed issuer-generation event evidence. */ + public static final class IssuerGenerationAuthorityEvent { + private final String schemaVersion; + private final String eventType; + private final String eventId; + private final String requestId; + private final String issuerId; + private final String sourceScope; + private final String outboxStreamKey; + private final String outboxSequence; + private final String issuerAuthGeneration; + private final String sourceVersion; + private final String eventDigest; + private final String canonicalJson; + + private IssuerGenerationAuthorityEvent( + String schemaVersion, + String eventType, + String eventId, + String requestId, + String issuerId, + String sourceScope, + String outboxStreamKey, + String outboxSequence, + String issuerAuthGeneration, + String sourceVersion, + String eventDigest, + String canonicalJson) { + this.schemaVersion = schemaVersion; + this.eventType = eventType; + this.eventId = eventId; + this.requestId = requestId; + this.issuerId = issuerId; + this.sourceScope = sourceScope; + this.outboxStreamKey = outboxStreamKey; + this.outboxSequence = outboxSequence; + this.issuerAuthGeneration = issuerAuthGeneration; + this.sourceVersion = sourceVersion; + this.eventDigest = eventDigest; + this.canonicalJson = canonicalJson; + } + + public String schemaVersion() { + return schemaVersion; + } + + public String eventType() { + return eventType; + } + + public String eventId() { + return eventId; + } + + public String requestId() { + return requestId; + } + + public String issuerId() { + return issuerId; + } + + public String sourceScope() { + return sourceScope; + } + + public String outboxStreamKey() { + return outboxStreamKey; + } + + public String outboxSequence() { + return outboxSequence; + } + + public String issuerAuthGeneration() { + return issuerAuthGeneration; + } + + public String sourceVersion() { + return sourceVersion; + } + + public String eventDigest() { + return eventDigest; + } + + public String canonicalJson() { + return canonicalJson; + } + + /** Returns a caller-owned copy of the canonical complete wire event bytes. */ + public byte[] canonicalJsonUtf8() { + return canonicalJson.getBytes(StandardCharsets.UTF_8); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/PasswordResetAuthorityEventV1Codec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/PasswordResetAuthorityEventV1Codec.java new file mode 100644 index 0000000000..f2068dcc0f --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/PasswordResetAuthorityEventV1Codec.java @@ -0,0 +1,372 @@ +package net.firedevops.firemud.common.account.authority; + +import com.fasterxml.jackson.core.JsonFactory; +import com.fasterxml.jackson.core.StreamReadFeature; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; + +/** Strict codec for committed Account password-reset authority events. */ +public final class PasswordResetAuthorityEventV1Codec { + public static final String SCHEMA_VERSION = "account-auth-password-reset-event/v1"; + public static final String EVENT_TYPE = "PASSWORD_RESET_COMMITTED"; + public static final String EVENT_STREAM_PREFIX = "account:auth-authority:v1:"; + + private static final Set PREIMAGE_FIELDS = + Set.of( + "schemaVersion", + "eventType", + "eventId", + "requestId", + "accountId", + "sourceScope", + "outboxStreamKey", + "outboxSequence", + "accountAuthorityGeneration", + "sourceVersion", + "accountSecurityCutoff"); + private static final Set WIRE_FIELDS; + private static final Set ACCOUNT_CUTOFF_FIELDS = + Set.of("accountAuthorityGeneration", "outboxStreamKey", "outboxSequence"); + private static final Pattern UUID_PATTERN = + Pattern.compile("[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"); + private static final String NIL_UUID = "00000000-0000-0000-0000-000000000000"; + private static final Pattern POSITIVE_DECIMAL_PATTERN = Pattern.compile("[1-9][0-9]*"); + private static final Pattern DIGEST_PATTERN = Pattern.compile("sha256:[0-9a-f]{64}"); + private static final ObjectMapper JSON = + new ObjectMapper( + JsonFactory.builder().enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION).build()) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS); + + static { + var wireFields = new java.util.HashSet<>(PREIMAGE_FIELDS); + wireFields.add("eventDigest"); + WIRE_FIELDS = Set.copyOf(wireFields); + } + + private PasswordResetAuthorityEventV1Codec() {} + + /** Validates a preimage and returns immutable evidence sealed with its canonical digest. */ + public static PasswordResetAuthorityEvent seal(Map preimage) { + Objects.requireNonNull(preimage, "preimage must not be null"); + JsonNode tree = JSON.valueToTree(preimage); + if (!(tree instanceof ObjectNode object)) { + throw invalid("event", "must be a JSON object"); + } + validatePreimage(object); + String digest = digest(object); + ObjectNode wire = object.deepCopy(); + wire.put("eventDigest", digest); + return toEvidence(wire, digest, canonicalJson(wire)); + } + + /** Validates and verifies one wire event from JSON, rejecting duplicate properties. */ + public static PasswordResetAuthorityEvent verify(String wireJson) { + Objects.requireNonNull(wireJson, "wireJson must not be null"); + final JsonNode tree; + try { + // JCS parsing rejects duplicate JSON object properties before Jackson builds a tree. + Rfc8785CanonicalJson.canonicalizeUtf8(wireJson); + tree = JSON.readTree(wireJson); + } catch (IOException exception) { + throw new IllegalArgumentException("event JSON is malformed", exception); + } + if (!(tree instanceof ObjectNode wire)) { + throw invalid("event", "must be a JSON object"); + } + return verifyWireNode(wire); + } + + /** Validates and verifies one wire event supplied as JSON-compatible map data. */ + public static PasswordResetAuthorityEvent verify(Map wireEvent) { + Objects.requireNonNull(wireEvent, "wireEvent must not be null"); + JsonNode tree = JSON.valueToTree(wireEvent); + if (!(tree instanceof ObjectNode wire)) { + throw invalid("event", "must be a JSON object"); + } + return verifyWireNode(wire); + } + + private static PasswordResetAuthorityEvent verifyWireNode(ObjectNode wire) { + requireExactFields(wire, WIRE_FIELDS, "event"); + String suppliedDigest = requireText(wire, "eventDigest", "event"); + if (!DIGEST_PATTERN.matcher(suppliedDigest).matches()) { + throw invalid("eventDigest", "must be lowercase sha256: followed by 64 lowercase hex digits"); + } + ObjectNode preimage = wire.deepCopy(); + preimage.remove("eventDigest"); + validatePreimage(preimage); + String expectedDigest = digest(preimage); + if (!MessageDigest.isEqual( + suppliedDigest.getBytes(StandardCharsets.US_ASCII), + expectedDigest.getBytes(StandardCharsets.US_ASCII))) { + throw invalid("eventDigest", "does not match the canonical event preimage"); + } + return toEvidence(wire, suppliedDigest, canonicalJson(wire)); + } + + private static void validatePreimage(ObjectNode event) { + requireExactFields(event, PREIMAGE_FIELDS, "event preimage"); + requireExactText(event, "schemaVersion", SCHEMA_VERSION, "event"); + requireExactText(event, "eventType", EVENT_TYPE, "event"); + requireNonEmptyText(event, "eventId", "event"); + requireNonEmptyText(event, "requestId", "event"); + + String accountId = requireUuid(event, "accountId", "event"); + String sourceScope = "account/" + accountId; + String streamKey = EVENT_STREAM_PREFIX + sourceScope; + requireExactText(event, "sourceScope", sourceScope, "event"); + requireExactText(event, "outboxStreamKey", streamKey, "event"); + + String outboxSequence = requirePositiveDecimal(event, "outboxSequence", "event"); + String accountAuthorityGeneration = + requirePositiveDecimal(event, "accountAuthorityGeneration", "event"); + requirePositiveDecimal(event, "sourceVersion", "event"); + + JsonNode cutoffNode = event.get("accountSecurityCutoff"); + if (!(cutoffNode instanceof ObjectNode cutoff)) { + throw invalid("accountSecurityCutoff", "must be a required JSON object"); + } + requireExactFields(cutoff, ACCOUNT_CUTOFF_FIELDS, "accountSecurityCutoff"); + String cutoffGeneration = + requirePositiveDecimal(cutoff, "accountAuthorityGeneration", "accountSecurityCutoff"); + String cutoffStream = requireText(cutoff, "outboxStreamKey", "accountSecurityCutoff"); + String cutoffSequence = + requirePositiveDecimal(cutoff, "outboxSequence", "accountSecurityCutoff"); + if (!accountAuthorityGeneration.equals(cutoffGeneration)) { + throw invalid( + "accountSecurityCutoff.accountAuthorityGeneration", + "must equal event.accountAuthorityGeneration"); + } + if (!streamKey.equals(cutoffStream)) { + throw invalid("accountSecurityCutoff.outboxStreamKey", "must equal event.outboxStreamKey"); + } + if (!outboxSequence.equals(cutoffSequence)) { + throw invalid("accountSecurityCutoff.outboxSequence", "must equal event.outboxSequence"); + } + } + + private static PasswordResetAuthorityEvent toEvidence( + ObjectNode wire, String digest, String canonicalJson) { + ObjectNode cutoff = (ObjectNode) wire.get("accountSecurityCutoff"); + return new PasswordResetAuthorityEvent( + wire.path("schemaVersion").textValue(), + wire.path("eventType").textValue(), + wire.path("eventId").textValue(), + wire.path("requestId").textValue(), + wire.path("accountId").textValue(), + wire.path("sourceScope").textValue(), + wire.path("outboxStreamKey").textValue(), + wire.path("outboxSequence").textValue(), + wire.path("accountAuthorityGeneration").textValue(), + wire.path("sourceVersion").textValue(), + new AccountSecurityCutoff( + cutoff.path("accountAuthorityGeneration").textValue(), + cutoff.path("outboxStreamKey").textValue(), + cutoff.path("outboxSequence").textValue()), + digest, + canonicalJson); + } + + private static void requireExactFields(ObjectNode object, Set required, String path) { + Set actual = new java.util.HashSet<>(); + object.fieldNames().forEachRemaining(actual::add); + if (!actual.equals(required)) { + Set missing = new java.util.HashSet<>(required); + missing.removeAll(actual); + Set unexpected = new java.util.HashSet<>(actual); + unexpected.removeAll(required); + StringBuilder message = new StringBuilder("must contain exactly the declared fields"); + if (!missing.isEmpty()) { + message.append("; missing ").append(missing); + } + if (!unexpected.isEmpty()) { + message.append("; unexpected ").append(unexpected); + } + throw invalid(path, message.toString()); + } + } + + private static String requireExactText( + ObjectNode object, String field, String expected, String path) { + String value = requireText(object, field, path); + if (!expected.equals(value)) { + throw invalid(path + "." + field, "must equal " + expected); + } + return value; + } + + private static String requireNonEmptyText(ObjectNode object, String field, String path) { + String value = requireText(object, field, path); + if (value.isEmpty()) { + throw invalid(path + "." + field, "must be nonempty"); + } + return value; + } + + private static String requireText(ObjectNode object, String field, String path) { + JsonNode value = object.get(field); + if (value == null || !value.isTextual()) { + throw invalid(path + "." + field, "must be a required string"); + } + return value.textValue(); + } + + private static String requireUuid(ObjectNode object, String field, String path) { + String value = requireText(object, field, path); + if (!UUID_PATTERN.matcher(value).matches() || NIL_UUID.equals(value)) { + throw invalid(path + "." + field, "must be a canonical lowercase non-nil UUID"); + } + return value; + } + + private static String requirePositiveDecimal(ObjectNode object, String field, String path) { + String value = requireText(object, field, path); + if (!POSITIVE_DECIMAL_PATTERN.matcher(value).matches()) { + throw invalid(path + "." + field, "must be a positive canonical decimal string"); + } + return value; + } + + private static String digest(ObjectNode preimage) { + try { + byte[] canonical = Rfc8785CanonicalJson.canonicalizeUtf8(preimage.toString()); + byte[] hash = MessageDigest.getInstance("SHA-256").digest(canonical); + return "sha256:" + java.util.HexFormat.of().formatHex(hash); + } catch (IOException exception) { + throw new IllegalArgumentException("event preimage cannot be canonicalized", exception); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + private static String canonicalJson(ObjectNode wire) { + try { + return new String( + Rfc8785CanonicalJson.canonicalizeUtf8(wire.toString()), StandardCharsets.UTF_8); + } catch (IOException exception) { + throw new IllegalArgumentException("event cannot be canonicalized", exception); + } + } + + private static IllegalArgumentException invalid(String path, String message) { + return new IllegalArgumentException(path + " " + message); + } + + /** Immutable verified or producer-sealed event evidence. */ + public static final class PasswordResetAuthorityEvent { + private final String schemaVersion; + private final String eventType; + private final String eventId; + private final String requestId; + private final String accountId; + private final String sourceScope; + private final String outboxStreamKey; + private final String outboxSequence; + private final String accountAuthorityGeneration; + private final String sourceVersion; + private final AccountSecurityCutoff accountSecurityCutoff; + private final String eventDigest; + private final String canonicalJson; + + private PasswordResetAuthorityEvent( + String schemaVersion, + String eventType, + String eventId, + String requestId, + String accountId, + String sourceScope, + String outboxStreamKey, + String outboxSequence, + String accountAuthorityGeneration, + String sourceVersion, + AccountSecurityCutoff accountSecurityCutoff, + String eventDigest, + String canonicalJson) { + this.schemaVersion = schemaVersion; + this.eventType = eventType; + this.eventId = eventId; + this.requestId = requestId; + this.accountId = accountId; + this.sourceScope = sourceScope; + this.outboxStreamKey = outboxStreamKey; + this.outboxSequence = outboxSequence; + this.accountAuthorityGeneration = accountAuthorityGeneration; + this.sourceVersion = sourceVersion; + this.accountSecurityCutoff = accountSecurityCutoff; + this.eventDigest = eventDigest; + this.canonicalJson = canonicalJson; + } + + public String schemaVersion() { + return schemaVersion; + } + + public String eventType() { + return eventType; + } + + public String eventId() { + return eventId; + } + + public String requestId() { + return requestId; + } + + public String accountId() { + return accountId; + } + + public String sourceScope() { + return sourceScope; + } + + public String outboxStreamKey() { + return outboxStreamKey; + } + + public String outboxSequence() { + return outboxSequence; + } + + public String accountAuthorityGeneration() { + return accountAuthorityGeneration; + } + + public String sourceVersion() { + return sourceVersion; + } + + public AccountSecurityCutoff accountSecurityCutoff() { + return accountSecurityCutoff; + } + + public String eventDigest() { + return eventDigest; + } + + public String canonicalJson() { + return canonicalJson; + } + + /** Returns a caller-owned copy of the canonical complete wire event bytes. */ + public byte[] canonicalJsonUtf8() { + return canonicalJson.getBytes(StandardCharsets.UTF_8); + } + } + + /** Immutable Account security cutoff checkpoint. */ + public record AccountSecurityCutoff( + String accountAuthorityGeneration, String outboxStreamKey, String outboxSequence) {} +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/DraftCommitBinding.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/DraftCommitBinding.java new file mode 100644 index 0000000000..e8ee145a51 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/DraftCommitBinding.java @@ -0,0 +1,454 @@ +package net.firedevops.firemud.common.authoring; + +import java.io.IOException; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Comparator; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.ObjectMapper; + +/** + * Complete immutable Game Design binding for one coordinated Draft commit. + * + *

This type retains a declared mutation and its affected tuple set exactly. Its owner labels and + * opaque payloads are not proof that the declaration is semantically complete; each typed owner + * producer must derive and verify its required tuple subset before any owner action. + */ +public final class DraftCommitBinding { + private static final ObjectMapper JSON = new ObjectMapper(); + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final Comparator AFFECTED_ORDER = + Comparator.comparing(AffectedUnit::owner) + .thenComparing(AffectedUnit::aggregateType) + .thenComparing(AffectedUnit::aggregateId) + .thenComparing(AffectedUnit::scopeType) + .thenComparing(AffectedUnit::scopeId); + + /** Owners participating in the canonical multi-owner Draft commit contract. */ + public enum Owner { + WORLD_MANAGEMENT, + ENTITY_MANAGEMENT, + GAME_LOGIC, + AUTOMATION_SCRIPTING, + GAME_DESIGN_CONTROL_PLANE + } + + /** Canonical identity plus the exact private Game Design Version/source lineage. */ + public record TargetProof( + UUID canonicalTenantId, + UUID canonicalVersionId, + long gameDesignVersionRowId, + String gameDesignVersionTenantKey, + long sourceGameRowId, + String sourceGameTenantKey, + String sourceProvenanceKind) { + public TargetProof { + requireNonNil(canonicalTenantId, "canonicalTenantId"); + requireNonNil(canonicalVersionId, "canonicalVersionId"); + if (gameDesignVersionRowId <= 0 || sourceGameRowId <= 0) { + throw new IllegalArgumentException("Game Design source row identities must be positive"); + } + requireBoundedText(gameDesignVersionTenantKey, 36, "gameDesignVersionTenantKey"); + requireBoundedText(sourceGameTenantKey, 36, "sourceGameTenantKey"); + if (!gameDesignVersionTenantKey.equals(sourceGameTenantKey)) { + throw new IllegalArgumentException( + "Version and source Game Design tenant keys must match exactly"); + } + if (!"NEW_GAME_ROW".equals(sourceProvenanceKind) + && !"RETAINED_GAME_V30".equals(sourceProvenanceKind)) { + throw new IllegalArgumentException("Unsupported canonical Version source provenance"); + } + } + } + + /** One full owner-typed revision payload. The payload is opaque and is never normalized here. */ + public record RevisionPayload( + String revisionOrder, UUID revisionId, Owner owner, String payload) { + public RevisionPayload { + Objects.requireNonNull(revisionOrder, "revisionOrder"); + requireNonNil(revisionId, "revisionId"); + Objects.requireNonNull(owner, "owner"); + Objects.requireNonNull(payload, "payload"); + } + } + + /** The expected epoch for one owner-local aggregate and scope fence. */ + public record AffectedUnit( + Owner owner, + String aggregateType, + String aggregateId, + String scopeType, + String scopeId, + String expectedEpoch) { + public AffectedUnit { + Objects.requireNonNull(owner, "owner"); + requireBoundedText(aggregateType, 128, "aggregateType"); + requireBoundedText(aggregateId, 256, "aggregateId"); + requireBoundedText(scopeType, 128, "scopeType"); + requireBoundedText(scopeId, 256, "scopeId"); + requireCanonicalCounter(expectedEpoch, "expectedEpoch"); + } + } + + private final TargetProof target; + private final UUID requestId; + private final UUID commitId; + private final String baseCommitId; + private final List revisions; + private final List affectedUnits; + private final List requiredOwners; + private final String canonicalJson; + private final byte[] canonicalBytes; + private final String digest; + + private DraftCommitBinding( + TargetProof target, + UUID requestId, + UUID commitId, + String baseCommitId, + List revisions, + List affectedUnits) { + this.target = Objects.requireNonNull(target, "target"); + requireNonNil(requestId, "requestId"); + requireNonNil(commitId, "commitId"); + requireBoundedText(baseCommitId, 256, "baseCommitId"); + this.requestId = requestId; + this.commitId = commitId; + this.baseCommitId = baseCommitId; + this.revisions = validateRevisions(revisions); + this.affectedUnits = validateAffectedUnits(affectedUnits); + this.requiredOwners = validateOwnerCoverage(this.revisions, this.affectedUnits); + try { + canonicalBytes = Rfc8785CanonicalJson.canonicalizeUtf8(serialize(toJsonObject())); + canonicalJson = new String(canonicalBytes, StandardCharsets.UTF_8); + digest = sha256(canonicalBytes); + } catch (IOException exception) { + throw new IllegalArgumentException( + "Draft commit binding could not be canonicalized", exception); + } + } + + public static DraftCommitBinding create( + TargetProof target, + UUID requestId, + UUID commitId, + String baseCommitId, + List revisions, + List affectedUnits) { + return new DraftCommitBinding( + target, requestId, commitId, baseCommitId, revisions, affectedUnits); + } + + /** Reconstructs an immutable binding from owner storage and rejects noncanonical/corrupt rows. */ + public static DraftCommitBinding fromStored(String storedJson, String storedDigest) { + Objects.requireNonNull(storedJson, "storedJson"); + Objects.requireNonNull(storedDigest, "storedDigest"); + try { + JsonNode root = JSON.readTree(storedJson); + JsonNode targetNode = requireObject(root, "target"); + TargetProof target = + new TargetProof( + UUID.fromString(requiredText(root, "canonicalTenantId")), + UUID.fromString(requiredText(root, "canonicalVersionId")), + positiveLong(targetNode, "gameDesignVersionRowId"), + requiredText(targetNode, "gameDesignVersionTenantKey"), + positiveLong(targetNode, "sourceGameRowId"), + requiredText(targetNode, "sourceGameTenantKey"), + requiredText(targetNode, "sourceProvenanceKind")); + List revisions = new ArrayList<>(); + for (JsonNode node : requiredArray(root, "revisions")) { + revisions.add( + new RevisionPayload( + requiredText(node, "revisionOrder"), + UUID.fromString(requiredText(node, "revisionId")), + Owner.valueOf(requiredText(node, "owner")), + requiredText(node, "payload"))); + } + List affectedUnits = new ArrayList<>(); + for (JsonNode node : requiredArray(root, "affectedUnits")) { + affectedUnits.add( + new AffectedUnit( + Owner.valueOf(requiredText(node, "owner")), + requiredText(node, "aggregateType"), + requiredText(node, "aggregateId"), + requiredText(node, "scopeType"), + requiredText(node, "scopeId"), + requiredText(node, "expectedEpoch"))); + } + DraftCommitBinding binding = + create( + target, + UUID.fromString(requiredText(root, "requestId")), + UUID.fromString(requiredText(root, "commitId")), + requiredText(root, "baseCommitId"), + revisions, + affectedUnits); + if (!binding.canonicalJson.equals(storedJson) + || !binding.digest.equals(storedDigest) + || !Arrays.equals(binding.canonicalBytes, storedJson.getBytes(StandardCharsets.UTF_8))) { + throw new IllegalArgumentException( + "Stored Draft commit binding is not exact canonical JSON"); + } + return binding; + } catch (RuntimeException exception) { + throw new IllegalStateException("Stored Draft commit binding is corrupt", exception); + } + } + + public TargetProof target() { + return target; + } + + public UUID requestId() { + return requestId; + } + + public UUID commitId() { + return commitId; + } + + public String baseCommitId() { + return baseCommitId; + } + + public List revisions() { + return List.copyOf(revisions); + } + + public List affectedUnits() { + return List.copyOf(affectedUnits); + } + + public List requiredOwners() { + return List.copyOf(requiredOwners); + } + + /** The canonical UTF-8 representation, retained as text for exact database equality. */ + public String canonicalJson() { + return canonicalJson; + } + + /** Returns a defensive copy of the exact RFC 8785 bytes stored with this binding. */ + public byte[] canonicalBytes() { + return canonicalBytes.clone(); + } + + public String digest() { + return digest; + } + + public List affectedUnits(Owner owner) { + return affectedUnits.stream().filter(unit -> unit.owner() == owner).toList(); + } + + @Override + public boolean equals(Object other) { + return this == other + || (other instanceof DraftCommitBinding binding + && digest.equals(binding.digest) + && Arrays.equals(canonicalBytes, binding.canonicalBytes)); + } + + @Override + public int hashCode() { + return 31 * digest.hashCode() + Arrays.hashCode(canonicalBytes); + } + + private Map toJsonObject() { + Map object = new LinkedHashMap<>(); + object.put("schemaVersion", "1"); + object.put("canonicalTenantId", target.canonicalTenantId().toString()); + object.put("canonicalVersionId", target.canonicalVersionId().toString()); + Map targetObject = new LinkedHashMap<>(); + targetObject.put("gameDesignVersionRowId", Long.toString(target.gameDesignVersionRowId())); + targetObject.put("gameDesignVersionTenantKey", target.gameDesignVersionTenantKey()); + targetObject.put("sourceGameRowId", Long.toString(target.sourceGameRowId())); + targetObject.put("sourceGameTenantKey", target.sourceGameTenantKey()); + targetObject.put("sourceProvenanceKind", target.sourceProvenanceKind()); + object.put("target", targetObject); + object.put("requestId", requestId.toString()); + object.put("commitId", commitId.toString()); + object.put("baseCommitId", baseCommitId); + object.put("revisions", revisions.stream().map(DraftCommitBinding::revisionJson).toList()); + object.put( + "affectedUnits", affectedUnits.stream().map(DraftCommitBinding::affectedUnitJson).toList()); + object.put("requiredOwners", requiredOwners.stream().map(Enum::name).toList()); + return object; + } + + private static Map revisionJson(RevisionPayload revision) { + Map object = new LinkedHashMap<>(); + object.put("revisionOrder", revision.revisionOrder()); + object.put("revisionId", revision.revisionId().toString()); + object.put("owner", revision.owner().name()); + object.put("payload", revision.payload()); + return object; + } + + private static Map affectedUnitJson(AffectedUnit unit) { + Map object = new LinkedHashMap<>(); + object.put("owner", unit.owner().name()); + object.put("aggregateType", unit.aggregateType()); + object.put("aggregateId", unit.aggregateId()); + object.put("scopeType", unit.scopeType()); + object.put("scopeId", unit.scopeId()); + object.put("expectedEpoch", unit.expectedEpoch()); + return object; + } + + private static List validateRevisions(List requested) { + Objects.requireNonNull(requested, "revisions"); + if (requested.isEmpty()) { + throw new IllegalArgumentException("Draft commit must contain at least one full revision"); + } + List copy = List.copyOf(requested); + Set revisionIds = new HashSet<>(); + for (int index = 0; index < copy.size(); index++) { + RevisionPayload revision = Objects.requireNonNull(copy.get(index), "revision"); + if (!Integer.toString(index).equals(revision.revisionOrder())) { + throw new IllegalArgumentException( + "Revision order must be the contiguous canonical array order"); + } + if (!revisionIds.add(revision.revisionId())) { + throw new IllegalArgumentException("Draft commit contains a duplicate revision identity"); + } + if (revision.payload().isEmpty()) { + throw new IllegalArgumentException("A full revision payload must not be omitted"); + } + } + return copy; + } + + private static List validateAffectedUnits(List requested) { + Objects.requireNonNull(requested, "affectedUnits"); + if (requested.isEmpty()) { + throw new IllegalArgumentException("Draft commit must declare its complete affected units"); + } + List copy = new ArrayList<>(requested.size()); + Set identities = new HashSet<>(); + for (AffectedUnit unit : requested) { + Objects.requireNonNull(unit, "affectedUnit"); + String identity = + unit.owner() + + "\u0000" + + unit.aggregateType() + + "\u0000" + + unit.aggregateId() + + "\u0000" + + unit.scopeType() + + "\u0000" + + unit.scopeId(); + if (!identities.add(identity)) { + throw new IllegalArgumentException( + "Draft commit contains a duplicate affected owner scope"); + } + copy.add(unit); + } + copy.sort(AFFECTED_ORDER); + return List.copyOf(copy); + } + + private static List validateOwnerCoverage( + List revisions, List affectedUnits) { + Set revisionOwners = new HashSet<>(); + revisions.forEach(revision -> revisionOwners.add(revision.owner())); + Set affectedOwners = new HashSet<>(); + affectedUnits.forEach(unit -> affectedOwners.add(unit.owner())); + if (!revisionOwners.equals(affectedOwners)) { + throw new IllegalArgumentException( + "Required owner set must exactly match owners derived from revisions and affected units"); + } + return Arrays.stream(Owner.values()).filter(revisionOwners::contains).toList(); + } + + private static String serialize(Object object) { + return JSON.writeValueAsString(object); + } + + private static String sha256(byte[] bytes) { + try { + return "sha256:" + + java.util.HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + private static String requiredText(JsonNode object, String field) { + JsonNode value = object == null ? null : object.get(field); + if (value == null || !value.isTextual()) { + throw new IllegalArgumentException( + "Stored Draft commit binding is missing text field " + field); + } + return value.textValue(); + } + + private static JsonNode requireObject(JsonNode object, String field) { + JsonNode value = object == null ? null : object.get(field); + if (value == null || !value.isObject()) { + throw new IllegalArgumentException( + "Stored Draft commit binding is missing object field " + field); + } + return value; + } + + private static JsonNode requiredArray(JsonNode object, String field) { + JsonNode value = object == null ? null : object.get(field); + if (value == null || !value.isArray()) { + throw new IllegalArgumentException( + "Stored Draft commit binding is missing array field " + field); + } + return value; + } + + private static long positiveLong(JsonNode object, String field) { + String value = requiredText(object, field); + try { + long parsed = Long.parseLong(value); + if (parsed <= 0 || !Long.toString(parsed).equals(value)) { + throw new IllegalArgumentException( + "Stored source row ID is not a positive canonical decimal"); + } + return parsed; + } catch (NumberFormatException exception) { + throw new IllegalArgumentException( + "Stored source row ID is outside the supported range", exception); + } + } + + private static void requireNonNil(UUID value, String label) { + Objects.requireNonNull(value, label); + if (NIL_UUID.equals(value)) { + throw new IllegalArgumentException(label + " must be a canonical non-nil UUID"); + } + } + + private static void requireCanonicalCounter(String value, String label) { + Objects.requireNonNull(value, label); + if (!value.matches("0|[1-9][0-9]*")) { + throw new IllegalArgumentException(label + " must be a canonical nonnegative decimal string"); + } + new BigInteger(value); + } + + private static void requireBoundedText(String value, int maxUtf8Bytes, String label) { + Objects.requireNonNull(value, label); + if (value.isBlank() + || value.getBytes(StandardCharsets.UTF_8).length > maxUtf8Bytes + || !value.equals(value.trim())) { + throw new IllegalArgumentException(label + " must be nonblank canonical bounded text"); + } + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountLogoutAllAuthorityEventV1CodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountLogoutAllAuthorityEventV1CodecTest.java new file mode 100644 index 0000000000..ee5cb00e0f --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountLogoutAllAuthorityEventV1CodecTest.java @@ -0,0 +1,197 @@ +package net.firedevops.firemud.common.account.authority; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.util.Map; +import net.firedevops.firemud.common.account.authority.AccountLogoutAllAuthorityEventV1Codec.AccountLogoutAllAuthorityEvent; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +class AccountLogoutAllAuthorityEventV1CodecTest { + private static final String VECTOR_RESOURCE = + "/net/firedevops/firemud/common/account/authority/" + + "account-auth-logout-all-event-v1-vectors.json"; + private static final ObjectMapper JSON = new ObjectMapper(); + private static JsonNode vectors; + + @BeforeAll + static void loadVectors() throws IOException { + try (InputStream stream = + AccountLogoutAllAuthorityEventV1CodecTest.class.getResourceAsStream(VECTOR_RESOURCE)) { + if (stream == null) { + throw new IOException("Missing shared event vectors: " + VECTOR_RESOURCE); + } + vectors = JSON.readTree(stream); + } + } + + @Test + void fixedVectorsVerifySealAndPreserveArbitraryPrecisionCounters() throws Exception { + assertThat(vectors.path("schemaVersion").asText()) + .isEqualTo("account-auth-logout-all-event-vectors/v1"); + + for (JsonNode vector : vectors.path("validEvents")) { + JsonNode wireEvent = vector.path("event"); + AccountLogoutAllAuthorityEvent verified = + AccountLogoutAllAuthorityEventV1Codec.verify(wireEvent.toString()); + assertThat(verified.eventDigest()).isEqualTo(vector.path("expectedEventDigest").asText()); + assertThat(verified.eventDigest()).isEqualTo(wireEvent.path("eventDigest").asText()); + assertThat(verified.canonicalJson()).isEqualTo(vector.path("expectedCanonicalJson").asText()); + assertThat(verified.canonicalJsonUtf8()) + .isEqualTo( + vector.path("expectedCanonicalJson").asText().getBytes(StandardCharsets.UTF_8)); + assertThat(verified.canonicalJsonUtf8()) + .isEqualTo(Rfc8785CanonicalJson.canonicalizeUtf8(wireEvent.toString())); + + ObjectNode preimage = (ObjectNode) wireEvent.deepCopy(); + preimage.remove("eventDigest"); + Map preimageMap = JSON.convertValue(preimage, new TypeReference<>() {}); + AccountLogoutAllAuthorityEvent sealed = + AccountLogoutAllAuthorityEventV1Codec.seal(preimageMap); + assertThat(sealed.eventDigest()).isEqualTo(vector.path("expectedEventDigest").asText()); + assertThat(sealed.canonicalJson()).isEqualTo(vector.path("expectedCanonicalJson").asText()); + } + + AccountLogoutAllAuthorityEvent ordinary = + AccountLogoutAllAuthorityEventV1Codec.verify( + vectors.path("validEvents").get(0).path("event").toString()); + assertThat(ordinary.accountId()).isEqualTo("11111111-1111-4111-8111-111111111111"); + assertThat(ordinary.requestId()).isEqualTo("22222222-2222-4222-8222-222222222222"); + assertThat(ordinary.eventId()) + .isEqualTo("account-logout-all-event-v1:22222222-2222-4222-8222-222222222222"); + assertThat(ordinary.accountSecurityCutoff().accountAuthorityGeneration()) + .isEqualTo(ordinary.accountAuthorityGeneration()); + assertThat(ordinary.accountSecurityCutoff().outboxStreamKey()) + .isEqualTo(ordinary.outboxStreamKey()); + assertThat(ordinary.accountSecurityCutoff().outboxSequence()) + .isEqualTo(ordinary.outboxSequence()); + + AccountLogoutAllAuthorityEvent large = + AccountLogoutAllAuthorityEventV1Codec.verify( + vectors.path("validEvents").get(1).path("event").toString()); + assertThat(large.outboxSequence()).isEqualTo("18446744073709551616000000000000000001"); + assertThat(large.accountAuthorityGeneration()) + .isEqualTo("92233720368547758081234567890123456789"); + assertThat(large.sourceVersion()).isEqualTo("90071992547409931234567890123456789"); + } + + @Test + void everyMutableDeclaredSourceFieldChangesTheDigest() { + ObjectNode baseline = (ObjectNode) vectors.path("validEvents").get(0).path("event").deepCopy(); + String originalDigest = baseline.path("eventDigest").asText(); + + for (JsonNode mutation : vectors.path("changedDeclaredFieldMutations")) { + ObjectNode changedWire = (ObjectNode) baseline.deepCopy(); + JsonNode changes = mutation.path("changes"); + changes + .fieldNames() + .forEachRemaining(field -> changedWire.set(field, changes.get(field).deepCopy())); + ObjectNode changedPreimage = (ObjectNode) changedWire.deepCopy(); + changedPreimage.remove("eventDigest"); + Map preimageMap = + JSON.convertValue(changedPreimage, new TypeReference<>() {}); + + AccountLogoutAllAuthorityEvent sealed = + AccountLogoutAllAuthorityEventV1Codec.seal(preimageMap); + assertThat(sealed.eventDigest()) + .as(mutation.path("name").asText()) + .isNotEqualTo(originalDigest); + assertThatThrownBy(() -> AccountLogoutAllAuthorityEventV1Codec.verify(changedWire.toString())) + .as(mutation.path("name").asText()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("eventDigest"); + } + } + + @Test + void canonicalPropertyReorderingPreservesTheFixedEvent() { + JsonNode vector = vectors.path("validEvents").get(0); + JsonNode event = vector.path("event"); + ObjectNode reordered = JSON.createObjectNode(); + for (JsonNode field : vectors.path("canonicalReorderedPropertyOrder")) { + String fieldName = field.asText(); + reordered.set(fieldName, event.path(fieldName).deepCopy()); + } + + AccountLogoutAllAuthorityEvent verified = + AccountLogoutAllAuthorityEventV1Codec.verify(reordered.toString()); + assertThat(verified.eventDigest()).isEqualTo(vector.path("expectedEventDigest").asText()); + assertThat(verified.canonicalJson()).isEqualTo(vector.path("expectedCanonicalJson").asText()); + } + + @Test + void malformedAndNoncanonicalVectorsAreRejected() { + ObjectNode baseline = (ObjectNode) vectors.path("validEvents").get(0).path("event").deepCopy(); + for (JsonNode mutation : vectors.path("invalidMutations")) { + ObjectNode changed = (ObjectNode) baseline.deepCopy(); + applyMutation(changed, mutation); + assertThatThrownBy(() -> AccountLogoutAllAuthorityEventV1Codec.verify(changed.toString())) + .as(mutation.path("name").asText()) + .isInstanceOf(IllegalArgumentException.class); + } + } + + @Test + void duplicatePropertiesAndLegacySchemasAreRejected() { + assertThatThrownBy( + () -> + AccountLogoutAllAuthorityEventV1Codec.verify( + "{\"eventId\":\"first\",\"eventId\":\"second\"}")) + .isInstanceOf(IllegalArgumentException.class); + + ObjectNode passwordReset = + (ObjectNode) vectors.path("validEvents").get(0).path("event").deepCopy(); + passwordReset.put("schemaVersion", "account-auth-password-reset-event/v1"); + passwordReset.put("eventType", "PASSWORD_RESET_COMMITTED"); + assertThatThrownBy(() -> AccountLogoutAllAuthorityEventV1Codec.verify(passwordReset.toString())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("schemaVersion"); + + assertThatThrownBy( + () -> + AccountLogoutAllAuthorityEventV1Codec.verify( + "{\"schemaVersion\":\"account-auth-issuer-generation-event/v1\"," + + "\"eventType\":\"ISSUER_GENERATION_ADVANCED\"}")) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void parsedEvidenceAndReturnedBytesAreImmutable() { + JsonNode vector = vectors.path("validEvents").get(0); + AccountLogoutAllAuthorityEvent event = + AccountLogoutAllAuthorityEventV1Codec.verify(vector.path("event").toString()); + byte[] bytes = event.canonicalJsonUtf8(); + bytes[0] = (byte) 'x'; + + assertThat(event.canonicalJsonUtf8()) + .isEqualTo(vector.path("expectedCanonicalJson").asText().getBytes(StandardCharsets.UTF_8)); + assertThat(event.accountSecurityCutoff().accountAuthorityGeneration()) + .isEqualTo(event.accountAuthorityGeneration()); + } + + private static void applyMutation(ObjectNode root, JsonNode mutation) { + String[] path = mutation.path("path").asText().substring(1).split("/"); + JsonNode parent = root; + for (int index = 0; index < path.length - 1; index++) { + parent = parent.path(path[index]); + } + if (!(parent instanceof ObjectNode object)) { + throw new IllegalArgumentException("Mutation parent must be an object: " + mutation); + } + String field = path[path.length - 1]; + switch (mutation.path("op").asText()) { + case "add", "replace" -> object.set(field, mutation.path("value").deepCopy()); + case "remove" -> object.remove(field); + default -> throw new IllegalArgumentException("Unsupported mutation operation: " + mutation); + } + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1CodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1CodecTest.java new file mode 100644 index 0000000000..146847ada6 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1CodecTest.java @@ -0,0 +1,327 @@ +package net.firedevops.firemud.common.account.authority; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.function.Consumer; +import org.junit.jupiter.api.Test; + +class AccountSecurityStateAuthorityEventV1CodecTest { + private static final ObjectMapper JSON = new ObjectMapper(); + private static final String ACCOUNT = "11111111-1111-4111-8111-111111111111"; + private static final String REQUEST = "22222222-2222-4222-8222-222222222222"; + private static final String STREAM = "account:auth-authority:v1:account/" + ACCOUNT; + private static final String DIGEST = + "sha256:6e6b82b81006e447301262b666825022462f4298a8b3fc0d44ce4a73895b3374"; + private static final String CANONICAL_PREIMAGE = + "{\"accountAuthorityGeneration\":\"2\",\"accountId\":\"" + + ACCOUNT + + "\",\"accountSecurityCutoff\":{\"accountAuthorityGeneration\":\"2\"," + + "\"outboxSequence\":\"1\",\"outboxStreamKey\":\"" + + STREAM + + "\"},\"accountState\":{\"emailVerified\":true,\"globalRoles\":[]," + + "\"lifecycleState\":\"ACTIVE\",\"loginAuthModes\":[\"EMAIL_OTP\",\"PASSWORD\"]}," + + "\"eventId\":\"account-security-state-event-v1:" + + REQUEST + + "\",\"eventType\":\"ACCOUNT_SECURITY_STATE_CHANGED\"," + + "\"mutationKinds\":[\"EMAIL_LOGIN_ELIGIBILITY_CHANGED\",\"LOGIN_AUTH_MODES_CHANGED\"]," + + "\"outboxSequence\":\"1\",\"outboxStreamKey\":\"" + + STREAM + + "\",\"requestId\":\"" + + REQUEST + + "\",\"schemaVersion\":\"account-auth-account-security-state-event/v1\"," + + "\"sourceScope\":\"account/" + + ACCOUNT + + "\",\"sourceVersion\":\"2\"}"; + private static final String CANONICAL_WIRE = + CANONICAL_PREIMAGE.replace("\"eventId\":", "\"eventDigest\":\"" + DIGEST + "\",\"eventId\":"); + + @Test + void fixedCombinedFamilyVectorSealsAndVerifiesExactCanonicalBytesAndHash() throws Exception { + var sealed = seal(preimage()); + var verified = AccountSecurityStateAuthorityEventV1Codec.verify(CANONICAL_WIRE); + assertThat(sealed.eventDigest()).isEqualTo(DIGEST); + assertThat(sealed.canonicalJson()).isEqualTo(CANONICAL_WIRE); + assertThat(verified.canonicalJsonUtf8()) + .isEqualTo(CANONICAL_WIRE.getBytes(StandardCharsets.UTF_8)); + assertThat(verified.accountId()).isEqualTo(ACCOUNT); + assertThat(verified.requestId()).isEqualTo(REQUEST); + assertThat(verified.sourceScope()).isEqualTo("account/" + ACCOUNT); + assertThat(verified.accountState().globalRoles()).isEmpty(); + assertThat(verified.mutationKinds()) + .containsExactly("EMAIL_LOGIN_ELIGIBILITY_CHANGED", "LOGIN_AUTH_MODES_CHANGED"); + assertThat(verified.accountSecurityCutoff().outboxSequence()).isEqualTo("1"); + } + + @Test + void positiveCountersBeyondLongArePreservedWithoutNumericConversion() throws Exception { + ObjectNode value = preimage(); + String huge = "18446744073709551616000000000000000001"; + value.put("accountAuthorityGeneration", huge); + value.put("sourceVersion", huge); + value.put("outboxSequence", huge); + cutoff(value).put("accountAuthorityGeneration", huge); + cutoff(value).put("outboxSequence", huge); + var sealed = seal(value); + var verified = AccountSecurityStateAuthorityEventV1Codec.verify(sealed.canonicalJson()); + assertThat(verified.accountAuthorityGeneration()).isEqualTo(huge); + assertThat(verified.sourceVersion()).isEqualTo(huge); + assertThat(verified.outboxSequence()).isEqualTo(huge); + assertThat(verified.accountSecurityCutoff().accountAuthorityGeneration()).isEqualTo(huge); + } + + @Test + void everyDeclaredRootAndNestedFieldIsRequiredAndBoundToOriginalDigest() throws Exception { + ObjectNode wire = (ObjectNode) JSON.readTree(CANONICAL_WIRE); + for (String section : List.of("", "accountState", "accountSecurityCutoff")) { + ObjectNode sectionNode = section.isEmpty() ? wire : (ObjectNode) wire.get(section); + List fields = new ArrayList<>(); + sectionNode.fieldNames().forEachRemaining(fields::add); + for (String field : fields) { + ObjectNode missing = wire.deepCopy(); + node(missing, section).remove(field); + reject(missing); + ObjectNode changed = wire.deepCopy(); + node(changed, section).putNull(field); + reject(changed); + } + } + } + + @Test + void supportedSemanticChangesRequireNewDigest() throws Exception { + List> changes = + List.of( + value -> { + String request = "33333333-3333-4333-8333-333333333333"; + value.put("requestId", request); + value.put("eventId", "account-security-state-event-v1:" + request); + }, + value -> { + String account = "44444444-4444-4444-8444-444444444444"; + String stream = "account:auth-authority:v1:account/" + account; + value.put("accountId", account); + value.put("sourceScope", "account/" + account); + value.put("outboxStreamKey", stream); + cutoff(value).put("outboxStreamKey", stream); + }, + value -> { + value.put("accountAuthorityGeneration", "3"); + cutoff(value).put("accountAuthorityGeneration", "3"); + }, + value -> value.put("sourceVersion", "3"), + value -> { + value.put("outboxSequence", "2"); + cutoff(value).put("outboxSequence", "2"); + }, + value -> state(value).put("emailVerified", false), + value -> state(value).putArray("loginAuthModes").add("PASSWORD"), + value -> state(value).putArray("globalRoles").add("platformAdmin"), + value -> state(value).put("lifecycleState", "SECURITY_LOCKED"), + value -> value.putArray("mutationKinds").add("GLOBAL_ROLE_CHANGED")); + for (Consumer change : changes) { + ObjectNode changed = preimage(); + change.accept(changed); + var sealed = seal(changed); + assertThat(sealed.eventDigest()).isNotEqualTo(DIGEST); + changed.put("eventDigest", DIGEST); + assertThatThrownBy(() -> AccountSecurityStateAuthorityEventV1Codec.verify(changed.toString())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("eventDigest"); + } + } + + @Test + void undeclaredFencesSecretsAndScalarRolesAreRejectedAtEveryObjectBoundary() throws Exception { + ObjectNode wire = (ObjectNode) JSON.readTree(CANONICAL_WIRE); + for (String section : List.of("", "accountState", "accountSecurityCutoff")) { + for (String extra : + List.of( + "issuanceFence", + "issuanceFenceSourceVersion", + "authorityTuple", + "passwordHash", + "password", + "globalRole", + "unknown")) { + ObjectNode changed = wire.deepCopy(); + node(changed, section).put(extra, "injected"); + reject(changed); + } + } + } + + @Test + void invalidCounterGrammarAndNumericAliasesAreRejected() throws Exception { + for (String section : List.of("", "accountSecurityCutoff")) { + List fields = + section.isEmpty() + ? List.of("accountAuthorityGeneration", "sourceVersion", "outboxSequence") + : List.of("accountAuthorityGeneration", "outboxSequence"); + for (String field : fields) { + for (String invalid : List.of("", "0", "01", "+1", "-1", "1.0", "1e2", " 1", "1 ")) { + ObjectNode changed = (ObjectNode) JSON.readTree(CANONICAL_WIRE); + node(changed, section).put(field, invalid); + reject(changed); + } + ObjectNode numeric = (ObjectNode) JSON.readTree(CANONICAL_WIRE); + node(numeric, section).put(field, 1); + reject(numeric); + } + } + } + + @Test + void unsupportedAndUnsortedDuplicateArraysAreRejectedBeforeSealing() throws Exception { + for (String field : List.of("mutationKinds", "loginAuthModes", "globalRoles")) { + String section = field.equals("mutationKinds") ? "" : "accountState"; + List> invalid = + switch (field) { + case "mutationKinds" -> + List.of( + List.of(), + List.of("PASSWORD_RESET"), + List.of("LOGOUT_ALL"), + List.of("GLOBAL_ROLE_CHANGED", "EMAIL_LOGIN_ELIGIBILITY_CHANGED"), + List.of("GLOBAL_ROLE_CHANGED", "GLOBAL_ROLE_CHANGED")); + case "loginAuthModes" -> + List.of( + List.of(), + List.of("password"), + List.of("PASSKEY"), + List.of("PASSWORD", "EMAIL_OTP"), + List.of("PASSWORD", "PASSWORD")); + default -> + List.of( + List.of("player"), + List.of("admin"), + List.of(""), + List.of("support", "platformAdmin"), + List.of("support", "support")); + }; + for (List values : invalid) { + ObjectNode changed = preimage(); + var array = node(changed, section).putArray(field); + values.forEach(array::add); + assertThatThrownBy(() -> seal(changed)).isInstanceOf(IllegalArgumentException.class); + } + } + } + + @Test + void exactPolicyVocabularyAndCombinedFamilySetAreSupported() throws Exception { + ObjectNode value = preimage(); + value + .putArray("mutationKinds") + .add("EMAIL_LOGIN_ELIGIBILITY_CHANGED") + .add("GLOBAL_ROLE_CHANGED") + .add("LIFECYCLE_STATE_CHANGED") + .add("LOGIN_AUTH_MODES_CHANGED"); + state(value).putArray("globalRoles").add("billingAdmin").add("platformAdmin").add("support"); + for (String lifecycle : + List.of("ACTIVE", "SECURITY_LOCKED", "DEACTIVATED_PENDING_DELETE", "DELETED")) { + state(value).put("lifecycleState", lifecycle); + assertThat(seal(value).mutationKinds()).hasSize(4); + } + for (String unsupported : List.of("active", "SUSPENDED", "")) { + state(value).put("lifecycleState", unsupported); + assertThatThrownBy(() -> seal(value)).isInstanceOf(IllegalArgumentException.class); + } + state(value).put("lifecycleState", "ACTIVE"); + state(value).put("emailVerified", "true"); + assertThatThrownBy(() -> seal(value)).isInstanceOf(IllegalArgumentException.class); + } + + @Test + void wrongIdentitiesScopeCutoffAndDiscriminatorsAreDenied() throws Exception { + List> changes = + List.of( + value -> value.put("schemaVersion", "account-auth-authority-source-event/v1"), + value -> value.put("eventType", "PASSWORD_RESET_COMMITTED"), + value -> value.put("eventId", "account-security-state-event-v1:other"), + value -> value.put("requestId", "00000000-0000-0000-0000-000000000000"), + value -> value.put("accountId", "11111111-1111-4111-8111-11111111111A"), + value -> value.put("sourceScope", "issuer/other"), + value -> value.put("outboxStreamKey", STREAM + "other"), + value -> cutoff(value).put("outboxStreamKey", STREAM + "other"), + value -> cutoff(value).put("outboxSequence", "2"), + value -> cutoff(value).put("accountAuthorityGeneration", "3")); + for (Consumer change : changes) { + ObjectNode changed = preimage(); + change.accept(changed); + assertThatThrownBy(() -> seal(changed)).isInstanceOf(IllegalArgumentException.class); + } + } + + @Test + void duplicatePropertiesTrailingTokensAndNonObjectsAreDenied() { + for (String invalid : + List.of( + CANONICAL_WIRE.replace( + "\"emailVerified\":true", "\"emailVerified\":true,\"emailVerified\":false"), + CANONICAL_WIRE.replace( + "\"sourceVersion\":\"2\"", "\"sourceVersion\":\"2\",\"sourceVersion\":\"2\""), + CANONICAL_WIRE + " {}", + "[]", + "null")) { + assertThatThrownBy(() -> AccountSecurityStateAuthorityEventV1Codec.verify(invalid)) + .isInstanceOf(IllegalArgumentException.class); + } + } + + @Test + void propertyReorderingCanonicalizesAndEvidenceDoesNotExposeMutableStorage() throws Exception { + ObjectNode reordered = JSON.createObjectNode(); + ObjectNode original = (ObjectNode) JSON.readTree(CANONICAL_WIRE); + List fields = new ArrayList<>(); + original.fieldNames().forEachRemaining(fields::add); + java.util.Collections.reverse(fields); + fields.forEach(field -> reordered.set(field, original.get(field))); + var evidence = AccountSecurityStateAuthorityEventV1Codec.verify(reordered.toString()); + assertThat(evidence.canonicalJson()).isEqualTo(CANONICAL_WIRE); + byte[] bytes = evidence.canonicalJsonUtf8(); + bytes[0] = 0; + assertThat(evidence.canonicalJsonUtf8()) + .isEqualTo(CANONICAL_WIRE.getBytes(StandardCharsets.UTF_8)); + assertThatThrownBy(() -> evidence.mutationKinds().add("GLOBAL_ROLE_CHANGED")) + .isInstanceOf(UnsupportedOperationException.class); + assertThatThrownBy(() -> evidence.accountState().loginAuthModes().clear()) + .isInstanceOf(UnsupportedOperationException.class); + assertThatThrownBy(() -> evidence.accountState().globalRoles().add("support")) + .isInstanceOf(UnsupportedOperationException.class); + } + + private static ObjectNode preimage() throws Exception { + return (ObjectNode) JSON.readTree(CANONICAL_PREIMAGE); + } + + private static ObjectNode node(ObjectNode root, String section) { + return section.isEmpty() ? root : (ObjectNode) root.get(section); + } + + private static ObjectNode state(ObjectNode root) { + return node(root, "accountState"); + } + + private static ObjectNode cutoff(ObjectNode root) { + return node(root, "accountSecurityCutoff"); + } + + private static AccountSecurityStateAuthorityEventV1Codec.AccountSecurityStateAuthorityEvent seal( + ObjectNode value) { + Map fields = JSON.convertValue(value, new TypeReference<>() {}); + return AccountSecurityStateAuthorityEventV1Codec.seal(fields); + } + + private static void reject(ObjectNode value) { + assertThatThrownBy(() -> AccountSecurityStateAuthorityEventV1Codec.verify(value.toString())) + .isInstanceOf(IllegalArgumentException.class); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/IssuerGenerationAuthorityEventV1CodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/IssuerGenerationAuthorityEventV1CodecTest.java new file mode 100644 index 0000000000..830246b21f --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/IssuerGenerationAuthorityEventV1CodecTest.java @@ -0,0 +1,194 @@ +package net.firedevops.firemud.common.account.authority; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.util.Map; +import net.firedevops.firemud.common.account.authority.IssuerGenerationAuthorityEventV1Codec.IssuerGenerationAuthorityEvent; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +class IssuerGenerationAuthorityEventV1CodecTest { + private static final String VECTOR_RESOURCE = + "/net/firedevops/firemud/common/account/authority/account-auth-issuer-generation-event-v1-vectors.json"; + private static final ObjectMapper JSON = new ObjectMapper(); + private static JsonNode vectors; + + @BeforeAll + static void loadVectors() throws IOException { + try (InputStream stream = + IssuerGenerationAuthorityEventV1CodecTest.class.getResourceAsStream(VECTOR_RESOURCE)) { + if (stream == null) { + throw new IOException("Missing shared event vectors: " + VECTOR_RESOURCE); + } + vectors = JSON.readTree(stream); + } + } + + @Test + void fixedVectorsVerifySealAndArbitraryPrecisionCounters() throws Exception { + assertThat(vectors.path("schemaVersion").asText()) + .isEqualTo("account-auth-issuer-generation-event-vectors/v1"); + + for (JsonNode vector : vectors.path("validEvents")) { + JsonNode wireEvent = vector.path("event"); + IssuerGenerationAuthorityEvent verified = + IssuerGenerationAuthorityEventV1Codec.verify(wireEvent.toString()); + assertThat(verified.eventDigest()).isEqualTo(vector.path("expectedEventDigest").asText()); + assertThat(verified.eventDigest()).isEqualTo(wireEvent.path("eventDigest").asText()); + assertThat(verified.canonicalJson()).isEqualTo(vector.path("expectedCanonicalJson").asText()); + assertThat(verified.canonicalJsonUtf8()) + .isEqualTo( + vector.path("expectedCanonicalJson").asText().getBytes(StandardCharsets.UTF_8)); + assertThat(verified.canonicalJsonUtf8()) + .isEqualTo(Rfc8785CanonicalJson.canonicalizeUtf8(wireEvent.toString())); + + Map wireMap = JSON.convertValue(wireEvent, new TypeReference<>() {}); + assertThat(IssuerGenerationAuthorityEventV1Codec.verify(wireMap).canonicalJson()) + .isEqualTo(vector.path("expectedCanonicalJson").asText()); + + ObjectNode preimage = (ObjectNode) wireEvent.deepCopy(); + preimage.remove("eventDigest"); + Map preimageMap = JSON.convertValue(preimage, new TypeReference<>() {}); + IssuerGenerationAuthorityEvent sealed = + IssuerGenerationAuthorityEventV1Codec.seal(preimageMap); + assertThat(sealed.eventDigest()).isEqualTo(vector.path("expectedEventDigest").asText()); + assertThat(sealed.canonicalJson()).isEqualTo(vector.path("expectedCanonicalJson").asText()); + } + + JsonNode baselineVector = vectors.path("validEvents").get(0); + IssuerGenerationAuthorityEvent baseline = + IssuerGenerationAuthorityEventV1Codec.verify(baselineVector.path("event").toString()); + assertThat(baseline.schemaVersion()).isEqualTo("account-auth-issuer-generation-event/v1"); + assertThat(baseline.eventType()).isEqualTo("ISSUER_GENERATION_ADVANCED"); + assertThat(baseline.eventId()).isEqualTo("event-issuer-generation-001"); + assertThat(baseline.requestId()).isEqualTo("request-issuer-generation-001"); + assertThat(baseline.issuerId()).isEqualTo("https://Auth.FireMUD.example/issuer"); + assertThat(baseline.sourceScope()).isEqualTo("issuer/https://Auth.FireMUD.example/issuer"); + assertThat(baseline.outboxStreamKey()) + .isEqualTo("account:auth-authority:v1:issuer/https://Auth.FireMUD.example/issuer"); + assertThat(baseline.outboxSequence()).isEqualTo("7"); + assertThat(baseline.issuerAuthGeneration()).isEqualTo("5"); + assertThat(baseline.sourceVersion()).isEqualTo("6"); + + IssuerGenerationAuthorityEvent large = + IssuerGenerationAuthorityEventV1Codec.verify( + vectors.path("validEvents").get(1).path("event").toString()); + assertThat(large.outboxSequence()).isEqualTo("18446744073709551616000000000000000001"); + assertThat(large.issuerAuthGeneration()).isEqualTo("92233720368547758081234567890123456789"); + assertThat(large.sourceVersion()).isEqualTo("90071992547409931234567890123456789"); + } + + @Test + void changingEveryDeclaredPreimageFieldCannotReuseTheOriginalDigest() { + ObjectNode baseline = (ObjectNode) vectors.path("validEvents").get(0).path("event").deepCopy(); + String originalDigest = baseline.path("eventDigest").asText(); + + for (JsonNode mutation : vectors.path("changedDeclaredFieldMutations")) { + ObjectNode changedWire = (ObjectNode) baseline.deepCopy(); + JsonNode changes = mutation.path("changes"); + changes + .fieldNames() + .forEachRemaining(field -> changedWire.set(field, changes.get(field).deepCopy())); + ObjectNode changedPreimage = (ObjectNode) changedWire.deepCopy(); + changedPreimage.remove("eventDigest"); + Map preimageMap = + JSON.convertValue(changedPreimage, new TypeReference<>() {}); + + if (mutation.path("sealValid").asBoolean()) { + IssuerGenerationAuthorityEvent sealed = + IssuerGenerationAuthorityEventV1Codec.seal(preimageMap); + assertThat(sealed.eventDigest()) + .as(mutation.path("name").asText()) + .isNotEqualTo(originalDigest); + assertThatThrownBy( + () -> IssuerGenerationAuthorityEventV1Codec.verify(changedWire.toString())) + .as(mutation.path("name").asText()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("eventDigest"); + } else { + assertThatThrownBy(() -> IssuerGenerationAuthorityEventV1Codec.seal(preimageMap)) + .as(mutation.path("name").asText()) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> IssuerGenerationAuthorityEventV1Codec.verify(changedWire.toString())) + .as(mutation.path("name").asText()) + .isInstanceOf(IllegalArgumentException.class); + } + } + } + + @Test + void canonicalPropertyReorderingPreservesTheFixedCanonicalEvent() { + JsonNode vector = vectors.path("validEvents").get(0); + JsonNode event = vector.path("event"); + ObjectNode reordered = JSON.createObjectNode(); + for (JsonNode field : vectors.path("canonicalReorderedPropertyOrder")) { + String fieldName = field.asText(); + reordered.set(fieldName, event.path(fieldName).deepCopy()); + } + + IssuerGenerationAuthorityEvent verified = + IssuerGenerationAuthorityEventV1Codec.verify(reordered.toString()); + assertThat(verified.eventDigest()).isEqualTo(vector.path("expectedEventDigest").asText()); + assertThat(verified.canonicalJson()).isEqualTo(vector.path("expectedCanonicalJson").asText()); + } + + @Test + void malformedAndNoncanonicalVectorsAreRejected() { + ObjectNode baseline = (ObjectNode) vectors.path("validEvents").get(0).path("event").deepCopy(); + for (JsonNode mutation : vectors.path("invalidMutations")) { + ObjectNode changed = (ObjectNode) baseline.deepCopy(); + applyMutation(changed, mutation); + assertThatThrownBy(() -> IssuerGenerationAuthorityEventV1Codec.verify(changed.toString())) + .as(mutation.path("name").asText()) + .isInstanceOf(IllegalArgumentException.class); + } + } + + @Test + void duplicatePropertiesAreRejectedBeforeShapeValidation() { + assertThatThrownBy( + () -> + IssuerGenerationAuthorityEventV1Codec.verify( + "{\"eventId\":\"first\",\"eventId\":\"second\"}")) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void parsedEvidenceIsImmutableAndCanonicalBytesAreCallerOwned() { + JsonNode vector = vectors.path("validEvents").get(0); + IssuerGenerationAuthorityEvent event = + IssuerGenerationAuthorityEventV1Codec.verify(vector.path("event").toString()); + byte[] bytes = event.canonicalJsonUtf8(); + bytes[0] = (byte) 'x'; + + assertThat(event.canonicalJsonUtf8()) + .isEqualTo(vector.path("expectedCanonicalJson").asText().getBytes(StandardCharsets.UTF_8)); + } + + private static void applyMutation(ObjectNode root, JsonNode mutation) { + String[] path = mutation.path("path").asText().substring(1).split("/"); + JsonNode parent = root; + for (int index = 0; index < path.length - 1; index++) { + parent = parent.path(path[index]); + } + if (!(parent instanceof ObjectNode object)) { + throw new IllegalArgumentException("Mutation parent must be an object: " + mutation); + } + String field = path[path.length - 1]; + switch (mutation.path("op").asText()) { + case "add", "replace" -> object.set(field, mutation.path("value").deepCopy()); + case "remove" -> object.remove(field); + default -> throw new IllegalArgumentException("Unsupported mutation operation: " + mutation); + } + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/PasswordResetAuthorityEventV1CodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/PasswordResetAuthorityEventV1CodecTest.java new file mode 100644 index 0000000000..55a7fdf293 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/PasswordResetAuthorityEventV1CodecTest.java @@ -0,0 +1,167 @@ +package net.firedevops.firemud.common.account.authority; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.util.Map; +import net.firedevops.firemud.common.account.authority.PasswordResetAuthorityEventV1Codec.PasswordResetAuthorityEvent; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +class PasswordResetAuthorityEventV1CodecTest { + private static final String VECTOR_RESOURCE = + "/net/firedevops/firemud/common/account/authority/account-auth-password-reset-event-v1-vectors.json"; + private static final ObjectMapper JSON = new ObjectMapper(); + private static JsonNode vectors; + + @BeforeAll + static void loadVectors() throws IOException { + try (InputStream stream = + PasswordResetAuthorityEventV1CodecTest.class.getResourceAsStream(VECTOR_RESOURCE)) { + if (stream == null) { + throw new IOException("Missing shared event vectors: " + VECTOR_RESOURCE); + } + vectors = JSON.readTree(stream); + } + } + + @Test + void fixedVectorsVerifySealAndArbitraryPrecisionCounters() throws Exception { + assertThat(vectors.path("schemaVersion").asText()) + .isEqualTo("account-auth-password-reset-event-vectors/v1"); + + for (JsonNode vector : vectors.path("validEvents")) { + JsonNode wireEvent = vector.path("event"); + PasswordResetAuthorityEvent verified = + PasswordResetAuthorityEventV1Codec.verify(wireEvent.toString()); + assertThat(verified.eventDigest()).isEqualTo(vector.path("expectedEventDigest").asText()); + assertThat(verified.eventDigest()).isEqualTo(wireEvent.path("eventDigest").asText()); + assertThat(verified.canonicalJson()).isEqualTo(vector.path("expectedCanonicalJson").asText()); + assertThat(verified.canonicalJsonUtf8()) + .isEqualTo( + vector.path("expectedCanonicalJson").asText().getBytes(StandardCharsets.UTF_8)); + assertThat(verified.canonicalJsonUtf8()) + .isEqualTo(Rfc8785CanonicalJson.canonicalizeUtf8(wireEvent.toString())); + + ObjectNode preimage = (ObjectNode) wireEvent.deepCopy(); + preimage.remove("eventDigest"); + Map preimageMap = JSON.convertValue(preimage, new TypeReference<>() {}); + PasswordResetAuthorityEvent sealed = PasswordResetAuthorityEventV1Codec.seal(preimageMap); + assertThat(sealed.eventDigest()).isEqualTo(vector.path("expectedEventDigest").asText()); + assertThat(sealed.canonicalJson()).isEqualTo(vector.path("expectedCanonicalJson").asText()); + } + + PasswordResetAuthorityEvent large = + PasswordResetAuthorityEventV1Codec.verify( + vectors.path("validEvents").get(1).path("event").toString()); + assertThat(large.outboxSequence()).isEqualTo("18446744073709551616000000000000000001"); + assertThat(large.accountAuthorityGeneration()) + .isEqualTo("92233720368547758081234567890123456789"); + assertThat(large.sourceVersion()).isEqualTo("90071992547409931234567890123456789"); + } + + @Test + void changingAnyDeclaredSourceEvidenceCannotReuseTheOriginalDigest() { + ObjectNode baseline = (ObjectNode) vectors.path("validEvents").get(0).path("event").deepCopy(); + String originalDigest = baseline.path("eventDigest").asText(); + + for (JsonNode mutation : vectors.path("changedDeclaredFieldMutations")) { + ObjectNode changedWire = (ObjectNode) baseline.deepCopy(); + JsonNode changes = mutation.path("changes"); + changes + .fieldNames() + .forEachRemaining(field -> changedWire.set(field, changes.get(field).deepCopy())); + ObjectNode changedPreimage = (ObjectNode) changedWire.deepCopy(); + changedPreimage.remove("eventDigest"); + Map preimageMap = + JSON.convertValue(changedPreimage, new TypeReference<>() {}); + + PasswordResetAuthorityEvent sealed = PasswordResetAuthorityEventV1Codec.seal(preimageMap); + assertThat(sealed.eventDigest()) + .as(mutation.path("name").asText()) + .isNotEqualTo(originalDigest); + assertThatThrownBy(() -> PasswordResetAuthorityEventV1Codec.verify(changedWire.toString())) + .as(mutation.path("name").asText()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("eventDigest"); + } + } + + @Test + void canonicalPropertyReorderingPreservesTheFixedCanonicalEvent() { + JsonNode vector = vectors.path("validEvents").get(0); + JsonNode event = vector.path("event"); + ObjectNode reordered = JSON.createObjectNode(); + for (JsonNode field : vectors.path("canonicalReorderedPropertyOrder")) { + String fieldName = field.asText(); + reordered.set(fieldName, event.path(fieldName).deepCopy()); + } + + PasswordResetAuthorityEvent verified = + PasswordResetAuthorityEventV1Codec.verify(reordered.toString()); + assertThat(verified.eventDigest()).isEqualTo(vector.path("expectedEventDigest").asText()); + assertThat(verified.canonicalJson()).isEqualTo(vector.path("expectedCanonicalJson").asText()); + } + + @Test + void malformedAndNoncanonicalVectorsAreRejected() { + ObjectNode baseline = (ObjectNode) vectors.path("validEvents").get(0).path("event").deepCopy(); + for (JsonNode mutation : vectors.path("invalidMutations")) { + ObjectNode changed = (ObjectNode) baseline.deepCopy(); + applyMutation(changed, mutation); + assertThatThrownBy(() -> PasswordResetAuthorityEventV1Codec.verify(changed.toString())) + .as(mutation.path("name").asText()) + .isInstanceOf(IllegalArgumentException.class); + } + } + + @Test + void duplicatePropertiesAreRejectedBeforeShapeValidation() { + assertThatThrownBy( + () -> + PasswordResetAuthorityEventV1Codec.verify( + "{\"eventId\":\"first\",\"eventId\":\"second\"}")) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void parsedEvidenceIsImmutableAndCanonicalBytesAreCallerOwned() { + JsonNode vector = vectors.path("validEvents").get(0); + PasswordResetAuthorityEvent event = + PasswordResetAuthorityEventV1Codec.verify(vector.path("event").toString()); + byte[] bytes = event.canonicalJsonUtf8(); + bytes[0] = (byte) 'x'; + + assertThat(event.canonicalJsonUtf8()) + .isEqualTo(vector.path("expectedCanonicalJson").asText().getBytes(StandardCharsets.UTF_8)); + assertThat(event.accountSecurityCutoff().accountAuthorityGeneration()) + .isEqualTo(event.accountAuthorityGeneration()); + assertThat(event.accountSecurityCutoff().outboxStreamKey()).isEqualTo(event.outboxStreamKey()); + assertThat(event.accountSecurityCutoff().outboxSequence()).isEqualTo(event.outboxSequence()); + } + + private static void applyMutation(ObjectNode root, JsonNode mutation) { + String[] path = mutation.path("path").asText().substring(1).split("/"); + JsonNode parent = root; + for (int index = 0; index < path.length - 1; index++) { + parent = parent.path(path[index]); + } + if (!(parent instanceof ObjectNode object)) { + throw new IllegalArgumentException("Mutation parent must be an object: " + mutation); + } + String field = path[path.length - 1]; + switch (mutation.path("op").asText()) { + case "add", "replace" -> object.set(field, mutation.path("value").deepCopy()); + case "remove" -> object.remove(field); + default -> throw new IllegalArgumentException("Unsupported mutation operation: " + mutation); + } + } +} diff --git a/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/authoring/DraftCommitBindingTest.java b/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/authoring/DraftCommitBindingTest.java new file mode 100644 index 0000000000..de3e7b5d75 --- /dev/null +++ b/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/authoring/DraftCommitBindingTest.java @@ -0,0 +1,224 @@ +package unit.net.firedevops.firemud.common.authoring; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import org.junit.jupiter.api.Test; +import tools.jackson.databind.ObjectMapper; +import tools.jackson.databind.node.ObjectNode; + +class DraftCommitBindingTest { + private static final String LARGE_EPOCH = "900719925474099312345678901234567890"; + + @Test + void canonicalBindingRetainsCompleteOpaqueInputsAndDecimalCounters() { + DraftCommitBinding binding = binding(); + DraftCommitBinding restored = + DraftCommitBinding.fromStored(binding.canonicalJson(), binding.digest()); + + assertThat(restored).isEqualTo(binding); + assertThat(binding.canonicalJson()) + .contains("\"gameDesignVersionRowId\":\"9007199254740993\"") + .contains("\"sourceGameRowId\":\"9007199254740995\"") + .contains("\"expectedEpoch\":\"" + LARGE_EPOCH + "\"") + .contains("unknownTypedField") + .contains("\\n \\\"full\\\": true"); + assertThat(binding.requiredOwners()) + .containsExactly(Owner.WORLD_MANAGEMENT, Owner.ENTITY_MANAGEMENT); + assertThat(binding.affectedUnits()) + .extracting(AffectedUnit::aggregateType, AffectedUnit::aggregateId) + .containsExactly( + org.assertj.core.groups.Tuple.tuple("WORLD_TEMPLATE", "world-23"), + org.assertj.core.groups.Tuple.tuple("ENTITY_TEMPLATE", "entity-17")); + + byte[] firstRead = binding.canonicalBytes(); + firstRead[0] = (byte) (firstRead[0] ^ 1); + assertThat(binding.canonicalBytes()).isNotEqualTo(firstRead); + assertThat(new String(binding.canonicalBytes(), StandardCharsets.UTF_8)) + .isEqualTo(binding.canonicalJson()); + } + + @Test + void canonicalBindingIsStableAcrossAffectedInputOrder() { + DraftCommitBinding first = binding(); + DraftCommitBinding reordered = + DraftCommitBinding.create( + first.target(), + first.requestId(), + first.commitId(), + first.baseCommitId(), + first.revisions(), + List.of(first.affectedUnits().get(1), first.affectedUnits().get(0))); + + assertThat(reordered.canonicalBytes()).containsExactly(first.canonicalBytes()); + assertThat(reordered.digest()).isEqualTo(first.digest()); + } + + @Test + void collectionAccessorsReturnImmutableCopies() { + DraftCommitBinding binding = binding(); + + assertThatThrownBy(() -> binding.revisions().add(binding.revisions().getFirst())) + .isInstanceOf(UnsupportedOperationException.class); + assertThatThrownBy(() -> binding.affectedUnits().clear()) + .isInstanceOf(UnsupportedOperationException.class); + assertThatThrownBy(() -> binding.requiredOwners().clear()) + .isInstanceOf(UnsupportedOperationException.class); + } + + @Test + void rejectsMissingOrNonArrayStoredCollections() { + DraftCommitBinding original = binding(); + ObjectMapper json = new ObjectMapper(); + + ObjectNode missingRevisions = (ObjectNode) json.readTree(original.canonicalJson()); + missingRevisions.remove("revisions"); + assertThatThrownBy( + () -> + DraftCommitBinding.fromStored( + json.writeValueAsString(missingRevisions), original.digest())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("corrupt"); + + ObjectNode invalidAffectedUnits = (ObjectNode) json.readTree(original.canonicalJson()); + invalidAffectedUnits.put("affectedUnits", "not-an-array"); + assertThatThrownBy( + () -> + DraftCommitBinding.fromStored( + json.writeValueAsString(invalidAffectedUnits), original.digest())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("corrupt"); + } + + @Test + void rejectsOmittedDuplicateOrInconsistentCanonicalOrder() { + DraftCommitBinding original = binding(); + assertThatThrownBy( + () -> + DraftCommitBinding.create( + original.target(), + original.requestId(), + original.commitId(), + original.baseCommitId(), + List.of(original.revisions().get(0)), + original.affectedUnits())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("owner set"); + assertThatThrownBy( + () -> + DraftCommitBinding.create( + original.target(), + original.requestId(), + original.commitId(), + original.baseCommitId(), + List.of(original.revisions().get(0), original.revisions().get(0)), + original.affectedUnits())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("canonical array order"); + assertThatThrownBy( + () -> + DraftCommitBinding.create( + original.target(), + original.requestId(), + original.commitId(), + original.baseCommitId(), + original.revisions(), + List.of(original.affectedUnits().get(0), original.affectedUnits().get(0)))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("duplicate affected"); + } + + @Test + void rejectsNonCanonicalCountersAndNilOrUnprovedTargetIdentity() { + DraftCommitBinding original = binding(); + AffectedUnit affected = original.affectedUnits().getFirst(); + assertThatThrownBy( + () -> + new AffectedUnit( + affected.owner(), + affected.aggregateType(), + affected.aggregateId(), + affected.scopeType(), + affected.scopeId(), + "01")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("canonical nonnegative decimal"); + assertThatThrownBy( + () -> + new TargetProof( + new UUID(0L, 0L), + original.target().canonicalVersionId(), + 1, + "tenant-source", + 2, + "tenant-source", + "NEW_GAME_ROW")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("canonical non-nil UUID"); + assertThatThrownBy( + () -> + new TargetProof( + original.target().canonicalTenantId(), + original.target().canonicalVersionId(), + 1, + "tenant-source", + 2, + "different-source", + "NEW_GAME_ROW")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("must match exactly"); + } + + private DraftCommitBinding binding() { + return DraftCommitBinding.create( + new TargetProof( + uuid("11111111-1111-4111-8111-111111111111"), + uuid("22222222-2222-4222-8222-222222222222"), + 9_007_199_254_740_993L, + "tenant-source", + 9_007_199_254_740_995L, + "tenant-source", + "NEW_GAME_ROW"), + uuid("33333333-3333-4333-8333-333333333333"), + uuid("44444444-4444-4444-8444-444444444444"), + "base-commit-opaque-01", + List.of( + new RevisionPayload( + "0", + uuid("55555555-5555-4555-8555-555555555555"), + Owner.WORLD_MANAGEMENT, + "{\n \"full\": true, \"unknownTypedField\": {\"keep\": \"all\"}\n}"), + new RevisionPayload( + "1", + uuid("66666666-6666-4666-8666-666666666666"), + Owner.ENTITY_MANAGEMENT, + "{\"actorTemplate\":{\"complete\":true}}")), + List.of( + new AffectedUnit( + Owner.WORLD_MANAGEMENT, + "WORLD_TEMPLATE", + "world-23", + "ROOM_SCOPE", + "room-scope-3", + LARGE_EPOCH), + new AffectedUnit( + Owner.ENTITY_MANAGEMENT, + "ENTITY_TEMPLATE", + "entity-17", + "ACTOR_SCOPE", + "actor-scope-2", + "0"))); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } +} diff --git a/services/common-platform-core/src/test/resources/net/firedevops/firemud/common/account/authority/account-auth-issuer-generation-event-v1-vectors.json b/services/common-platform-core/src/test/resources/net/firedevops/firemud/common/account/authority/account-auth-issuer-generation-event-v1-vectors.json new file mode 100644 index 0000000000..898dd32a2e --- /dev/null +++ b/services/common-platform-core/src/test/resources/net/firedevops/firemud/common/account/authority/account-auth-issuer-generation-event-v1-vectors.json @@ -0,0 +1,126 @@ +{ + "schemaVersion": "account-auth-issuer-generation-event-vectors/v1", + "validEvents": [ + { + "name": "issuer-generation-advance", + "event": { + "schemaVersion": "account-auth-issuer-generation-event/v1", + "eventType": "ISSUER_GENERATION_ADVANCED", + "eventId": "event-issuer-generation-001", + "requestId": "request-issuer-generation-001", + "issuerId": "https://Auth.FireMUD.example/issuer", + "sourceScope": "issuer/https://Auth.FireMUD.example/issuer", + "outboxStreamKey": "account:auth-authority:v1:issuer/https://Auth.FireMUD.example/issuer", + "outboxSequence": "7", + "issuerAuthGeneration": "5", + "sourceVersion": "6", + "eventDigest": "sha256:df88f7ee54a9f24102b6fbecc5a93595091e2d6a1fc7fca8ba2d8bbbc08cb735" + }, + "expectedEventDigest": "sha256:df88f7ee54a9f24102b6fbecc5a93595091e2d6a1fc7fca8ba2d8bbbc08cb735", + "expectedCanonicalJson": "{\"eventDigest\":\"sha256:df88f7ee54a9f24102b6fbecc5a93595091e2d6a1fc7fca8ba2d8bbbc08cb735\",\"eventId\":\"event-issuer-generation-001\",\"eventType\":\"ISSUER_GENERATION_ADVANCED\",\"issuerAuthGeneration\":\"5\",\"issuerId\":\"https://Auth.FireMUD.example/issuer\",\"outboxSequence\":\"7\",\"outboxStreamKey\":\"account:auth-authority:v1:issuer/https://Auth.FireMUD.example/issuer\",\"requestId\":\"request-issuer-generation-001\",\"schemaVersion\":\"account-auth-issuer-generation-event/v1\",\"sourceScope\":\"issuer/https://Auth.FireMUD.example/issuer\",\"sourceVersion\":\"6\"}" + }, + { + "name": "arbitrary-precision-counters", + "event": { + "schemaVersion": "account-auth-issuer-generation-event/v1", + "eventType": "ISSUER_GENERATION_ADVANCED", + "eventId": "event-issuer-generation-large", + "requestId": "request-issuer-generation-large", + "issuerId": "https://Auth.FireMUD.example/issuer", + "sourceScope": "issuer/https://Auth.FireMUD.example/issuer", + "outboxStreamKey": "account:auth-authority:v1:issuer/https://Auth.FireMUD.example/issuer", + "outboxSequence": "18446744073709551616000000000000000001", + "issuerAuthGeneration": "92233720368547758081234567890123456789", + "sourceVersion": "90071992547409931234567890123456789", + "eventDigest": "sha256:98b9c742c3267d4db283196c1d80865c3ab9227df08c6efd8c7025d46c79ee5c" + }, + "expectedEventDigest": "sha256:98b9c742c3267d4db283196c1d80865c3ab9227df08c6efd8c7025d46c79ee5c", + "expectedCanonicalJson": "{\"eventDigest\":\"sha256:98b9c742c3267d4db283196c1d80865c3ab9227df08c6efd8c7025d46c79ee5c\",\"eventId\":\"event-issuer-generation-large\",\"eventType\":\"ISSUER_GENERATION_ADVANCED\",\"issuerAuthGeneration\":\"92233720368547758081234567890123456789\",\"issuerId\":\"https://Auth.FireMUD.example/issuer\",\"outboxSequence\":\"18446744073709551616000000000000000001\",\"outboxStreamKey\":\"account:auth-authority:v1:issuer/https://Auth.FireMUD.example/issuer\",\"requestId\":\"request-issuer-generation-large\",\"schemaVersion\":\"account-auth-issuer-generation-event/v1\",\"sourceScope\":\"issuer/https://Auth.FireMUD.example/issuer\",\"sourceVersion\":\"90071992547409931234567890123456789\"}" + } + ], + "canonicalReorderedPropertyOrder": [ + "sourceVersion", + "sourceScope", + "schemaVersion", + "requestId", + "outboxStreamKey", + "outboxSequence", + "issuerId", + "issuerAuthGeneration", + "eventType", + "eventId", + "eventDigest" + ], + "changedDeclaredFieldMutations": [ + { + "name": "schema-version", + "sealValid": false, + "changes": {"schemaVersion": "account-auth-issuer-generation-event/v2"} + }, + { + "name": "event-type", + "sealValid": false, + "changes": {"eventType": "ISSUER_GENERATION_RESET"} + }, + { + "name": "event-id", + "sealValid": true, + "changes": {"eventId": "event-issuer-generation-changed"} + }, + { + "name": "request-id", + "sealValid": true, + "changes": {"requestId": "request-issuer-generation-changed"} + }, + { + "name": "issuer-id-preserves-exact-spelling", + "sealValid": true, + "changes": { + "issuerId": "https://auth.firemud.example/issuer", + "sourceScope": "issuer/https://auth.firemud.example/issuer", + "outboxStreamKey": "account:auth-authority:v1:issuer/https://auth.firemud.example/issuer" + } + }, + { + "name": "source-scope", + "sealValid": false, + "changes": {"sourceScope": "issuer/https://other.firemud.example/issuer"} + }, + { + "name": "outbox-stream-key", + "sealValid": false, + "changes": {"outboxStreamKey": "account:auth-authority:v1:issuer/https://other.firemud.example/issuer"} + }, + { + "name": "outbox-sequence", + "sealValid": true, + "changes": {"outboxSequence": "8"} + }, + { + "name": "issuer-auth-generation", + "sealValid": true, + "changes": {"issuerAuthGeneration": "6"} + }, + { + "name": "source-version", + "sealValid": true, + "changes": {"sourceVersion": "7"} + } + ], + "invalidMutations": [ + {"name": "missing-required-source-version", "op": "remove", "path": "/sourceVersion"}, + {"name": "unknown-top-level-property", "op": "add", "path": "/unexpected", "value": true}, + {"name": "null-issuer", "op": "replace", "path": "/issuerId", "value": null}, + {"name": "wrong-type-sequence", "op": "replace", "path": "/outboxSequence", "value": 7}, + {"name": "array-issuer", "op": "replace", "path": "/issuerId", "value": ["https://Auth.FireMUD.example/issuer"]}, + {"name": "blank-issuer", "op": "replace", "path": "/issuerId", "value": " \t"}, + {"name": "empty-event-id", "op": "replace", "path": "/eventId", "value": ""}, + {"name": "empty-request-id", "op": "replace", "path": "/requestId", "value": ""}, + {"name": "zero-sequence", "op": "replace", "path": "/outboxSequence", "value": "0"}, + {"name": "leading-zero-generation", "op": "replace", "path": "/issuerAuthGeneration", "value": "05"}, + {"name": "negative-source-version", "op": "replace", "path": "/sourceVersion", "value": "-1"}, + {"name": "mismatched-source-scope", "op": "replace", "path": "/sourceScope", "value": "issuer/https://other.firemud.example/issuer"}, + {"name": "mismatched-stream-key", "op": "replace", "path": "/outboxStreamKey", "value": "account:auth-authority:v1:issuer/https://other.firemud.example/issuer"}, + {"name": "invalid-digest", "op": "replace", "path": "/eventDigest", "value": "sha256:1111111111111111111111111111111111111111111111111111111111111111"} + ] +} diff --git a/services/common-platform-core/src/test/resources/net/firedevops/firemud/common/account/authority/account-auth-logout-all-event-v1-vectors.json b/services/common-platform-core/src/test/resources/net/firedevops/firemud/common/account/authority/account-auth-logout-all-event-v1-vectors.json new file mode 100644 index 0000000000..fd7cbdb26b --- /dev/null +++ b/services/common-platform-core/src/test/resources/net/firedevops/firemud/common/account/authority/account-auth-logout-all-event-v1-vectors.json @@ -0,0 +1,150 @@ +{ + "schemaVersion": "account-auth-logout-all-event-vectors/v1", + "validEvents": [ + { + "name": "standard-account-logout-all-cutoff", + "expectedEventDigest": "sha256:8bcd1a2c82b807a59f01cab599dfabc43d7b687fba80709ef9aa54590272f439", + "expectedCanonicalJson": "{\"accountAuthorityGeneration\":\"2\",\"accountId\":\"11111111-1111-4111-8111-111111111111\",\"accountSecurityCutoff\":{\"accountAuthorityGeneration\":\"2\",\"outboxSequence\":\"1\",\"outboxStreamKey\":\"account:auth-authority:v1:account/11111111-1111-4111-8111-111111111111\"},\"eventDigest\":\"sha256:8bcd1a2c82b807a59f01cab599dfabc43d7b687fba80709ef9aa54590272f439\",\"eventId\":\"account-logout-all-event-v1:22222222-2222-4222-8222-222222222222\",\"eventType\":\"LOGOUT_ALL_COMMITTED\",\"outboxSequence\":\"1\",\"outboxStreamKey\":\"account:auth-authority:v1:account/11111111-1111-4111-8111-111111111111\",\"requestId\":\"22222222-2222-4222-8222-222222222222\",\"schemaVersion\":\"account-auth-logout-all-event/v1\",\"sourceScope\":\"account/11111111-1111-4111-8111-111111111111\",\"sourceVersion\":\"2\"}", + "event": { + "schemaVersion": "account-auth-logout-all-event/v1", + "eventType": "LOGOUT_ALL_COMMITTED", + "eventId": "account-logout-all-event-v1:22222222-2222-4222-8222-222222222222", + "requestId": "22222222-2222-4222-8222-222222222222", + "accountId": "11111111-1111-4111-8111-111111111111", + "sourceScope": "account/11111111-1111-4111-8111-111111111111", + "outboxStreamKey": "account:auth-authority:v1:account/11111111-1111-4111-8111-111111111111", + "outboxSequence": "1", + "accountAuthorityGeneration": "2", + "sourceVersion": "2", + "accountSecurityCutoff": { + "accountAuthorityGeneration": "2", + "outboxStreamKey": "account:auth-authority:v1:account/11111111-1111-4111-8111-111111111111", + "outboxSequence": "1" + }, + "eventDigest": "sha256:8bcd1a2c82b807a59f01cab599dfabc43d7b687fba80709ef9aa54590272f439" + } + }, + { + "name": "counters-above-javascript-safe-integer-and-signed-long", + "expectedEventDigest": "sha256:c5938750b1da3b163fdadc80913667430052797e91671f098189f86e120e44d7", + "expectedCanonicalJson": "{\"accountAuthorityGeneration\":\"92233720368547758081234567890123456789\",\"accountId\":\"11111111-1111-4111-8111-111111111111\",\"accountSecurityCutoff\":{\"accountAuthorityGeneration\":\"92233720368547758081234567890123456789\",\"outboxSequence\":\"18446744073709551616000000000000000001\",\"outboxStreamKey\":\"account:auth-authority:v1:account/11111111-1111-4111-8111-111111111111\"},\"eventDigest\":\"sha256:c5938750b1da3b163fdadc80913667430052797e91671f098189f86e120e44d7\",\"eventId\":\"account-logout-all-event-v1:22222222-2222-4222-8222-222222222222\",\"eventType\":\"LOGOUT_ALL_COMMITTED\",\"outboxSequence\":\"18446744073709551616000000000000000001\",\"outboxStreamKey\":\"account:auth-authority:v1:account/11111111-1111-4111-8111-111111111111\",\"requestId\":\"22222222-2222-4222-8222-222222222222\",\"schemaVersion\":\"account-auth-logout-all-event/v1\",\"sourceScope\":\"account/11111111-1111-4111-8111-111111111111\",\"sourceVersion\":\"90071992547409931234567890123456789\"}", + "event": { + "schemaVersion": "account-auth-logout-all-event/v1", + "eventType": "LOGOUT_ALL_COMMITTED", + "eventId": "account-logout-all-event-v1:22222222-2222-4222-8222-222222222222", + "requestId": "22222222-2222-4222-8222-222222222222", + "accountId": "11111111-1111-4111-8111-111111111111", + "sourceScope": "account/11111111-1111-4111-8111-111111111111", + "outboxStreamKey": "account:auth-authority:v1:account/11111111-1111-4111-8111-111111111111", + "outboxSequence": "18446744073709551616000000000000000001", + "accountAuthorityGeneration": "92233720368547758081234567890123456789", + "sourceVersion": "90071992547409931234567890123456789", + "accountSecurityCutoff": { + "accountAuthorityGeneration": "92233720368547758081234567890123456789", + "outboxStreamKey": "account:auth-authority:v1:account/11111111-1111-4111-8111-111111111111", + "outboxSequence": "18446744073709551616000000000000000001" + }, + "eventDigest": "sha256:c5938750b1da3b163fdadc80913667430052797e91671f098189f86e120e44d7" + } + } + ], + "changedDeclaredFieldMutations": [ + { + "name": "request-and-derived-event-identities", + "changes": { + "requestId": "33333333-3333-4333-8333-333333333333", + "eventId": "account-logout-all-event-v1:33333333-3333-4333-8333-333333333333" + } + }, + { + "name": "account-identity-and-derived-scope", + "changes": { + "accountId": "44444444-4444-4444-8444-444444444444", + "sourceScope": "account/44444444-4444-4444-8444-444444444444", + "outboxStreamKey": "account:auth-authority:v1:account/44444444-4444-4444-8444-444444444444", + "accountSecurityCutoff": { + "accountAuthorityGeneration": "2", + "outboxStreamKey": "account:auth-authority:v1:account/44444444-4444-4444-8444-444444444444", + "outboxSequence": "1" + } + } + }, + { + "name": "outbox-sequence-and-cutoff", + "changes": { + "outboxSequence": "3", + "accountSecurityCutoff": { + "accountAuthorityGeneration": "2", + "outboxStreamKey": "account:auth-authority:v1:account/11111111-1111-4111-8111-111111111111", + "outboxSequence": "3" + } + } + }, + { + "name": "account-authority-generation-and-cutoff", + "changes": { + "accountAuthorityGeneration": "4", + "accountSecurityCutoff": { + "accountAuthorityGeneration": "4", + "outboxStreamKey": "account:auth-authority:v1:account/11111111-1111-4111-8111-111111111111", + "outboxSequence": "1" + } + } + }, + {"name": "source-version", "changes": {"sourceVersion": "3"}} + ], + "canonicalReorderedPropertyOrder": [ + "sourceVersion", + "requestId", + "outboxSequence", + "outboxStreamKey", + "eventType", + "eventId", + "eventDigest", + "accountId", + "accountAuthorityGeneration", + "accountSecurityCutoff", + "schemaVersion", + "sourceScope" + ], + "invalidMutations": [ + {"name": "unsupported-schema", "op": "replace", "path": "/schemaVersion", "value": "account-auth-logout-all-event/v2"}, + {"name": "password-reset-schema-is-not-an-alias", "op": "replace", "path": "/schemaVersion", "value": "account-auth-password-reset-event/v1"}, + {"name": "unsupported-event-type", "op": "replace", "path": "/eventType", "value": "PASSWORD_RESET_COMMITTED"}, + {"name": "numeric-event-type", "op": "replace", "path": "/eventType", "value": 7}, + {"name": "missing-event-id", "op": "remove", "path": "/eventId"}, + {"name": "null-event-id", "op": "replace", "path": "/eventId", "value": null}, + {"name": "missing-request-id", "op": "remove", "path": "/requestId"}, + {"name": "nil-request-id", "op": "replace", "path": "/requestId", "value": "00000000-0000-0000-0000-000000000000"}, + {"name": "uppercase-request-id", "op": "replace", "path": "/requestId", "value": "22222222-2222-4222-8222-22222222222A"}, + {"name": "request-event-identity-mismatch", "op": "replace", "path": "/requestId", "value": "33333333-3333-4333-8333-333333333333"}, + {"name": "wrong-event-id-prefix", "op": "replace", "path": "/eventId", "value": "password-reset-event-v1:22222222-2222-4222-8222-222222222222"}, + {"name": "nil-account-id", "op": "replace", "path": "/accountId", "value": "00000000-0000-0000-0000-000000000000"}, + {"name": "uppercase-account-id", "op": "replace", "path": "/accountId", "value": "11111111-1111-4111-8111-11111111111A"}, + {"name": "numeric-account-id", "op": "replace", "path": "/accountId", "value": 111}, + {"name": "mismatched-source-scope", "op": "replace", "path": "/sourceScope", "value": "account/22222222-2222-4222-8222-222222222222"}, + {"name": "mismatched-stream-key", "op": "replace", "path": "/outboxStreamKey", "value": "account:auth-authority:v1:account/22222222-2222-4222-8222-222222222222"}, + {"name": "numeric-outbox-sequence", "op": "replace", "path": "/outboxSequence", "value": 1}, + {"name": "zero-outbox-sequence", "op": "replace", "path": "/outboxSequence", "value": "0"}, + {"name": "leading-zero-outbox-sequence", "op": "replace", "path": "/outboxSequence", "value": "01"}, + {"name": "negative-outbox-sequence", "op": "replace", "path": "/outboxSequence", "value": "-1"}, + {"name": "numeric-account-generation", "op": "replace", "path": "/accountAuthorityGeneration", "value": 2}, + {"name": "zero-source-version", "op": "replace", "path": "/sourceVersion", "value": "0"}, + {"name": "null-source-version", "op": "replace", "path": "/sourceVersion", "value": null}, + {"name": "null-security-cutoff", "op": "replace", "path": "/accountSecurityCutoff", "value": null}, + {"name": "array-security-cutoff", "op": "replace", "path": "/accountSecurityCutoff", "value": []}, + {"name": "missing-cutoff-sequence", "op": "remove", "path": "/accountSecurityCutoff/outboxSequence"}, + {"name": "extra-cutoff-field", "op": "add", "path": "/accountSecurityCutoff/issuanceFence", "value": "4"}, + {"name": "numeric-cutoff-generation", "op": "replace", "path": "/accountSecurityCutoff/accountAuthorityGeneration", "value": 2}, + {"name": "mismatched-cutoff-generation", "op": "replace", "path": "/accountSecurityCutoff/accountAuthorityGeneration", "value": "3"}, + {"name": "mismatched-cutoff-stream", "op": "replace", "path": "/accountSecurityCutoff/outboxStreamKey", "value": "account:auth-authority:v1:account/22222222-2222-4222-8222-222222222222"}, + {"name": "mismatched-cutoff-sequence", "op": "replace", "path": "/accountSecurityCutoff/outboxSequence", "value": "2"}, + {"name": "unknown-fence-field", "op": "add", "path": "/issuanceFence", "value": "9"}, + {"name": "forbidden-authority-tuple", "op": "add", "path": "/authorityTuple", "value": {}}, + {"name": "forbidden-presented-token-identity", "op": "add", "path": "/tokenHash", "value": "sha256:1111111111111111111111111111111111111111111111111111111111111111"}, + {"name": "forbidden-recipient-tuple", "op": "add", "path": "/recipientAuthorityTuple", "value": {}}, + {"name": "missing-digest", "op": "remove", "path": "/eventDigest"}, + {"name": "malformed-digest", "op": "replace", "path": "/eventDigest", "value": "SHA256:1111111111111111111111111111111111111111111111111111111111111111"}, + {"name": "digest-mismatch", "op": "replace", "path": "/eventDigest", "value": "sha256:1111111111111111111111111111111111111111111111111111111111111111"} + ] +} diff --git a/services/common-platform-core/src/test/resources/net/firedevops/firemud/common/account/authority/account-auth-password-reset-event-v1-vectors.json b/services/common-platform-core/src/test/resources/net/firedevops/firemud/common/account/authority/account-auth-password-reset-event-v1-vectors.json new file mode 100644 index 0000000000..0c2a591b0b --- /dev/null +++ b/services/common-platform-core/src/test/resources/net/firedevops/firemud/common/account/authority/account-auth-password-reset-event-v1-vectors.json @@ -0,0 +1,136 @@ +{ + "schemaVersion": "account-auth-password-reset-event-vectors/v1", + "validEvents": [ + { + "name": "standard-password-reset-cutoff", + "expectedEventDigest": "sha256:9d276449fcd7388ff4dee66f5d69f92c666e15c641ab0f21990104ac9b9bea07", + "expectedCanonicalJson": "{\"accountAuthorityGeneration\":\"7\",\"accountId\":\"018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a\",\"accountSecurityCutoff\":{\"accountAuthorityGeneration\":\"7\",\"outboxSequence\":\"3\",\"outboxStreamKey\":\"account:auth-authority:v1:account/018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a\"},\"eventDigest\":\"sha256:9d276449fcd7388ff4dee66f5d69f92c666e15c641ab0f21990104ac9b9bea07\",\"eventId\":\"password-reset-event-001\",\"eventType\":\"PASSWORD_RESET_COMMITTED\",\"outboxSequence\":\"3\",\"outboxStreamKey\":\"account:auth-authority:v1:account/018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a\",\"requestId\":\"password-reset-request-001\",\"schemaVersion\":\"account-auth-password-reset-event/v1\",\"sourceScope\":\"account/018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a\",\"sourceVersion\":\"12\"}", + "event": { + "schemaVersion": "account-auth-password-reset-event/v1", + "eventType": "PASSWORD_RESET_COMMITTED", + "eventId": "password-reset-event-001", + "requestId": "password-reset-request-001", + "accountId": "018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a", + "sourceScope": "account/018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a", + "outboxStreamKey": "account:auth-authority:v1:account/018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a", + "outboxSequence": "3", + "accountAuthorityGeneration": "7", + "sourceVersion": "12", + "accountSecurityCutoff": { + "accountAuthorityGeneration": "7", + "outboxStreamKey": "account:auth-authority:v1:account/018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a", + "outboxSequence": "3" + }, + "eventDigest": "sha256:9d276449fcd7388ff4dee66f5d69f92c666e15c641ab0f21990104ac9b9bea07" + } + }, + { + "name": "counters-above-javascript-safe-integer-and-signed-long", + "expectedEventDigest": "sha256:2fef25b7ec2fc79dc95e07352e0477214835f09ee287d0233bd937488c8b2f65", + "expectedCanonicalJson": "{\"accountAuthorityGeneration\":\"92233720368547758081234567890123456789\",\"accountId\":\"018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a\",\"accountSecurityCutoff\":{\"accountAuthorityGeneration\":\"92233720368547758081234567890123456789\",\"outboxSequence\":\"18446744073709551616000000000000000001\",\"outboxStreamKey\":\"account:auth-authority:v1:account/018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a\"},\"eventDigest\":\"sha256:2fef25b7ec2fc79dc95e07352e0477214835f09ee287d0233bd937488c8b2f65\",\"eventId\":\"password-reset-event-large-counters\",\"eventType\":\"PASSWORD_RESET_COMMITTED\",\"outboxSequence\":\"18446744073709551616000000000000000001\",\"outboxStreamKey\":\"account:auth-authority:v1:account/018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a\",\"requestId\":\"password-reset-request-large-counters\",\"schemaVersion\":\"account-auth-password-reset-event/v1\",\"sourceScope\":\"account/018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a\",\"sourceVersion\":\"90071992547409931234567890123456789\"}", + "event": { + "schemaVersion": "account-auth-password-reset-event/v1", + "eventType": "PASSWORD_RESET_COMMITTED", + "eventId": "password-reset-event-large-counters", + "requestId": "password-reset-request-large-counters", + "accountId": "018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a", + "sourceScope": "account/018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a", + "outboxStreamKey": "account:auth-authority:v1:account/018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a", + "outboxSequence": "18446744073709551616000000000000000001", + "accountAuthorityGeneration": "92233720368547758081234567890123456789", + "sourceVersion": "90071992547409931234567890123456789", + "accountSecurityCutoff": { + "accountAuthorityGeneration": "92233720368547758081234567890123456789", + "outboxStreamKey": "account:auth-authority:v1:account/018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a", + "outboxSequence": "18446744073709551616000000000000000001" + }, + "eventDigest": "sha256:2fef25b7ec2fc79dc95e07352e0477214835f09ee287d0233bd937488c8b2f65" + } + } + ], + "changedDeclaredFieldMutations": [ + {"name": "event-id", "changes": {"eventId": "password-reset-event-002"}}, + {"name": "request-id", "changes": {"requestId": "password-reset-request-002"}}, + { + "name": "account-identity-and-derived-scope", + "changes": { + "accountId": "018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0b", + "sourceScope": "account/018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0b", + "outboxStreamKey": "account:auth-authority:v1:account/018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0b", + "accountSecurityCutoff": { + "accountAuthorityGeneration": "7", + "outboxStreamKey": "account:auth-authority:v1:account/018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0b", + "outboxSequence": "3" + } + } + }, + { + "name": "outbox-sequence-and-cutoff", + "changes": { + "outboxSequence": "4", + "accountSecurityCutoff": { + "accountAuthorityGeneration": "7", + "outboxStreamKey": "account:auth-authority:v1:account/018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a", + "outboxSequence": "4" + } + } + }, + { + "name": "account-authority-generation-and-cutoff", + "changes": { + "accountAuthorityGeneration": "8", + "accountSecurityCutoff": { + "accountAuthorityGeneration": "8", + "outboxStreamKey": "account:auth-authority:v1:account/018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a", + "outboxSequence": "3" + } + } + }, + {"name": "source-version", "changes": {"sourceVersion": "13"}} + ], + "canonicalReorderedPropertyOrder": [ + "sourceVersion", + "requestId", + "outboxSequence", + "outboxStreamKey", + "eventType", + "eventId", + "eventDigest", + "accountId", + "accountAuthorityGeneration", + "accountSecurityCutoff", + "schemaVersion", + "sourceScope" + ], + "invalidMutations": [ + {"name": "unsupported-schema", "op": "replace", "path": "/schemaVersion", "value": "account-auth-password-reset-event/v2"}, + {"name": "unsupported-event-type", "op": "replace", "path": "/eventType", "value": "PASSWORD_RESET_REQUESTED"}, + {"name": "missing-required-event-id", "op": "remove", "path": "/eventId"}, + {"name": "empty-event-id", "op": "replace", "path": "/eventId", "value": ""}, + {"name": "missing-required-request-id", "op": "remove", "path": "/requestId"}, + {"name": "null-account-id", "op": "replace", "path": "/accountId", "value": null}, + {"name": "nil-account-id", "op": "replace", "path": "/accountId", "value": "00000000-0000-0000-0000-000000000000"}, + {"name": "uppercase-account-id", "op": "replace", "path": "/accountId", "value": "018F8F0A-1A6B-7B13-8D04-5F6E7D8C9B0A"}, + {"name": "mismatched-source-scope", "op": "replace", "path": "/sourceScope", "value": "account/018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0b"}, + {"name": "mismatched-stream-key", "op": "replace", "path": "/outboxStreamKey", "value": "account:auth-authority:v1:account/018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0b"}, + {"name": "numeric-outbox-sequence", "op": "replace", "path": "/outboxSequence", "value": 3}, + {"name": "zero-outbox-sequence", "op": "replace", "path": "/outboxSequence", "value": "0"}, + {"name": "leading-zero-outbox-sequence", "op": "replace", "path": "/outboxSequence", "value": "03"}, + {"name": "negative-outbox-sequence", "op": "replace", "path": "/outboxSequence", "value": "-3"}, + {"name": "exponent-outbox-sequence", "op": "replace", "path": "/outboxSequence", "value": "3e0"}, + {"name": "numeric-account-generation", "op": "replace", "path": "/accountAuthorityGeneration", "value": 7}, + {"name": "zero-source-version", "op": "replace", "path": "/sourceVersion", "value": "0"}, + {"name": "null-security-cutoff", "op": "replace", "path": "/accountSecurityCutoff", "value": null}, + {"name": "missing-cutoff-sequence", "op": "remove", "path": "/accountSecurityCutoff/outboxSequence"}, + {"name": "extra-cutoff-field", "op": "add", "path": "/accountSecurityCutoff/issuanceFence", "value": "4"}, + {"name": "mismatched-cutoff-generation", "op": "replace", "path": "/accountSecurityCutoff/accountAuthorityGeneration", "value": "8"}, + {"name": "mismatched-cutoff-stream", "op": "replace", "path": "/accountSecurityCutoff/outboxStreamKey", "value": "account:auth-authority:v1:account/018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0b"}, + {"name": "mismatched-cutoff-sequence", "op": "replace", "path": "/accountSecurityCutoff/outboxSequence", "value": "4"}, + {"name": "unknown-fence-field", "op": "add", "path": "/issuanceFence", "value": "9"}, + {"name": "forbidden-authority-tuple", "op": "add", "path": "/authorityTuple", "value": {}}, + {"name": "forbidden-credential-material", "op": "add", "path": "/passwordVerifier", "value": "secret"}, + {"name": "missing-digest", "op": "remove", "path": "/eventDigest"}, + {"name": "malformed-digest", "op": "replace", "path": "/eventDigest", "value": "SHA256:1111111111111111111111111111111111111111111111111111111111111111"}, + {"name": "digest-mismatch", "op": "replace", "path": "/eventDigest", "value": "sha256:1111111111111111111111111111111111111111111111111111111111111111"} + ] +} From f3f5ce7cf85281bce9e343bac7e8e07522fe5838 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 7 Oct 2026 10:21:17 +1300 Subject: [PATCH 3/9] fix(account): repair real PostgreSQL source and fence failures --- .../AccountAuthorityOutboxRepository.java | 14 +- ...ccountJwtSignerDesiredStateRepository.java | 4 +- ...ccountJwtValidatorInventoryRepository.java | 41 ++++++ ...account_tenant_authority_source_bridge.sql | 36 ++--- ...V76__draft_commit_authorization_fences.sql | 29 +++- ...orizationFencePostgresIntegrationTest.java | 71 +++++++++ ...rceEvidencePersistenceIntegrationTest.java | 136 ++++++++---------- ...orInventoryPersistenceIntegrationTest.java | 27 ++-- .../AccountAuthorityOutboxRepositoryTest.java | 50 +++++++ .../security/AccountPublicJwksCache.java | 3 +- 10 files changed, 300 insertions(+), 111 deletions(-) diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthorityOutboxRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthorityOutboxRepository.java index 037db96b19..7766cfa838 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthorityOutboxRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthorityOutboxRepository.java @@ -224,7 +224,19 @@ public Optional readCheckpoint(String outboxStreamKey) { if (stream == null) { return Optional.empty(); } - long sequence = requiredPositive(stream, "last_sequence"); + long sequence = requiredNonnegative(stream, "last_sequence"); + if (sequence == 0L) { + Record event = + dsl.fetchOne( + "SELECT outbox_sequence FROM account_authority_outbox_events " + + "WHERE outbox_stream_key = ? LIMIT 1", + outboxStreamKey); + if (event != null) { + throw new IllegalStateException( + "Account authority outbox zero checkpoint has event evidence"); + } + return Optional.empty(); + } Event event = findEvent(outboxStreamKey, sequence) .orElseThrow( diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtSignerDesiredStateRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtSignerDesiredStateRepository.java index 544f4c365f..9391f4492b 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtSignerDesiredStateRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtSignerDesiredStateRepository.java @@ -121,8 +121,8 @@ public DesiredState initialize(Binding binding, EnrollmentIdentity enrollmentIde binding.clusterId(), binding.namespace(), binding.mode().value(), - enrollmentIdentity.expectedClusterIncarnationUid(), - enrollmentIdentity.expectedNamespaceUid(), + UUID.fromString(enrollmentIdentity.expectedClusterIncarnationUid()), + UUID.fromString(enrollmentIdentity.expectedNamespaceUid()), enrollmentIdentity.materializerTrustBindingDigest(), enrollmentIdentity.materializerTrustConfigRevision(), enrollmentIdentity.apiBindingDigest(), diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtValidatorInventoryRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtValidatorInventoryRepository.java index 3cfed267d0..cb6c36ed00 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtValidatorInventoryRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtValidatorInventoryRepository.java @@ -2,6 +2,7 @@ import java.security.MessageDigest; import java.time.Instant; +import java.util.Arrays; import java.util.HexFormat; import java.util.Objects; import java.util.UUID; @@ -223,6 +224,46 @@ public record StoredSnapshot( public byte[] canonicalBytes() { return canonicalBytes.clone(); } + + @Override + public boolean equals(Object other) { + if (this == other) { + return true; + } + if (!(other instanceof StoredSnapshot that)) { + return false; + } + return digest.equals(that.digest) + && environmentId.equals(that.environmentId) + && clusterId.equals(that.clusterId) + && clusterIncarnationUid.equals(that.clusterIncarnationUid) + && namespace.equals(that.namespace) + && namespaceUid.equals(that.namespaceUid) + && apiBindingRevision.equals(that.apiBindingRevision) + && apiBindingDigest.equals(that.apiBindingDigest) + && inventoryBindingRevision.equals(that.inventoryBindingRevision) + && inventoryBindingDigest.equals(that.inventoryBindingDigest) + && observedAt.equals(that.observedAt) + && Arrays.equals(canonicalBytes, that.canonicalBytes); + } + + @Override + public int hashCode() { + return 31 + * Objects.hash( + digest, + environmentId, + clusterId, + clusterIncarnationUid, + namespace, + namespaceUid, + apiBindingRevision, + apiBindingDigest, + inventoryBindingRevision, + inventoryBindingDigest, + observedAt) + + Arrays.hashCode(canonicalBytes); + } } public static final class InventorySnapshotUnavailableException extends RuntimeException { diff --git a/services/account-service/src/main/resources/db/migration/V73__account_tenant_authority_source_bridge.sql b/services/account-service/src/main/resources/db/migration/V73__account_tenant_authority_source_bridge.sql index 8b4bdc5fdd..74a86c8d47 100644 --- a/services/account-service/src/main/resources/db/migration/V73__account_tenant_authority_source_bridge.sql +++ b/services/account-service/src/main/resources/db/migration/V73__account_tenant_authority_source_bridge.sql @@ -174,10 +174,11 @@ BEGIN RAISE EXCEPTION 'Tenant authority source must advance one exact immutable event' USING ERRCODE = '23514', CONSTRAINT = 'account_tenant_authority_source_monotonic'; END IF; - SELECT event_id, event_digest, payload INTO authority_event - FROM account_authority_outbox_events - WHERE outbox_stream_key = NEW.outbox_stream_key - AND outbox_sequence = NEW.last_outbox_sequence; + SELECT authority_event_row.event_id, authority_event_row.event_digest, + authority_event_row.payload INTO authority_event + FROM account_authority_outbox_events AS authority_event_row + WHERE authority_event_row.outbox_stream_key = NEW.outbox_stream_key + AND authority_event_row.outbox_sequence = NEW.last_outbox_sequence; IF authority_event.event_id IS DISTINCT FROM NEW.last_event_id OR authority_event.event_digest IS DISTINCT FROM NEW.last_event_digest THEN RAISE EXCEPTION 'Tenant authority source head differs from its exact event' @@ -221,10 +222,11 @@ BEGIN RAISE EXCEPTION 'Tenant authority event differs from fresh Game Design source evidence' USING ERRCODE = '23514', CONSTRAINT = 'account_tenant_authority_source_evidence'; END IF; - SELECT event_id, event_digest, payload INTO billing_event - FROM account_tenant_entitlement_outbox_events - WHERE tenant_uuid = NEW.tenant_uuid - AND tenant_billing_sequence = NEW.tenant_billing_sequence; + SELECT billing_event_row.event_id, billing_event_row.event_digest, + billing_event_row.payload INTO billing_event + FROM account_tenant_entitlement_outbox_events AS billing_event_row + WHERE billing_event_row.tenant_uuid = NEW.tenant_uuid + AND billing_event_row.tenant_billing_sequence = NEW.tenant_billing_sequence; IF billing_event.event_id IS DISTINCT FROM NEW.tenant_billing_event_id OR billing_event.event_digest IS DISTINCT FROM NEW.tenant_billing_event_digest THEN RAISE EXCEPTION 'Tenant authority event does not link to the exact tenant billing event' @@ -357,10 +359,11 @@ BEGIN RAISE EXCEPTION 'Demo entitlement tenant authority event has the wrong scope' USING ERRCODE = '23514', CONSTRAINT = 'account_demo_entitlement_authority_scope'; END IF; - SELECT event_id, event_digest, payload INTO authority_event - FROM account_authority_outbox_events - WHERE outbox_stream_key = NEW.tenant_authority_outbox_stream_key - AND outbox_sequence = NEW.tenant_authority_outbox_sequence; + SELECT authority_event_row.event_id, authority_event_row.event_digest, + authority_event_row.payload INTO authority_event + FROM account_authority_outbox_events AS authority_event_row + WHERE authority_event_row.outbox_stream_key = NEW.tenant_authority_outbox_stream_key + AND authority_event_row.outbox_sequence = NEW.tenant_authority_outbox_sequence; IF authority_event.event_id IS DISTINCT FROM NEW.tenant_authority_event_id OR authority_event.event_digest IS DISTINCT FROM NEW.tenant_authority_event_digest THEN RAISE EXCEPTION 'Demo entitlement authority receipt differs from its exact source event' @@ -412,10 +415,11 @@ BEGIN RAISE EXCEPTION 'Committed demo receipt requires its exact tenant authority checkpoint' USING ERRCODE = '23514', CONSTRAINT = 'account_demo_entitlement_authority_receipt_required'; END IF; - SELECT event_id, event_digest, payload INTO authority_event - FROM account_authority_outbox_events - WHERE outbox_stream_key = NEW.tenant_authority_outbox_stream_key - AND outbox_sequence = NEW.tenant_authority_outbox_sequence; + SELECT authority_event_row.event_id, authority_event_row.event_digest, + authority_event_row.payload INTO authority_event + FROM account_authority_outbox_events AS authority_event_row + WHERE authority_event_row.outbox_stream_key = NEW.tenant_authority_outbox_stream_key + AND authority_event_row.outbox_sequence = NEW.tenant_authority_outbox_sequence; IF authority_event.event_id IS DISTINCT FROM NEW.tenant_authority_event_id OR authority_event.event_digest IS DISTINCT FROM NEW.tenant_authority_event_digest THEN RAISE EXCEPTION 'Committed demo receipt authority event differs from Account outbox' diff --git a/services/account-service/src/main/resources/db/migration/V76__draft_commit_authorization_fences.sql b/services/account-service/src/main/resources/db/migration/V76__draft_commit_authorization_fences.sql index e0fb5be03a..6cfd73f856 100644 --- a/services/account-service/src/main/resources/db/migration/V76__draft_commit_authorization_fences.sql +++ b/services/account-service/src/main/resources/db/migration/V76__draft_commit_authorization_fences.sql @@ -36,10 +36,26 @@ CREATE TABLE account_draft_authorization_owner_readbacks ( CREATE TABLE account_draft_authorization_source_changes ( change_id UUID PRIMARY KEY, binding BYTEA NOT NULL CHECK (octet_length(binding) > 0), - status VARCHAR(16) NOT NULL CHECK (status IN ('WAITING', 'SOURCE_COMMITTED')), + status VARCHAR(16) NOT NULL + CHECK (status IN ('WAITING', 'SOURCE_COMMITTED', 'SOURCE_ABORTED')), requested_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, committed_at TIMESTAMPTZ, - CHECK ((status = 'WAITING') = (committed_at IS NULL)) + aborted_at TIMESTAMPTZ, + abort_reason VARCHAR(32) CHECK (abort_reason IN ('EXPIRED', 'DEFINITIVE_ABORT')), + CHECK ( + (status = 'WAITING' + AND committed_at IS NULL + AND aborted_at IS NULL + AND abort_reason IS NULL) + OR (status = 'SOURCE_COMMITTED' + AND committed_at IS NOT NULL + AND aborted_at IS NULL + AND abort_reason IS NULL) + OR (status = 'SOURCE_ABORTED' + AND committed_at IS NULL + AND aborted_at IS NOT NULL + AND abort_reason IS NOT NULL) + ) ); CREATE TABLE account_draft_authorization_changed_scopes ( @@ -85,11 +101,16 @@ BEGIN IF TG_OP = 'DELETE' THEN RAISE EXCEPTION 'Draft source change cannot be deleted'; END IF; - IF OLD.status <> 'WAITING' OR NEW.status <> 'SOURCE_COMMITTED' + IF OLD.status <> 'WAITING' OR NEW.status NOT IN ('SOURCE_COMMITTED', 'SOURCE_ABORTED') OR NEW.change_id IS DISTINCT FROM OLD.change_id OR NEW.binding IS DISTINCT FROM OLD.binding OR NEW.requested_at IS DISTINCT FROM OLD.requested_at - OR NEW.committed_at IS NULL THEN + OR (NEW.status = 'SOURCE_COMMITTED' + AND (NEW.committed_at IS NULL OR NEW.aborted_at IS NOT NULL OR NEW.abort_reason IS NOT NULL)) + OR (NEW.status = 'SOURCE_ABORTED' + AND (NEW.committed_at IS NOT NULL OR NEW.aborted_at IS NULL + OR NEW.abort_reason IS NULL + OR NEW.abort_reason NOT IN ('EXPIRED', 'DEFINITIVE_ABORT'))) THEN RAISE EXCEPTION 'Draft source change result is immutable'; END IF; IF EXISTS ( diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFencePostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFencePostgresIntegrationTest.java index c1e9720f24..4a398c04dc 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFencePostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFencePostgresIntegrationTest.java @@ -21,6 +21,7 @@ import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository.Ordering; import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository.Settlement; import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository.SourceChange; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository.SourceChangeAbortReason; import net.firedevops.firemud.common.authoring.DraftCommitBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; @@ -75,6 +76,76 @@ void revokeBeforeCommitDeniesDelayedRequestsUntilBothDefinitiveAborts() { .isInstanceOf(IllegalStateException.class); } + @Test + void abortedSourceChangeRetainsExactTerminalReasonAndCannotReopenOrBecomeMalformed() { + Context context = context(); + DraftAuthorizationFenceBinding binding = binding(); + SourceChange change = change(binding); + tx(context, () -> context.repository().reserve(binding)); + assertThat(tx(context, () -> context.repository().requestSourceChange(change))).isFalse(); + assertThat(tx(context, () -> context.repository().sourceAbortPermitted(change))).isFalse(); + owner(context, binding, Owner.WORLD, Outcome.DEFINITIVELY_ABORTED, new byte[] {31}); + owner(context, binding, Owner.GAME_DESIGN, Outcome.DEFINITIVELY_ABORTED, new byte[] {32}); + assertThat(tx(context, () -> context.repository().sourceAbortPermitted(change))).isTrue(); + + tx( + context, + () -> { + context.repository().markSourceAborted(change, SourceChangeAbortReason.EXPIRED); + return null; + }); + var aborted = tx(context, () -> context.repository().readSourceChange(change)); + assertThat(aborted.status()).isEqualTo("SOURCE_ABORTED"); + assertThat(aborted.committedAt()).isNull(); + assertThat(aborted.abortedAt()).isNotNull(); + assertThat(aborted.abortReason()).isEqualTo(SourceChangeAbortReason.EXPIRED); + + tx( + context, + () -> { + context.repository().markSourceAborted(change, SourceChangeAbortReason.EXPIRED); + return null; + }); + assertThatThrownBy( + () -> + tx( + context, + () -> { + context + .repository() + .markSourceAborted(change, SourceChangeAbortReason.DEFINITIVE_ABORT); + return null; + })) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + tx( + context, + () -> + context + .dsl() + .execute( + "UPDATE account_draft_authorization_source_changes" + + " SET status = 'WAITING', aborted_at = NULL, abort_reason = NULL" + + " WHERE change_id = ?", + change.changeId()))) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + tx( + context, + () -> + context + .dsl() + .execute( + "INSERT INTO account_draft_authorization_source_changes" + + " (change_id, binding, status, aborted_at, abort_reason)" + + " VALUES (?, ?, 'SOURCE_ABORTED', NULL, NULL)", + UUID.randomUUID(), + new byte[] {1}))) + .isInstanceOf(DataAccessException.class); + } + @Test void worldCommittedAndGameDesignUnknownSurviveRestartAndBlockSourceUntilExactBothReadbacks() { Context context = context(); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java index 417f79eee9..9519ddc7f8 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java @@ -5,7 +5,6 @@ import java.nio.charset.StandardCharsets; import java.util.Objects; -import java.util.Optional; import java.util.UUID; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CountDownLatch; @@ -53,7 +52,8 @@ static void stopOwnedContainer() { } @Test - void freshAccountBaselineAndSecurityMutationsCommitExactSourceEvidence() throws Exception { + void freshAccountBaselineIsValidButGenericSaveHistoryCannotAuthorizeSecurityCurrentness() + throws Exception { TestContext context = newTestContext(); DSLContext dsl = context.dsl(); TransactionTemplate transaction = context.transaction(); @@ -109,29 +109,17 @@ void freshAccountBaselineAndSecurityMutationsCommitExactSourceEvidence() throws account.setEmailVerified(true); transaction.executeWithoutResult(status -> accounts.save(account)); - var changed = - transaction.execute( - status -> sources.readCurrentIssuerAccountSources(ISSUER, account.getAccountUuid())); - assertThat(changed.account().generation()).isEqualTo(3L); - assertThat(changed.account().sourceVersion()).isEqualTo(3L); - assertThat(changed.account().issuanceFence().value()).isEqualTo(3L); - assertThat(changed.account().checkpoint().sequence()).isEqualTo(2L); - assertThat(changed.account().accountSecurityCutoff()).isPresent(); - assertThat(changed.account().accountSecurityCutoff().orElseThrow().accountAuthorityGeneration()) - .isEqualTo("3"); - assertThat(changed.account().accountSecurityCutoff().orElseThrow().outboxSequence()) - .isEqualTo("2"); + String streamKey = + AccountAuthoritySourceEventV1Codec.EVENT_STREAM_PREFIX + + "account/" + + account.getAccountUuid(); AccountEvent passwordReset = (AccountEvent) AccountAuthoritySourceEventV1Codec.verify( new String( transaction.execute( - status -> - outbox - .findEvent(changed.account().checkpoint().outboxStreamKey(), 1L) - .orElseThrow() - .payload()), - java.nio.charset.StandardCharsets.UTF_8)); + status -> outbox.findEvent(streamKey, 1L).orElseThrow().payload()), + StandardCharsets.UTF_8)); assertThat(passwordReset.mutationKinds()).containsExactly("PASSWORD_RESET"); assertThat(passwordReset.canonicalJson()).doesNotContain("changed-password-hash-not-for-event"); AccountEvent latest = @@ -139,15 +127,17 @@ void freshAccountBaselineAndSecurityMutationsCommitExactSourceEvidence() throws AccountAuthoritySourceEventV1Codec.verify( new String( transaction.execute( - status -> - outbox - .findEvent(changed.account().checkpoint().outboxStreamKey(), 2L) - .orElseThrow() - .payload()), - java.nio.charset.StandardCharsets.UTF_8)); + status -> outbox.findEvent(streamKey, 2L).orElseThrow().payload()), + StandardCharsets.UTF_8)); assertThat(latest.mutationKinds()).containsExactly("EMAIL_LOGIN_ELIGIBILITY_CHANGED"); - assertThat(latest.accountSecurityCutoff().outboxSequence()).isEqualTo("2"); assertThat(latest.canonicalJson()).doesNotContain("changed-password-hash-not-for-event"); + assertThatThrownBy( + () -> + transaction.execute( + status -> + sources.readCurrentIssuerAccountSources(ISSUER, account.getAccountUuid()))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Account source event schema is unsupported"); Account rollbackAttempt = accounts.findByAccountUuid(account.getAccountUuid()).orElseThrow(); rollbackAttempt.setPasswordHash("rollback-only-password-hash"); @@ -160,40 +150,36 @@ void freshAccountBaselineAndSecurityMutationsCommitExactSourceEvidence() throws })) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("force Account source event rollback"); - var afterRollback = - transaction.execute( - status -> sources.readCurrentIssuerAccountSources(ISSUER, account.getAccountUuid())); + assertThat(accounts.findByAccountUuid(account.getAccountUuid()).orElseThrow().getPasswordHash()) + .isEqualTo("changed-password-hash-not-for-event"); + var rolledBackEvent = transaction.execute(status -> outbox.findEvent(streamKey, 3L)); + assertThat(rolledBackEvent).isEmpty(); assertThat( accounts.findByAccountUuid(account.getAccountUuid()).orElseThrow().getLifecycleState()) .isEqualTo(AccountLifecycleState.ACTIVE); - assertThat(afterRollback.account().generation()).isEqualTo(3L); - assertThat(afterRollback.account().issuanceFence().value()).isEqualTo(3L); - assertThat(afterRollback.account().checkpoint().sequence()).isEqualTo(2L); - assertThat(afterRollback.account().accountSecurityCutoff().orElseThrow().outboxSequence()) - .isEqualTo("2"); - Optional rolledBackEvent = - transaction.execute( - status -> outbox.findEvent(changed.account().checkpoint().outboxStreamKey(), 3L)); - assertThat(rolledBackEvent).isEmpty(); + assertThatThrownBy( + () -> + transaction.execute( + status -> + sources.readCurrentIssuerAccountSources(ISSUER, account.getAccountUuid()))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Account source event schema is unsupported"); Account lifecycleUpdate = accounts.findByAccountUuid(account.getAccountUuid()).orElseThrow(); lifecycleUpdate.setLifecycleState(AccountLifecycleState.SECURITY_LOCKED); transaction.executeWithoutResult(status -> accounts.save(lifecycleUpdate)); - var afterLifecycleUpdate = - transaction.execute( - status -> sources.readCurrentIssuerAccountSources(ISSUER, account.getAccountUuid())); assertThat( accounts.findByAccountUuid(account.getAccountUuid()).orElseThrow().getLifecycleState()) .isEqualTo(AccountLifecycleState.ACTIVE); assertThat(lifecycleUpdate.getLifecycleState()).isEqualTo(AccountLifecycleState.ACTIVE); - assertThat(afterLifecycleUpdate.account().generation()).isEqualTo(3L); - assertThat(afterLifecycleUpdate.account().issuanceFence().value()).isEqualTo(3L); - assertThat(afterLifecycleUpdate.account().checkpoint().sequence()).isEqualTo(2L); - var absentLifecycleEvent = - transaction.execute( - status -> - outbox.findEvent( - afterLifecycleUpdate.account().checkpoint().outboxStreamKey(), 3L)); + var absentLifecycleEvent = transaction.execute(status -> outbox.findEvent(streamKey, 3L)); assertThat(absentLifecycleEvent).isEmpty(); + assertThatThrownBy( + () -> + transaction.execute( + status -> + sources.readCurrentIssuerAccountSources(ISSUER, account.getAccountUuid()))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Account source event schema is unsupported"); assertThatThrownBy(() -> accounts.delete(account)) .isInstanceOf(IllegalStateException.class) @@ -210,7 +196,7 @@ void freshAccountBaselineAndSecurityMutationsCommitExactSourceEvidence() throws } @Test - void freshAccountWithNullGlobalRoleCanCommitSecurityMutationSourceEvent() { + void genericSaveHistoryWithNullGlobalRoleDoesNotAuthorizeCanonicalCurrentness() { TestContext context = newTestContext(); DSLContext dsl = context.dsl(); TransactionTemplate transaction = context.transaction(); @@ -231,16 +217,12 @@ void freshAccountWithNullGlobalRoleCanCommitSecurityMutationSourceEvent() { account.setPasswordHash("changed-null-role-account-password-hash"); transaction.executeWithoutResult(status -> accounts.save(account)); - var changed = - transaction.execute( - status -> sources.readCurrentIssuerAccountSources(ISSUER, account.getAccountUuid())); - assertThat(changed.account().checkpoint().sequence()).isEqualTo(1L); + String streamKey = + AccountAuthoritySourceEventV1Codec.EVENT_STREAM_PREFIX + + "account/" + + account.getAccountUuid(); AccountAuthorityOutboxRepository.Event storedEvent = - transaction.execute( - status -> - outbox - .findEvent(changed.account().checkpoint().outboxStreamKey(), 1L) - .orElseThrow()); + transaction.execute(status -> outbox.findEvent(streamKey, 1L).orElseThrow()); AccountEvent event = (AccountEvent) AccountAuthoritySourceEventV1Codec.verify( @@ -250,6 +232,13 @@ void freshAccountWithNullGlobalRoleCanCommitSecurityMutationSourceEvent() { assertThat(event.accountState().globalRole()).isNull(); assertThat(event.canonicalJson()).contains("\"globalRole\":null"); assertThat(event.canonicalJson()).doesNotContain("changed-null-role-account-password-hash"); + assertThatThrownBy( + () -> + transaction.execute( + status -> + sources.readCurrentIssuerAccountSources(ISSUER, account.getAccountUuid()))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Account source event schema is unsupported"); } @Test @@ -409,32 +398,23 @@ void concurrentAccountMutationAndAuthorityReadUseAccountRowBeforeGenerationLocks awaitLockWait(dsl, readerPid, writerPid); releaseWriter.countDown(); writer.get(45, TimeUnit.SECONDS); - var readback = snapshot.get(45, TimeUnit.SECONDS); - assertThat(readback.account().generation()).isEqualTo(2L); - assertThat(readback.account().sourceVersion()).isEqualTo(2L); - assertThat(readback.account().issuanceFence().value()).isEqualTo(2L); - assertThat(readback.account().issuanceFence().sourceVersion()).isEqualTo(2L); - assertThat(readback.account().checkpoint().sequence()).isEqualTo(1L); + assertThatThrownBy(() -> snapshot.get(45, TimeUnit.SECONDS)) + .isInstanceOf(java.util.concurrent.ExecutionException.class) + .hasRootCauseMessage("Account source event schema is unsupported"); + String streamKey = + AccountAuthoritySourceEventV1Codec.EVENT_STREAM_PREFIX + + "account/" + + account.getAccountUuid(); AccountAuthorityOutboxRepository.Event committedEvent = - transaction.execute( - status -> - outbox - .findEvent(readback.account().checkpoint().outboxStreamKey(), 1L) - .orElseThrow()); - assertThat(committedEvent.eventId()) - .isEqualTo(readback.account().checkpoint().sourceEventId().orElseThrow()); - assertThat(committedEvent.eventDigest()) - .isEqualTo(readback.account().checkpoint().sourceEventDigest().orElseThrow()); + transaction.execute(status -> outbox.findEvent(streamKey, 1L).orElseThrow()); AccountEvent event = (AccountEvent) AccountAuthoritySourceEventV1Codec.verify( new String(committedEvent.payload(), StandardCharsets.UTF_8)); assertThat(event.accountId()).isEqualTo(account.getAccountUuid().toString()); assertThat(event.outboxSequence()).isEqualTo("1"); - assertThat(event.accountAuthorityGeneration()).isEqualTo("2"); - assertThat(event.sourceVersion()).isEqualTo("2"); - assertThat(event.issuanceFence()).isEqualTo("2"); assertThat(event.mutationKinds()).containsExactly("PASSWORD_RESET"); + assertThat(event.canonicalJson()).doesNotContain("lock-order-updated-hash"); } finally { startLockPhase.countDown(); releaseWriter.countDown(); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountJwtValidatorInventoryPersistenceIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountJwtValidatorInventoryPersistenceIntegrationTest.java index b7af26883f..f44d7fd6f5 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountJwtValidatorInventoryPersistenceIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountJwtValidatorInventoryPersistenceIntegrationTest.java @@ -131,20 +131,29 @@ void differentBytesCannotReuseAStoredDigestAndWrongOwnerIdentityIsDenied() throw new AccountJwtValidatorInventoryRepository(context.dsl()); InventorySnapshot candidate = snapshot(); inTransaction(context, () -> repository.persistOrReadback(candidate, BINDING, trust())); + Instant observedAt = candidate.observedAt(); + String environmentId = candidate.environmentId(); + String namespace = candidate.namespace(); + String apiBindingRevision = candidate.apiBindingRevision(); + String apiBindingDigest = candidate.apiBindingDigest(); + String inventoryBindingRevision = candidate.inventoryBindingRevision(); + String inventoryBindingDigest = candidate.inventoryBindingDigest(); + String digest = candidate.digest(); + byte[] canonicalBytes = candidate.canonicalBytes(); InventorySnapshot wrongIdentity = mock(InventorySnapshot.class); - when(wrongIdentity.observedAt()).thenReturn(candidate.observedAt()); - when(wrongIdentity.environmentId()).thenReturn(candidate.environmentId()); + when(wrongIdentity.observedAt()).thenReturn(observedAt); + when(wrongIdentity.environmentId()).thenReturn(environmentId); when(wrongIdentity.clusterId()).thenReturn("other-cluster"); when(wrongIdentity.clusterIncarnationUid()).thenReturn(CLUSTER_UID); - when(wrongIdentity.namespace()).thenReturn(candidate.namespace()); + when(wrongIdentity.namespace()).thenReturn(namespace); when(wrongIdentity.namespaceUid()).thenReturn(NAMESPACE_UID); - when(wrongIdentity.apiBindingRevision()).thenReturn(candidate.apiBindingRevision()); - when(wrongIdentity.apiBindingDigest()).thenReturn(candidate.apiBindingDigest()); - when(wrongIdentity.inventoryBindingRevision()).thenReturn(candidate.inventoryBindingRevision()); - when(wrongIdentity.inventoryBindingDigest()).thenReturn(candidate.inventoryBindingDigest()); - when(wrongIdentity.digest()).thenReturn(candidate.digest()); - when(wrongIdentity.canonicalBytes()).thenReturn(candidate.canonicalBytes()); + when(wrongIdentity.apiBindingRevision()).thenReturn(apiBindingRevision); + when(wrongIdentity.apiBindingDigest()).thenReturn(apiBindingDigest); + when(wrongIdentity.inventoryBindingRevision()).thenReturn(inventoryBindingRevision); + when(wrongIdentity.inventoryBindingDigest()).thenReturn(inventoryBindingDigest); + when(wrongIdentity.digest()).thenReturn(digest); + when(wrongIdentity.canonicalBytes()).thenReturn(canonicalBytes); assertThatThrownBy( () -> diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthorityOutboxRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthorityOutboxRepositoryTest.java index d31f2c9c79..fbc00c6dcb 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthorityOutboxRepositoryTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthorityOutboxRepositoryTest.java @@ -261,6 +261,56 @@ void positiveCheckpointReadbackReturnsItsExactEventIdentityAndDigest() { .contains(new Checkpoint(streamKey, 2L, "event-2", "canonical-digest-2")); } + @Test + void emptyZeroSequenceStreamHasNoPositiveCheckpoint() { + String streamKey = "account:auth-authority:v1:membership/account-a/tenant-a"; + Record stream = streamRecord(0L); + when(dsl.fetchOne(anyString(), any(Object[].class))) + .thenAnswer( + invocation -> + invocation.getArgument(0).startsWith("SELECT last_sequence") + ? stream + : null); + + assertThat(repository.readCheckpoint(streamKey)).isEmpty(); + verify(dsl) + .fetchOne( + startsWith("SELECT outbox_sequence FROM account_authority_outbox_events"), + any(Object[].class)); + } + + @Test + void zeroSequenceStreamWithAnyEventEvidenceIsCorrupt() { + String streamKey = "account:auth-authority:v1:membership/account-a/tenant-a"; + Record stream = streamRecord(0L); + Record event = mock(Record.class); + when(dsl.fetchOne(anyString(), any(Object[].class))) + .thenAnswer( + invocation -> + invocation.getArgument(0).startsWith("SELECT last_sequence") + ? stream + : event); + + assertThatThrownBy(() -> repository.readCheckpoint(streamKey)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("zero checkpoint has event evidence"); + } + + @Test + void negativeSequenceHeadIsRejectedBeforeEventEvidenceCanBePromoted() { + String streamKey = "account:auth-authority:v1:membership/account-a/tenant-a"; + Record negativeStream = streamRecord(-1L); + when(dsl.fetchOne(anyString(), any(Object[].class))).thenReturn(negativeStream); + + assertThatThrownBy(() -> repository.readCheckpoint(streamKey)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("last_sequence"); + verify(dsl, never()) + .fetchOne( + startsWith("SELECT outbox_sequence FROM account_authority_outbox_events"), + any(Object[].class)); + } + @Test void requestReadbackFindsAnExactHistoricalEventInItsStream() { String streamKey = "account:auth-authority:v1:membership/account-a/tenant-a"; diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/security/AccountPublicJwksCache.java b/services/common-security/src/main/java/net/firedevops/firemud/common/security/AccountPublicJwksCache.java index 9779fbc4f4..9f10bce0d3 100644 --- a/services/common-security/src/main/java/net/firedevops/firemud/common/security/AccountPublicJwksCache.java +++ b/services/common-security/src/main/java/net/firedevops/firemud/common/security/AccountPublicJwksCache.java @@ -6,6 +6,7 @@ import java.nio.charset.CharacterCodingException; import java.nio.charset.CodingErrorAction; import java.nio.charset.StandardCharsets; +import java.security.GeneralSecurityException; import java.security.KeyFactory; import java.security.MessageDigest; import java.security.interfaces.RSAPublicKey; @@ -276,7 +277,7 @@ private static Map parseJwks(byte[] bytes) { return parsed; } catch (InvalidJwksException ex) { throw ex; - } catch (Exception ex) { + } catch (GeneralSecurityException | RuntimeException ex) { throw new InvalidJwksException(); } } From 2f43d2a8281342648aae1b6841785ce51bedd9f5 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 7 Oct 2026 11:43:03 +1300 Subject: [PATCH 4/9] Correct canonical issuer source and deferred tenant authority proof --- .../service/IssuerGenerationProjection.java | 26 ++++-- ...account_tenant_authority_source_bridge.sql | 11 ++- ...StateOperationPostgresIntegrationTest.java | 4 +- ...EntitlementPersistenceIntegrationTest.java | 48 ++++++++++ .../IssuerGenerationProjectionTest.java | 93 +++++++++++++------ 5 files changed, 144 insertions(+), 38 deletions(-) diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/IssuerGenerationProjection.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/IssuerGenerationProjection.java index 543a77eea2..d93ca57ec9 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/IssuerGenerationProjection.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/IssuerGenerationProjection.java @@ -14,7 +14,8 @@ import java.util.Set; import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeKind; import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository.CurrentSourceEvidence; -import net.firedevops.firemud.common.account.authority.IssuerGenerationAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.AccountAuthoritySourceEventV1Codec; +import net.firedevops.firemud.common.account.authority.AccountAuthoritySourceEventV1Codec.IssuerEvent; import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; /** Closed Account-owned current issuer projection; not recipient or token authorization. */ @@ -85,10 +86,13 @@ public record IssuerGenerationProjection( throw new IllegalArgumentException( "Advanced issuer projection requires complete event evidence"); } - var event = IssuerGenerationAuthorityEventV1Codec.verify(sourceEvent.orElseThrow()); + var verified = AccountAuthoritySourceEventV1Codec.verify(sourceEvent.orElseThrow()); + if (!(verified instanceof IssuerEvent event)) { + throw new IllegalArgumentException("Issuer projection source event is not an issuer event"); + } if (!sourceEvent.orElseThrow().equals(event.canonicalJson()) + || !event.eventId().equals(event.requestId()) || !issuerId.equals(event.issuerId()) - || !("issuer/" + issuerId).equals(event.sourceScope()) || !issuerAuthGeneration.equals(event.issuerAuthGeneration()) || !sourceVersion.equals(event.sourceVersion()) || !outboxStreamKey.equals(event.outboxStreamKey()) @@ -116,18 +120,28 @@ public static IssuerGenerationProjection fromSource( throw new IllegalArgumentException("Issuer source enrollment is unavailable"); } var stored = snapshot.latestEvent().orElseThrow(); - var event = - IssuerGenerationAuthorityEventV1Codec.verify( + var verified = + AccountAuthoritySourceEventV1Codec.verify( new String(stored.payload(), java.nio.charset.StandardCharsets.UTF_8)); + if (!(verified instanceof IssuerEvent event)) { + throw new IllegalArgumentException( + "Issuer source checkpoint does not contain an issuer event"); + } if (!java.util.Arrays.equals(stored.payload(), event.canonicalJsonUtf8()) || !stored.outboxStreamKey().equals(source.checkpoint().outboxStreamKey()) || stored.outboxSequence() != source.checkpoint().sequence() + || !event.outboxStreamKey().equals(source.checkpoint().outboxStreamKey()) + || !event.outboxSequence().equals(Long.toString(source.checkpoint().sequence())) + || !event.issuerId().equals(source.scope().issuerId()) + || !event.issuerAuthGeneration().equals(Long.toString(source.generation())) + || !event.sourceVersion().equals(Long.toString(source.sourceVersion())) || !source.checkpoint().sourceEventId().equals(Optional.of(stored.eventId())) || !source.checkpoint().sourceEventDigest().equals(Optional.of(stored.eventDigest())) || !stored.eventId().equals(event.eventId()) || !stored.eventDigest().equals(event.eventDigest()) || !stored.requestId().equals(event.requestId()) - || !stored.eventId().equals("account-issuer-authority-event-v1:" + stored.requestId())) { + || !stored.eventId().equals(stored.requestId()) + || !event.eventId().equals(event.requestId())) { throw new IllegalArgumentException( "Issuer projection event differs from the owned checkpoint"); } diff --git a/services/account-service/src/main/resources/db/migration/V73__account_tenant_authority_source_bridge.sql b/services/account-service/src/main/resources/db/migration/V73__account_tenant_authority_source_bridge.sql index 74a86c8d47..1b641d4d2e 100644 --- a/services/account-service/src/main/resources/db/migration/V73__account_tenant_authority_source_bridge.sql +++ b/services/account-service/src/main/resources/db/migration/V73__account_tenant_authority_source_bridge.sql @@ -322,14 +322,21 @@ LANGUAGE plpgsql AS $$ DECLARE source_row RECORD; + stream_head BIGINT; BEGIN IF left(NEW.outbox_stream_key, length('account:auth-authority:v1:tenant/')) = 'account:auth-authority:v1:tenant/' THEN + -- This is deferred: the queued NEW image may be the temporary sequence-zero row + -- created while the first source head is enrolled. Validate the final live head instead. + SELECT last_sequence INTO stream_head + FROM account_authority_outbox_streams + WHERE outbox_stream_key = NEW.outbox_stream_key; SELECT last_outbox_sequence INTO source_row FROM account_tenant_authority_source_records WHERE outbox_stream_key = NEW.outbox_stream_key; - IF source_row.last_outbox_sequence IS DISTINCT FROM NEW.last_sequence - OR NEW.last_sequence <= 0 THEN + IF stream_head IS NULL + OR source_row.last_outbox_sequence IS DISTINCT FROM stream_head + OR stream_head <= 0 THEN RAISE EXCEPTION 'Tenant authority outbox head lacks an Account-owned source checkpoint' USING ERRCODE = '23514', CONSTRAINT = 'account_tenant_authority_stream_source'; END IF; diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountSecurityStateOperationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountSecurityStateOperationPostgresIntegrationTest.java index 00842039a6..d13101f363 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountSecurityStateOperationPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountSecurityStateOperationPostgresIntegrationTest.java @@ -18,6 +18,7 @@ import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository.SourceChange; import net.firedevops.firemud.accountservice.dto.AccountSecurityStateMutationRequest; import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.entity.AccountLoginAuthModes; import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeState; @@ -776,7 +777,8 @@ private Event producerFixture( .execute( "UPDATE accounts SET email_verified = ?, login_auth_modes = ?, lifecycle_state = ? WHERE account_uuid = ?", pending.request().desiredState().emailVerified(), - String.join(",", pending.request().desiredState().loginAuthModes()), + AccountLoginAuthModes.normalize( + String.join(",", pending.request().desiredState().loginAuthModes())), pending .request() .desiredState() diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementPersistenceIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementPersistenceIntegrationTest.java index a8a60b82dc..2ab0469135 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementPersistenceIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementPersistenceIntegrationTest.java @@ -61,6 +61,54 @@ static void stopPostgresFixture() { } } + @Test + void sequenceZeroTenantAuthorityHeadCannotCommit() { + TestContext context = newTestContext(); + FreshTenantIdentityAssociationRepository identityRepository = + new FreshTenantIdentityAssociationRepository(context.dsl(), TEST_NAMESPACE); + AccountAuthorityGenerationRepository generationRepository = + new AccountAuthorityGenerationRepository(context.dsl()); + AccountTenantEntitlementOutboxRepository billingOutbox = + new AccountTenantEntitlementOutboxRepository(context.dsl()); + AccountTenantAuthorityEventRepository tenantAuthorityEvents = + new AccountTenantAuthorityEventRepository( + context.dsl(), + new AccountAuthorityOutboxRepository(context.dsl()), + billingOutbox, + identityRepository, + generationRepository); + UUID tenantId = UUID.fromString("88888888-8888-4888-8888-888888888888"); + UUID requestId = UUID.fromString("88888888-8888-4888-8888-888888888889"); + FreshTenantCreationEvidence source = evidence(tenantId, 805L); + inTransaction( + context.transaction(), + () -> { + identityRepository.importVerified(source); + generationRepository.initializeTenantIfAbsent(tenantId); + return null; + }); + + assertThatThrownBy( + () -> + inTransaction( + context.transaction(), + () -> { + tenantAuthorityEvents.establishFirstEventSource( + tenantId, + requestId, + source, + generationRepository.read( + AccountAuthorityGenerationRepository.AuthorityScope.tenant(tenantId))); + context + .dsl() + .execute( + "SET CONSTRAINTS account_tenant_authority_stream_consistency IMMEDIATE"); + return null; + })) + .hasRootCauseMessage( + "ERROR: Tenant authority outbox head lacks an Account-owned source checkpoint"); + } + @Test void exactFreshUuidReplayConflictQuotasAndGenerationChangeAreTransactionallyFenced() { TestContext context = newTestContext(); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/IssuerGenerationProjectionTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/IssuerGenerationProjectionTest.java index b33285952f..b4da090d67 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/IssuerGenerationProjectionTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/IssuerGenerationProjectionTest.java @@ -4,10 +4,10 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.math.BigInteger; -import java.util.Map; import java.util.Optional; import net.firedevops.firemud.accountservice.service.IssuerGenerationProjection; -import net.firedevops.firemud.common.account.authority.IssuerGenerationAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.AccountAuthoritySourceEventV1Codec; +import net.firedevops.firemud.common.account.authority.AccountAuthoritySourceEventV1Codec.IssuerPreimage; import org.junit.jupiter.api.Test; class IssuerGenerationProjectionTest { @@ -17,18 +17,9 @@ void ownedAdvancedSourceKeepsCanonicalOriginalBytesAndRejectsCheckpointContradic String request = java.util.UUID.randomUUID().toString(); String stream = "account:auth-authority:v1:issuer/" + issuer; var event = - IssuerGenerationAuthorityEventV1Codec.seal( - Map.ofEntries( - Map.entry("schemaVersion", IssuerGenerationAuthorityEventV1Codec.SCHEMA_VERSION), - Map.entry("eventType", IssuerGenerationAuthorityEventV1Codec.EVENT_TYPE), - Map.entry("eventId", "account-issuer-authority-event-v1:" + request), - Map.entry("requestId", request), - Map.entry("issuerId", issuer), - Map.entry("sourceScope", "issuer/" + issuer), - Map.entry("outboxStreamKey", stream), - Map.entry("outboxSequence", "1"), - Map.entry("issuerAuthGeneration", "2"), - Map.entry("sourceVersion", "2"))); + AccountAuthoritySourceEventV1Codec.sealIssuer( + new IssuerPreimage( + request, request, stream, "1", issuer, "2", "2", "SIGNER_COMPROMISE")); var source = new net.firedevops.firemud.accountservice.repository .AccountAuthoritySourceEvidenceRepository.CurrentSourceEvidence( @@ -72,27 +63,71 @@ void ownedAdvancedSourceKeepsCanonicalOriginalBytesAndRejectsCheckpointContradic .AccountAuthoritySourceEvidenceRepository.CanonicalIssuerSourceSnapshot( source, Optional.of(contradictory)))) .isInstanceOf(IllegalArgumentException.class); + + var nonProducerEvent = + AccountAuthoritySourceEventV1Codec.sealIssuer( + new IssuerPreimage( + "account-issuer-authority-event-v1:" + request, + request, + stream, + "1", + issuer, + "2", + "2", + "SIGNER_COMPROMISE")); + var nonProducerStored = + new net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Event( + stream, + request, + 1L, + nonProducerEvent.eventId(), + nonProducerEvent.eventDigest(), + nonProducerEvent.canonicalJsonUtf8()); + var nonProducerSource = + new net.firedevops.firemud.accountservice.repository + .AccountAuthoritySourceEvidenceRepository.CurrentSourceEvidence( + source.scope(), + source.generation(), + source.sourceVersion(), + source.issuanceFence(), + new net.firedevops.firemud.accountservice.repository + .AccountAuthoritySourceEvidenceRepository.SourceCheckpoint( + stream, + 1L, + Optional.of(nonProducerEvent.eventId()), + Optional.of(nonProducerEvent.eventDigest())), + source.accountSecurityCutoff(), + source.initializationProvenance(), + source.accountSourceNumericId(), + source.accountUuidProvenance(), + source.initializationTransactionId(), + source.accountRepositoryInsertTransactionId()); + assertThatThrownBy( + () -> + IssuerGenerationProjection.fromSource( + new net.firedevops.firemud.accountservice.repository + .AccountAuthoritySourceEvidenceRepository.CanonicalIssuerSourceSnapshot( + nonProducerSource, Optional.of(nonProducerStored)))) + .isInstanceOf(IllegalArgumentException.class); } @Test - void exactCanonicalEventAndArbitraryPrecisionCountersSurviveOwnerRoundTrip() { + void exactCanonicalEventAndLongBoundaryCountersSurviveOwnerRoundTrip() { String issuer = "firemud-account-service"; - String generation = "92233720368547758081234567890"; - String sequence = "92233720368547758081234567889"; + String generation = Long.toString(Long.MAX_VALUE); + String sequence = Long.toString(Long.MAX_VALUE - 1L); String stream = "account:auth-authority:v1:issuer/" + issuer; var event = - IssuerGenerationAuthorityEventV1Codec.seal( - Map.ofEntries( - Map.entry("schemaVersion", IssuerGenerationAuthorityEventV1Codec.SCHEMA_VERSION), - Map.entry("eventType", IssuerGenerationAuthorityEventV1Codec.EVENT_TYPE), - Map.entry("eventId", "canonical-issuer-event"), - Map.entry("requestId", "original-request"), - Map.entry("issuerId", issuer), - Map.entry("sourceScope", "issuer/" + issuer), - Map.entry("outboxStreamKey", stream), - Map.entry("outboxSequence", sequence), - Map.entry("issuerAuthGeneration", generation), - Map.entry("sourceVersion", generation))); + AccountAuthoritySourceEventV1Codec.sealIssuer( + new IssuerPreimage( + "original-request", + "original-request", + stream, + sequence, + issuer, + generation, + generation, + "SIGNER_COMPROMISE")); var projection = new IssuerGenerationProjection( issuer, From 848ab802bd505194df687b88c416741a303ef5d2 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 7 Oct 2026 11:58:23 +1300 Subject: [PATCH 5/9] fix(account): close tenant authority source static proof --- .../dto/DemoTenantEntitlementSnapshot.java | 5 + ...ccountDemoTenantEntitlementRepository.java | 4 + ...AccountTenantAuthorityEventRepository.java | 4 + ...ountTenantEntitlementOutboxRepository.java | 4 + ...StateOperationPostgresIntegrationTest.java | 56 ++++--- ...EntitlementPersistenceIntegrationTest.java | 140 ++++++++++-------- 6 files changed, 133 insertions(+), 80 deletions(-) diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/DemoTenantEntitlementSnapshot.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/DemoTenantEntitlementSnapshot.java index 1fbf5cac8f..d5de209ab2 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/DemoTenantEntitlementSnapshot.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/DemoTenantEntitlementSnapshot.java @@ -1,5 +1,6 @@ package net.firedevops.firemud.accountservice.dto; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.util.Objects; import java.util.UUID; import java.util.regex.Pattern; @@ -34,6 +35,10 @@ public record DemoTenantEntitlementSnapshot( private static final UUID NIL_UUID = new UUID(0L, 0L); private static final Pattern EVENT_DIGEST = Pattern.compile("sha256:[0-9a-f]{64}"); + @SuppressFBWarnings( + value = "NP_LOAD_OF_KNOWN_NULL_VALUE", + justification = + "NON_PAID_DEMO requires null subscriptionStatus; the compact record constructor implicitly stores that validated null.") public DemoTenantEntitlementSnapshot { if (canonicalTenantId == null || NIL_UUID.equals(canonicalTenantId)) { throw new IllegalArgumentException("Canonical tenant UUID is required"); diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementRepository.java index 5aaff4ba72..77d1cabbaf 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementRepository.java @@ -35,6 +35,10 @@ public class AccountDemoTenantEntitlementRepository { private final AccountTenantEntitlementOutboxRepository outboxRepository; private final AccountTenantAuthorityEventRepository tenantAuthorityEvents; + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "Preserve injected collaborator preconditions; Spring must proxy this non-final repository.") public AccountDemoTenantEntitlementRepository( DSLContext dsl, FreshTenantIdentityAssociationRepository tenantIdentityRepository, diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepository.java index 7c9ae87a0a..60655921ca 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepository.java @@ -31,6 +31,10 @@ public class AccountTenantAuthorityEventRepository { private final FreshTenantIdentityAssociationRepository tenantIdentity; private final AccountAuthorityGenerationRepository generations; + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "Preserve injected collaborator preconditions; Spring must proxy this non-final repository.") public AccountTenantAuthorityEventRepository( DSLContext dsl, AccountAuthorityOutboxRepository authorityOutbox, diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantEntitlementOutboxRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantEntitlementOutboxRepository.java index e2fe64018a..a5f7971da6 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantEntitlementOutboxRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantEntitlementOutboxRepository.java @@ -24,6 +24,10 @@ public class AccountTenantEntitlementOutboxRepository { private static final UUID NIL_UUID = new UUID(0L, 0L); private final DSLContext dsl; + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "Preserve the injected DSLContext precondition; Spring must proxy this non-final repository.") public AccountTenantEntitlementOutboxRepository(DSLContext dsl) { this.dsl = Objects.requireNonNull(dsl); } diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountSecurityStateOperationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountSecurityStateOperationPostgresIntegrationTest.java index d13101f363..43188b7729 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountSecurityStateOperationPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountSecurityStateOperationPostgresIntegrationTest.java @@ -77,11 +77,13 @@ void pendingClaimAndExactRetryRetainOneOriginalCaptureWithoutSourceMutation() { assertThat(actualSource.initializationTransactionId()) .isEqualTo(actualSource.accountRepositoryInsertTransactionId()); assertThat( - fixture - .dsl() - .fetchOne( - "SELECT last_sequence FROM account_authority_outbox_streams WHERE outbox_stream_key = ?", - stream(seed.account().getAccountUuid())) + Objects.requireNonNull( + fixture + .dsl() + .fetchOne( + "SELECT last_sequence FROM account_authority_outbox_streams WHERE outbox_stream_key = ?", + stream(seed.account().getAccountUuid())), + "Expected persisted Account authority outbox stream row") .get(0, Long.class)) .isZero(); Pending pending = pending(fixture, seed, state(false), state(true), 0L, new byte[0]); @@ -146,10 +148,13 @@ void zeroReceiptRejectsAbsentMismatchedAndFabricatedV40BaselineWithoutMutation() assertThat(tx(fixture, () -> fixture.generations().read(seed.source().scope()))) .isEqualTo(seed.source()); assertThat( - fixture - .dsl() - .fetchOne( - "SELECT email_verified FROM accounts WHERE id = ?", seed.account().getId()) + Objects.requireNonNull( + fixture + .dsl() + .fetchOne( + "SELECT email_verified FROM accounts WHERE id = ?", + seed.account().getId()), + "Expected persisted Account row after rejected security-state operation") .get(0, Boolean.class)) .isFalse(); } @@ -182,10 +187,13 @@ void accountRepositoryRoleSavePersistsGenericHistoryButNotCanonicalRoleAuthority }); assertThat(saved.getRole()).isEqualTo("player"); assertThat( - fixture - .dsl() - .fetchOne( - "SELECT role FROM accounts WHERE account_uuid = ?", saved.getAccountUuid()) + Objects.requireNonNull( + fixture + .dsl() + .fetchOne( + "SELECT role FROM accounts WHERE account_uuid = ?", + saved.getAccountUuid()), + "Expected persisted Account role row") .get("role", String.class)) .isEqualTo("player"); @@ -677,10 +685,13 @@ void missingSecurityReceiptAndChangedCurrentPoststateCannotCommit() { .isInstanceOf(RuntimeException.class); assertThat(missing.dsl().fetchCount(DSL.table("account_authority_outbox_events"))).isZero(); assertThat( - missing - .dsl() - .fetchOne( - "SELECT email_verified FROM accounts WHERE id = ?", seed.account().getId()) + Objects.requireNonNull( + missing + .dsl() + .fetchOne( + "SELECT email_verified FROM accounts WHERE id = ?", + seed.account().getId()), + "Expected persisted Account row after missing-receipt rejection") .get(0, Boolean.class)) .isFalse(); @@ -698,10 +709,13 @@ void missingSecurityReceiptAndChangedCurrentPoststateCannotCommit() { other.account().getId())) .isInstanceOf(RuntimeException.class); assertThat( - changed - .dsl() - .fetchOne( - "SELECT email_verified FROM accounts WHERE id = ?", other.account().getId()) + Objects.requireNonNull( + changed + .dsl() + .fetchOne( + "SELECT email_verified FROM accounts WHERE id = ?", + other.account().getId()), + "Expected persisted Account row after rejected poststate change") .get(0, Boolean.class)) .isTrue(); tx( diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementPersistenceIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementPersistenceIntegrationTest.java index 2ab0469135..4866b49b17 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementPersistenceIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementPersistenceIntegrationTest.java @@ -4,6 +4,7 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.util.Map; +import java.util.Objects; import java.util.Set; import java.util.UUID; import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementRequest; @@ -98,7 +99,8 @@ void sequenceZeroTenantAuthorityHeadCannotCommit() { requestId, source, generationRepository.read( - AccountAuthorityGenerationRepository.AuthorityScope.tenant(tenantId))); + AccountAuthorityGenerationRepository.AuthorityScope.tenant( + tenantId))); context .dsl() .execute( @@ -269,38 +271,46 @@ void exactFreshUuidReplayConflictQuotasAndGenerationChangeAreTransactionallyFenc .hasMessageContaining("changed after its complete evaluation snapshot"); Long legacyIdentityColumnCount = - context - .dsl() - .fetchOne( - "SELECT COUNT(*) FROM information_schema.columns WHERE table_schema = ? " - + "AND table_name = 'account_demo_tenant_entitlements' " - + "AND column_name IN ('tenant_id', 'legacy_tenant_id')", - context.schema()) + Objects.requireNonNull( + context + .dsl() + .fetchOne( + "SELECT COUNT(*) FROM information_schema.columns WHERE table_schema = ? " + + "AND table_name = 'account_demo_tenant_entitlements' " + + "AND column_name IN ('tenant_id', 'legacy_tenant_id')", + context.schema()), + "Expected information_schema aggregate row") .get(0, Long.class); assertThat(legacyIdentityColumnCount).isZero(); Long outboxEventCount = - context - .dsl() - .fetchOne( - "SELECT COUNT(*) FROM account_tenant_entitlement_outbox_events WHERE tenant_uuid = ?", - tenantId) + Objects.requireNonNull( + context + .dsl() + .fetchOne( + "SELECT COUNT(*) FROM account_tenant_entitlement_outbox_events WHERE tenant_uuid = ?", + tenantId), + "Expected tenant entitlement outbox aggregate row") .get(0, Long.class); assertThat(outboxEventCount).isEqualTo(2L); Long authorityEventCount = - context - .dsl() - .fetchOne( - "SELECT COUNT(*) FROM account_authority_outbox_events " - + "WHERE outbox_stream_key = ?", - "account:auth-authority:v1:tenant/" + tenantId) + Objects.requireNonNull( + context + .dsl() + .fetchOne( + "SELECT COUNT(*) FROM account_authority_outbox_events " + + "WHERE outbox_stream_key = ?", + "account:auth-authority:v1:tenant/" + tenantId), + "Expected tenant authority outbox aggregate row") .get(0, Long.class); assertThat(authorityEventCount).isEqualTo(2L); Long operationCount = - context - .dsl() - .fetchOne( - "SELECT COUNT(*) FROM account_demo_tenant_entitlement_operations WHERE tenant_uuid = ?", - tenantId) + Objects.requireNonNull( + context + .dsl() + .fetchOne( + "SELECT COUNT(*) FROM account_demo_tenant_entitlement_operations WHERE tenant_uuid = ?", + tenantId), + "Expected tenant entitlement operation aggregate row") .get(0, Long.class); assertThat(operationCount).isEqualTo(2L); @@ -395,20 +405,24 @@ void failedOwnerTransactionAndUnmappedGenerationCannotCreateSyntheticAuthorityHi .hasMessageContaining("force owner transaction rollback"); assertTenantHasOnlyGenerationOne(context, rollbackTenant); assertThat( - context - .dsl() - .fetchOne( - "SELECT COUNT(*) FROM account_authority_outbox_events " - + "WHERE outbox_stream_key = ?", - "account:auth-authority:v1:tenant/" + rollbackTenant) + Objects.requireNonNull( + context + .dsl() + .fetchOne( + "SELECT COUNT(*) FROM account_authority_outbox_events " + + "WHERE outbox_stream_key = ?", + "account:auth-authority:v1:tenant/" + rollbackTenant), + "Expected rolled-back tenant authority outbox aggregate row") .get(0, Long.class)) .isZero(); assertThat( - context - .dsl() - .fetchOne( - "SELECT COUNT(*) FROM account_tenant_entitlement_outbox_events WHERE tenant_uuid = ?", - rollbackTenant) + Objects.requireNonNull( + context + .dsl() + .fetchOne( + "SELECT COUNT(*) FROM account_tenant_entitlement_outbox_events WHERE tenant_uuid = ?", + rollbackTenant), + "Expected rolled-back tenant billing outbox aggregate row") .get(0, Long.class)) .isZero(); @@ -449,42 +463,50 @@ void failedOwnerTransactionAndUnmappedGenerationCannotCreateSyntheticAuthorityHi .isInstanceOf(IllegalStateException.class) .hasMessageContaining("advanced without canonical source-event evidence"); assertThat( - context - .dsl() - .fetchOne( - "SELECT generation FROM account_authority_generations " - + "WHERE scope_kind = 'TENANT' AND tenant_uuid = ?", - retainedTenant) + Objects.requireNonNull( + context + .dsl() + .fetchOne( + "SELECT generation FROM account_authority_generations " + + "WHERE scope_kind = 'TENANT' AND tenant_uuid = ?", + retainedTenant), + "Expected retained tenant authority generation row") .get(0, Long.class)) .isEqualTo(2L); assertThat( - context - .dsl() - .fetchOne( - "SELECT COUNT(*) FROM account_fresh_tenant_identity_associations " - + "WHERE canonical_tenant_id = ?", - retainedTenant) + Objects.requireNonNull( + context + .dsl() + .fetchOne( + "SELECT COUNT(*) FROM account_fresh_tenant_identity_associations " + + "WHERE canonical_tenant_id = ?", + retainedTenant), + "Expected retained tenant identity association aggregate row") .get(0, Long.class)) .isEqualTo(1L); } private static void assertTenantHasOnlyGenerationOne(TestContext context, UUID tenantId) { assertThat( - context - .dsl() - .fetchOne( - "SELECT generation FROM account_authority_generations " - + "WHERE scope_kind = 'TENANT' AND tenant_uuid = ?", - tenantId) + Objects.requireNonNull( + context + .dsl() + .fetchOne( + "SELECT generation FROM account_authority_generations " + + "WHERE scope_kind = 'TENANT' AND tenant_uuid = ?", + tenantId), + "Expected tenant authority generation row") .get(0, Long.class)) .isEqualTo(1L); assertThat( - context - .dsl() - .fetchOne( - "SELECT COUNT(*) FROM account_demo_tenant_entitlement_operations " - + "WHERE tenant_uuid = ?", - tenantId) + Objects.requireNonNull( + context + .dsl() + .fetchOne( + "SELECT COUNT(*) FROM account_demo_tenant_entitlement_operations " + + "WHERE tenant_uuid = ?", + tenantId), + "Expected tenant entitlement operation aggregate row") .get(0, Long.class)) .isZero(); } From 77fbb2d29b1239eeb2c43719305ab05b75b046ae Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 7 Oct 2026 12:35:22 +1300 Subject: [PATCH 6/9] Format retained Account rollback and lifecycle proof after reconciliation --- ...countAuthoritySourceEvidencePersistenceIntegrationTest.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java index 4fc5481ed6..94dec08aa9 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java @@ -328,8 +328,7 @@ void freshAccountBaselineIsValidButGenericSaveHistoryCannotAuthorizeSecurityCurr assertThat( Objects.requireNonNull( dsl.fetchOne( - "SELECT * FROM accounts WHERE account_uuid = ?", - account.getAccountUuid()), + "SELECT * FROM accounts WHERE account_uuid = ?", account.getAccountUuid()), "expected Account after lifecycle rejection") .intoMap()) .isEqualTo(accountBeforeLifecycleRejection); From 50d027063bd40d7c4a827a8ef310de6eaf669be2 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 7 Oct 2026 23:55:56 +1300 Subject: [PATCH 7/9] fix(account): read committed authority receipts without lock upgrades --- ...countSecurityStateOperationRepository.java | 43 ++++++++++++++++--- .../AccountAuthoritySourceEventReadback.java | 4 +- ...tSecurityStateOperationRepositoryTest.java | 3 ++ ...countAuthoritySourceEventReadbackTest.java | 14 +++--- 4 files changed, 49 insertions(+), 15 deletions(-) diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountSecurityStateOperationRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountSecurityStateOperationRepository.java index c8e5867660..dce14e3b25 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountSecurityStateOperationRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountSecurityStateOperationRepository.java @@ -128,6 +128,15 @@ public Claim claim(AccountSecurityStateMutationRequest request, Capture capture) /** Returns immutable current or historical operation evidence without applying a mutation. */ public Optional findByRequestId(UUID requestId) { + return findByRequestId(requestId, false); + } + + /** Reads only complete immutable receipts without upgrading a source reader's Account lock. */ + public Optional findCommittedByRequestIdShared(UUID requestId) { + return findByRequestId(requestId, true); + } + + private Optional findByRequestId(UUID requestId, boolean sharedCommittedRead) { requireTransaction(); Objects.requireNonNull(requestId); Record identity = @@ -141,8 +150,12 @@ public Optional findByRequestId(UUID requestId) { identity.get("account_id", Long.class), identity.get("account_uuid", UUID.class), AccountIdentityProvenance.fromStorageValue( - identity.get("account_provenance", String.class))); - Optional stored = readForUpdate(requestId); + identity.get("account_provenance", String.class)), + sharedCommittedRead); + Optional stored = readOperation(requestId, sharedCommittedRead); + if (sharedCommittedRead && stored.isPresent() && stored.orElseThrow().receipt().isEmpty()) { + throw new IllegalStateException("Complete committed security-state receipt is required"); + } stored .filter(operation -> operation.receipt().isEmpty()) .ifPresent(operation -> requireSourceChange(operation.capture(), false)); @@ -160,8 +173,11 @@ public void requireCurrentPostState(Operation operation, ScopeState current) { () -> new IllegalStateException("Committed security-state receipt is required")); var request = operation.request(); lockAssociation( - operation.capture().accountId(), request.accountUuid(), operation.capture().provenance()); - Operation stored = findByRequestId(request.requestId()).orElseThrow(); + operation.capture().accountId(), + request.accountUuid(), + operation.capture().provenance(), + true); + Operation stored = findCommittedByRequestIdShared(request.requestId()).orElseThrow(); requireRequest(stored, request); if (!stored.receipt().orElseThrow().event().equals(receipt.event()) || current == null @@ -254,8 +270,17 @@ public Operation complete( } private Optional readForUpdate(UUID requestId) { + return readOperation(requestId, false); + } + + private Optional readOperation(UUID requestId, boolean shared) { Record row = - dsl.fetchOne("SELECT * FROM " + TABLE + " WHERE request_id = ? FOR UPDATE", requestId); + dsl.fetchOne( + "SELECT * FROM " + + TABLE + + " WHERE request_id = ?" + + (shared ? " FOR SHARE" : " FOR UPDATE"), + requestId); if (row == null) return Optional.empty(); UUID accountUuid = row.get("account_uuid", UUID.class); var request = @@ -549,9 +574,15 @@ private void requireSourceChange(Capture capture, boolean committed) { private void lockAssociation( long numericId, UUID accountUuid, AccountIdentityProvenance provenance) { + lockAssociation(numericId, accountUuid, provenance, false); + } + + private void lockAssociation( + long numericId, UUID accountUuid, AccountIdentityProvenance provenance, boolean shared) { Record account = dsl.fetchOne( - "SELECT id, account_uuid, account_uuid_source_numeric_id, account_uuid_provenance FROM accounts WHERE id = ? FOR UPDATE", + "SELECT id, account_uuid, account_uuid_source_numeric_id, account_uuid_provenance FROM accounts WHERE id = ?" + + (shared ? " FOR SHARE" : " FOR UPDATE"), numericId); if (account == null || !accountUuid.equals(account.get("account_uuid", UUID.class)) diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadback.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadback.java index a351a3354f..c6136e68ac 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadback.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadback.java @@ -211,7 +211,7 @@ public RetainedEventEvidence requireRetainedEvent( if (verified.securityState().isPresent()) { var operation = securityStateRepository - .findByRequestId(UUID.fromString(verified.requestId())) + .findCommittedByRequestIdShared(UUID.fromString(verified.requestId())) .orElseThrow( () -> new IllegalStateException( @@ -270,7 +270,7 @@ private void requireSecurityStateReceipt( boolean latest) { var operation = securityStateRepository - .findByRequestId(UUID.fromString(verified.requestId())) + .findCommittedByRequestIdShared(UUID.fromString(verified.requestId())) .orElseThrow( () -> new IllegalStateException( diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountSecurityStateOperationRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountSecurityStateOperationRepositoryTest.java index 38bb559393..65906f6eba 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountSecurityStateOperationRepositoryTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountSecurityStateOperationRepositoryTest.java @@ -20,6 +20,9 @@ void storageDeniesOutsideWritableOwnerTransactionBeforeDataAccess() { assertThatThrownBy(() -> repository.findByRequestId(UUID.randomUUID())) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("Writable Account owner transaction"); + assertThatThrownBy(() -> repository.findCommittedByRequestIdShared(UUID.randomUUID())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Writable Account owner transaction"); verifyNoInteractions(dsl); assertThat( repository diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadbackTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadbackTest.java index f03aa6bcd4..8fcd68df12 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadbackTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadbackTest.java @@ -31,6 +31,7 @@ import net.firedevops.firemud.accountservice.repository.AccountLogoutAllOperationRepository.LogoutAllReceipt; import net.firedevops.firemud.accountservice.repository.AccountPasswordResetOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountPasswordResetOperationRepository.PasswordResetReceipt; +import net.firedevops.firemud.accountservice.repository.AccountSecurityStateOperationRepository; import net.firedevops.firemud.accountservice.service.AccountAuthoritySourceEventReadback; import net.firedevops.firemud.accountservice.service.AccountAuthoritySourceReader.AccountSourceEventReadback; import net.firedevops.firemud.accountservice.service.AccountAuthoritySourceReader.AccountSourceSnapshot; @@ -506,14 +507,10 @@ void structurallyValidSecurityStateWithoutReceiptCannotPassOwnerReadback() { AccountPasswordResetOperationRepository resets = mock(AccountPasswordResetOperationRepository.class); AccountLogoutAllOperationRepository logouts = mock(AccountLogoutAllOperationRepository.class); + AccountSecurityStateOperationRepository securityStates = + mock(AccountSecurityStateOperationRepository.class); AccountAuthoritySourceEventReadback readback = - new AccountAuthoritySourceEventReadback( - outbox, - resets, - logouts, - org.mockito.Mockito.mock( - net.firedevops.firemud.accountservice.repository - .AccountSecurityStateOperationRepository.class)); + new AccountAuthoritySourceEventReadback(outbox, resets, logouts, securityStates); Event event = securityStateEvent(ACCOUNT_UUID, 1L, "2", "2"); assertThat(structuralSnapshot(event, 2L, 2L).latestEvent()).contains(event); when(outbox.readCheckpoint(event.outboxStreamKey())) @@ -530,6 +527,9 @@ void structurallyValidSecurityStateWithoutReceiptCannotPassOwnerReadback() { .isInstanceOf(IllegalStateException.class) .hasMessageContaining("no immutable operation receipt"); verifyNoInteractions(resets, logouts); + verify(securityStates, org.mockito.Mockito.times(2)) + .findCommittedByRequestIdShared(UUID.fromString(event.requestId())); + verify(securityStates, never()).findByRequestId(UUID.fromString(event.requestId())); } private AccountSourceSnapshot structuralSnapshot( From 74703280194953280841d517977e0f36706c9fca Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 31 Oct 2026 19:45:49 +1300 Subject: [PATCH 8/9] Qualify retained Account authority receipts and source guards --- .../player-access-and-session.md | 2 + ...lUiSourceGuardPostgresIntegrationTest.java | 427 +++++ ...StateOperationPostgresIntegrationTest.java | 1381 +++++++++++++++++ .../dto/AccountLogoutRequestDigestTest.java | 105 ++ ...countSecurityStateMutationRequestTest.java | 182 +++ ...untLogoutAllAuthorityEventV1CodecTest.java | 125 ++ ...asswordResetAuthorityEventV1CodecTest.java | 125 ++ ...ount-auth-logout-all-event-v1-vectors.json | 103 ++ ...-auth-password-reset-event-v1-vectors.json | 95 ++ 9 files changed, 2545 insertions(+) create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSecurityStateOperationPostgresIntegrationTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountLogoutRequestDigestTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountSecurityStateMutationRequestTest.java create mode 100644 services/common-platform-core/src/test/resources/net/firedevops/firemud/common/account/authority/account-auth-logout-all-event-v1-vectors.json create mode 100644 services/common-platform-core/src/test/resources/net/firedevops/firemud/common/account/authority/account-auth-password-reset-event-v1-vectors.json 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 93c4d7acb6..4aca54b9bf 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -398,6 +398,8 @@ The current Account source/currentness cut preserves V1–V40, V40.1, V53, and V Proof qualification for the Account source/currentness cut: historical `7a665c83e81f5cec85fcd7ec9a205c291bc0eba2` results remain historical evidence only. Physical Account job `114042562197` on `c69fa3645f3ddf16d2eaafd3838a29a52141736f` executed 98 integration cases with zero skips and one canonical-order Game Logic fixture failure; its correction passed Account job `114050124577` on `fb6ca4dd29fa3f39407f7f2cc32a016fab155403`. The subsequent `f1ed94a42dfdcb1f63bf52c95c60e9e5744af4b7` Account job `114059401680` in run `38001172632`, artifact `11648894382`, executed 101 PostgreSQL integration cases with zero skips and one trigger-catalog fixture failure. The new inspection-lock, immutable TRUNCATE and exact disclosure-source regressions passed. PostgreSQL truncates identifiers to its `name` type's capacity; the catalog assertion now compares through `?::name` while retaining enabled statement-level TRUNCATE checks and actual rejection tests. The final `14eaa6c9568928f0079830159ac66f37ead2c146` Account job `114067421524` in run `38003644164` passed its physical integration task with Docker active, including the corrected settlement/source-vector fixture classes in its aggregate JaCoCo execution inventory. Successful case-level JUnit totals were not retained, so no new exact per-case counts are claimed. All five required exact-head gates and subsequent metadata-preservation gates passed. This bounded evidence does not establish runtime activation or playable closure. +Current Account authority proof receiving in #3034 preserves the canonical production and migration owners while adapting eight retained test/resource paths. R1369 freshly passes 14 Common logout/reset codec cases, eight Account request-binding cases, and 25 PostgreSQL cases across source guards and security-state operations, with zero failures, errors or skips. The database cases cover observed lock contention, mixed-owner outcomes, rollback, immutable terminal retry, forged checkpoint refusal, retained receipts and populated V78→V79 history without backfill. Affected enabled test/static analysis and Java formatting pass. The retained v1 vector values are unchanged; obsolete issuer schemas, historical migration names and weaker source guards are not restored. These are controlled storage/source fixtures, not authenticated production mutation, runtime registration, genuine issuer custody or public-admission proof. Earlier snapshots below retain their original source attribution. + Canonical first-JOIN membership-event production requires current public-JOIN entitlement; a bare fresh tenant 1/1 baseline is denied and does not preserve admission. Tenant authority requires Account's exact typed tenant event, fresh Game Design provenance, and matching composite generation/source-version and billing coordinates. No entitlement caller wires this producer, so this does not activate public JOIN or gameplay admission. Historical gate 108 passed 593 Account unit cases and five focused shared World hold cases. Later gate 123 passed 598 Account unit cases, and gate 124 passed 27 focused shared-evidence cases across a broader selection; these are distinct executed snapshots and suite scopes, not conflicting totals. jOOQ generation and integration-test compilation passed. Published checkpoint `b5234acd7f93440170178d1b808e19b4a00ac644` subsequently passed required CI. PostgreSQL-backed integration sources, including the later-generation JOIN and exact outbox replay cases, remain unexecuted locally; neither unit proof nor historical CI establishes fresh-image playable proof for subsequent corrections. Earlier Account checkpoints `d619948920469228814d8d2ef60f9dac8672e7ea` and `f086de2896f885e33745d1482872ec2ae1c480c2` have reported green required CI, including full-stack Smoke. Reported local validation passed 535 Account unit tests, integration-test source compilation, and documentation checks; local physical PostgreSQL validation was not run. The newer reconciled head `5deaf573be3774b4eb8285ff857907f03b2ba5e0` and subsequent retained-source denial correction do not inherit an exact-head green claim. The correction passed 249 focused Account unit tests, integration-test source compilation, and documentation checks; exact-head required CI and physical PostgreSQL proof remain pending. diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authordraft/AccountControlUiSourceGuardPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authordraft/AccountControlUiSourceGuardPostgresIntegrationTest.java index eccc4280bd..885f7fc151 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authordraft/AccountControlUiSourceGuardPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authordraft/AccountControlUiSourceGuardPostgresIntegrationTest.java @@ -10,8 +10,13 @@ import java.util.Map; import java.util.Objects; import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; import java.util.function.Supplier; import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository.SourceChangeAbortReason; import net.firedevops.firemud.accountservice.entity.Account; import net.firedevops.firemud.accountservice.repository.AccountRepository; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; @@ -230,6 +235,428 @@ void waitingAndRevokeIntentCanStillBeRecordedWhileActualMutationStaysDenied() { changePassword(c, binding.actorAccountId(), "test-only-after-aborts"); } + @Test + void everyMixedOwnerOutcomePairingRemainsFencedUnderBothOrderings() { + for (DraftAuthorizationFenceRepository.Ordering ordering : + List.of( + DraftAuthorizationFenceRepository.Ordering.COMMIT_ORDER, + DraftAuthorizationFenceRepository.Ordering.REVOKE_ORDER)) { + for (Outcome worldOutcome : Outcome.values()) { + for (Outcome gameDesignOutcome : Outcome.values()) { + if (worldOutcome == gameDesignOutcome) { + continue; + } + Context c = context(); + var binding = binding(c); + var change = sourceChange(binding); + c.tx( + () -> { + c.fences.reserve(binding); + if (ordering == DraftAuthorizationFenceRepository.Ordering.COMMIT_ORDER) { + c.fences.claimCommitOrder(binding); + } else { + assertThat(c.fences.requestSourceChange(change)).isFalse(); + } + return null; + }); + terminal(c, binding, Owner.WORLD, worldOutcome); + terminal(c, binding, Owner.GAME_DESIGN, gameDesignOutcome); + + assertThat(c.tx(() -> c.fences.readSettlement(binding))) + .as("%s with WORLD %s and GAME_DESIGN %s", ordering, worldOutcome, gameDesignOutcome) + .isEqualTo(DraftAuthorizationFenceRepository.Settlement.PENDING); + assertThatThrownBy( + () -> changePassword(c, binding.actorAccountId(), "test-only-mixed-outcome")) + .isInstanceOf(DataAccessException.class); + if (ordering == DraftAuthorizationFenceRepository.Ordering.REVOKE_ORDER) { + assertThat(c.tx(() -> c.fences.sourceMutationPermitted(change))).isFalse(); + assertThat(c.tx(() -> c.fences.sourceAbortPermitted(change))).isFalse(); + } + } + } + } + } + + @Test + void overlappingSourceChangeClaimsObserveBackendWaitWhileDisjointSourcesProceed() + throws Exception { + Context c = context(); + var binding = binding(c); + var firstChange = sourceChange(binding); + var overlappingChange = sourceChange(binding); + c.tx(() -> c.fences.reserve(binding)); + + CountDownLatch firstIntentRecorded = new CountDownLatch(1); + CountDownLatch releaseFirstIntent = new CountDownLatch(1); + AtomicReference firstFailure = new AtomicReference<>(); + AtomicInteger firstPid = new AtomicInteger(); + Thread firstClaim = + new Thread( + () -> { + try { + c.tx( + () -> { + firstPid.set( + Objects.requireNonNull(c.dsl.fetchOne("SELECT pg_backend_pid()")) + .get(0, Integer.class)); + assertThat(c.fences.requestSourceChange(firstChange)).isFalse(); + firstIntentRecorded.countDown(); + await(releaseFirstIntent); + return null; + }); + } catch (Throwable failure) { + firstFailure.set(failure); + firstIntentRecorded.countDown(); + } + }, + "draft-source-change-first-claim"); + firstClaim.start(); + + assertThat(firstIntentRecorded.await(5, TimeUnit.SECONDS)).isTrue(); + assertThat(firstFailure.get()).isNull(); + + CountDownLatch overlappingStarted = new CountDownLatch(1); + AtomicInteger overlappingPid = new AtomicInteger(); + AtomicReference overlappingFailure = new AtomicReference<>(); + Thread overlappingClaim = + startContender( + c, + overlappingStarted, + overlappingPid, + overlappingFailure, + () -> c.fences.requestSourceChange(overlappingChange)); + try { + assertThat(overlappingStarted.await(5, TimeUnit.SECONDS)).isTrue(); + awaitBackendLock(c, overlappingPid.get(), List.of(firstPid.get())); + + var disjointBinding = binding(c); + var disjointChange = sourceChange(disjointBinding); + c.tx(() -> c.fences.reserve(disjointBinding)); + assertThat(c.tx(() -> c.fences.requestSourceChange(disjointChange))).isFalse(); + assertThat(c.tx(() -> c.fences.read(disjointBinding)).ordering()) + .isEqualTo(DraftAuthorizationFenceRepository.Ordering.REVOKE_ORDER); + assertThat(c.tx(() -> c.fences.readSourceChange(disjointChange).status())) + .isEqualTo("WAITING"); + } finally { + releaseFirstIntent.countDown(); + } + + join(firstClaim); + join(overlappingClaim); + assertThat(firstFailure.get()).isNull(); + assertThat(overlappingFailure.get()) + .isInstanceOf(DraftAuthorizationFenceRepository.PendingSourceChangeException.class); + assertThat(c.tx(() -> c.fences.readSourceChange(firstChange).status())).isEqualTo("WAITING"); + assertThatThrownBy(() -> c.tx(() -> c.fences.readSourceChange(overlappingChange))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Absent or changed immutable source mutation intent"); + } + + @Test + void commitOrderAndRevocationContendersSerializeBehindObservedPostgresLocks() throws Exception { + assertContendedOrderingWins(true); + assertContendedOrderingWins(false); + } + + @Test + void reservationAndSourceChangeIntentRollbackLeavesRowsUnchangedAndAllowsDisjointWork() { + Context c = context(); + var binding = binding(c); + var change = sourceChange(binding); + Map before = authorizationRowCounts(c); + String passwordBefore = accountPassword(c, binding.actorAccountId()); + + assertThatThrownBy( + () -> + c.tx( + () -> { + c.fences.reserve(binding); + assertThat(c.fences.requestSourceChange(change)).isFalse(); + throw new IllegalStateException("test-only transaction rollback"); + })) + .isInstanceOf(IllegalStateException.class) + .hasMessage("test-only transaction rollback"); + + assertThat(authorizationRowCounts(c)).isEqualTo(before); + assertThat(accountPassword(c, binding.actorAccountId())).isEqualTo(passwordBefore); + assertThat(c.tx(() -> c.fences.readOriginalBinding(binding.operationId()))) + .as("the reservation rolled back with its source-change intent") + .isEmpty(); + assertThatThrownBy(() -> c.tx(() -> c.fences.readSourceChange(change))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Absent or changed immutable source mutation intent"); + + var disjointBinding = binding(c); + var disjointChange = sourceChange(disjointBinding); + c.tx(() -> c.fences.reserve(disjointBinding)); + assertThat(c.tx(() -> c.fences.requestSourceChange(disjointChange))).isFalse(); + assertThat(c.tx(() -> c.fences.read(disjointBinding).ordering())) + .isEqualTo(DraftAuthorizationFenceRepository.Ordering.REVOKE_ORDER); + assertThat(c.tx(() -> c.fences.readSourceChange(disjointChange).status())).isEqualTo("WAITING"); + } + + @Test + void exactSourceAbortRetryPreservesTerminalReadbackAndCannotReopen() { + Context c = context(); + var binding = binding(c); + var change = sourceChange(binding); + c.tx( + () -> { + c.fences.reserve(binding); + assertThat(c.fences.requestSourceChange(change)).isFalse(); + return null; + }); + terminal(c, binding, Owner.WORLD, Outcome.DEFINITIVELY_ABORTED); + terminal(c, binding, Owner.GAME_DESIGN, Outcome.DEFINITIVELY_ABORTED); + assertThat(c.tx(() -> c.fences.sourceAbortPermitted(change))).isTrue(); + + c.tx( + () -> { + c.fences.markSourceAborted(change, SourceChangeAbortReason.EXPIRED); + return null; + }); + var aborted = c.tx(() -> c.fences.readSourceChange(change)); + String abortedRowVersion = sourceChangeRowVersion(c, change.changeId()); + assertThat(aborted.status()).isEqualTo("SOURCE_ABORTED"); + assertThat(aborted.requestedAt()).isNotNull(); + assertThat(aborted.committedAt()).isNull(); + assertThat(aborted.abortedAt()).isNotNull(); + assertThat(aborted.abortReason()).isEqualTo(SourceChangeAbortReason.EXPIRED); + + c.tx( + () -> { + c.fences.markSourceAborted(change, SourceChangeAbortReason.EXPIRED); + return null; + }); + assertSourceChangeUnchanged(c.tx(() -> c.fences.readSourceChange(change)), aborted); + assertThat(sourceChangeRowVersion(c, change.changeId())).isEqualTo(abortedRowVersion); + + assertThatThrownBy( + () -> + c.tx( + () -> { + c.fences.markSourceAborted(change, SourceChangeAbortReason.DEFINITIVE_ABORT); + return null; + })) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Source change abort reason differs from readback"); + assertSourceChangeUnchanged(c.tx(() -> c.fences.readSourceChange(change)), aborted); + + assertThatThrownBy(() -> c.tx(() -> c.fences.requestSourceChange(change))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Aborted source change cannot be requested again"); + assertThatThrownBy( + () -> + c.tx( + () -> { + c.fences.markSourceCommitted(change); + return null; + })) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Aborted source change cannot be committed"); + assertSourceChangeUnchanged(c.tx(() -> c.fences.readSourceChange(change)), aborted); + assertThat(sourceChangeRowVersion(c, change.changeId())).isEqualTo(abortedRowVersion); + } + + private static void assertContendedOrderingWins(boolean commitOrderWins) throws Exception { + Context c = context(); + var binding = binding(c); + var change = sourceChange(binding); + c.tx(() -> c.fences.reserve(binding)); + + try (Connection blocker = c.source.getConnection()) { + blocker.setAutoCommit(false); + try (var statement = + blocker.prepareStatement( + "SELECT source_key FROM account_draft_authorization_source_locks" + + " WHERE source_key = ? FOR UPDATE")) { + statement.setString(1, binding.sources().getFirst().key()); + assertThat(statement.executeQuery().next()).isTrue(); + } + + int blockerPid; + try (var statement = blocker.createStatement(); + var rows = statement.executeQuery("SELECT pg_backend_pid()")) { + assertThat(rows.next()).isTrue(); + blockerPid = rows.getInt(1); + } + CountDownLatch firstStarted = new CountDownLatch(1); + AtomicInteger firstPid = new AtomicInteger(); + AtomicReference firstFailure = new AtomicReference<>(); + Thread firstContender = + startContender( + c, + firstStarted, + firstPid, + firstFailure, + () -> { + if (commitOrderWins) { + c.fences.claimCommitOrder(binding); + } else { + c.fences.requestSourceChange(change); + } + }); + Thread secondContender = null; + AtomicReference secondFailure = new AtomicReference<>(); + try { + assertThat(firstStarted.await(5, TimeUnit.SECONDS)).isTrue(); + awaitBackendLock(c, firstPid.get(), List.of(blockerPid)); + + CountDownLatch secondStarted = new CountDownLatch(1); + AtomicInteger secondPid = new AtomicInteger(); + secondContender = + startContender( + c, + secondStarted, + secondPid, + secondFailure, + () -> { + if (commitOrderWins) { + c.fences.requestSourceChange(change); + } else { + c.fences.claimCommitOrder(binding); + } + }); + assertThat(secondStarted.await(5, TimeUnit.SECONDS)).isTrue(); + awaitBackendLock(c, secondPid.get(), List.of(blockerPid, firstPid.get())); + } finally { + blocker.commit(); + } + join(firstContender); + if (secondContender != null) { + join(secondContender); + } + assertThat(firstFailure.get()).isNull(); + if (commitOrderWins) { + assertThat(secondFailure.get()).isNull(); + } else { + assertThat(secondFailure.get()) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Revocation precedes this owner commit"); + } + } + + if (commitOrderWins) { + assertThat(c.tx(() -> c.fences.read(binding).ordering())) + .isEqualTo(DraftAuthorizationFenceRepository.Ordering.COMMIT_ORDER); + assertThat(c.tx(() -> c.fences.readSourceChange(change).status())).isEqualTo("WAITING"); + } else { + assertThat(c.tx(() -> c.fences.read(binding).ordering())) + .isEqualTo(DraftAuthorizationFenceRepository.Ordering.REVOKE_ORDER); + assertThatThrownBy(() -> c.tx(() -> c.fences.claimCommitOrder(binding))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Revocation precedes this owner commit"); + } + } + + private static Thread startContender( + Context c, + CountDownLatch started, + AtomicInteger backendPid, + AtomicReference failure, + Runnable action) { + Thread contender = + new Thread( + () -> { + try { + c.tx( + () -> { + backendPid.set( + Objects.requireNonNull(c.dsl.fetchOne("SELECT pg_backend_pid()")) + .get(0, Integer.class)); + started.countDown(); + action.run(); + return null; + }); + } catch (Throwable thrown) { + failure.set(thrown); + started.countDown(); + } + }, + "draft-fence-postgres-contender"); + contender.start(); + return contender; + } + + private static void awaitBackendLock(Context c, int backendPid, List expectedBlockers) + throws InterruptedException { + long deadline = System.nanoTime() + Duration.ofSeconds(5).toNanos(); + while (System.nanoTime() < deadline) { + for (int expectedBlocker : expectedBlockers) { + var activity = + c.dsl.fetchOne( + "SELECT wait_event_type = 'Lock' AND ? = ANY(pg_blocking_pids(pid)) " + + "FROM pg_stat_activity WHERE pid = ?", + expectedBlocker, + backendPid); + if (activity != null && Boolean.TRUE.equals(activity.get(0, Boolean.class))) { + return; + } + } + Thread.sleep(10); + } + throw new AssertionError( + "PostgreSQL backend " + backendPid + " did not wait behind " + expectedBlockers); + } + + private static void join(Thread thread) throws InterruptedException { + thread.join(Duration.ofSeconds(10).toMillis()); + assertThat(thread.isAlive()).as("PostgreSQL contention worker finished").isFalse(); + } + + private static void await(CountDownLatch latch) { + try { + assertThat(latch.await(10, TimeUnit.SECONDS)).isTrue(); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("Interrupted while holding a test transaction", interrupted); + } + } + + private static Map authorizationRowCounts(Context c) { + return Map.of( + "source_locks", c.dsl.fetchCount(DSL.table("account_draft_authorization_source_locks")), + "fences", c.dsl.fetchCount(DSL.table("account_draft_authorization_fences")), + "sources", c.dsl.fetchCount(DSL.table("account_draft_authorization_sources")), + "owner_readbacks", + c.dsl.fetchCount(DSL.table("account_draft_authorization_owner_readbacks")), + "source_changes", c.dsl.fetchCount(DSL.table("account_draft_authorization_source_changes")), + "changed_scopes", + c.dsl.fetchCount(DSL.table("account_draft_authorization_changed_scopes"))); + } + + private static String accountPassword(Context c, UUID accountId) { + return Objects.requireNonNull( + c.dsl.fetchOne("SELECT password_hash FROM accounts WHERE account_uuid = ?", accountId)) + .get("password_hash", String.class); + } + + private static DraftAuthorizationFenceRepository.SourceChange sourceChange( + DraftAuthorizationFenceBinding binding) { + return new DraftAuthorizationFenceRepository.SourceChange( + UUID.randomUUID(), binding.sources(), new byte[] {17}); + } + + private static void assertSourceChangeUnchanged( + DraftAuthorizationFenceRepository.SourceChangeSnapshot actual, + DraftAuthorizationFenceRepository.SourceChangeSnapshot expected) { + assertThat(actual.changeId()).isEqualTo(expected.changeId()); + assertThat(actual.binding()).containsExactly(expected.binding()); + assertThat(actual.status()).isEqualTo(expected.status()); + assertThat(actual.requestedAt()).isEqualTo(expected.requestedAt()); + assertThat(actual.committedAt()).isEqualTo(expected.committedAt()); + assertThat(actual.abortedAt()).isEqualTo(expected.abortedAt()); + assertThat(actual.abortReason()).isEqualTo(expected.abortReason()); + } + + private static String sourceChangeRowVersion(Context c, UUID changeId) { + return Objects.requireNonNull( + c.dsl.fetchOne( + "SELECT xmin::text FROM account_draft_authorization_source_changes WHERE change_id = ?", + changeId)) + .get(0, String.class); + } + private static void terminal( Context c, DraftAuthorizationFenceBinding binding, Owner owner, Outcome outcome) { c.tx( diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSecurityStateOperationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSecurityStateOperationPostgresIntegrationTest.java new file mode 100644 index 0000000000..f3e4f29184 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSecurityStateOperationPostgresIntegrationTest.java @@ -0,0 +1,1381 @@ +package integration.net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.function.Supplier; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository.SourceChange; +import net.firedevops.firemud.accountservice.dto.AccountSecurityStateMutationRequest; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.entity.AccountLoginAuthModes; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeState; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Event; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.EventEvidence; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository; +import net.firedevops.firemud.accountservice.repository.AccountLogoutAllOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountPasswordResetOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.repository.AccountSecurityStateOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountSecurityStateOperationRepository.Capture; +import net.firedevops.firemud.accountservice.service.AccountAuthoritySourceEventReadback; +import net.firedevops.firemud.accountservice.service.AccountAuthoritySourceReader; +import net.firedevops.firemud.common.account.authority.AccountSecurityStateAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.AccountSecurityStateAuthorityEventV1Codec.AccountState; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** Synthetic owner producer/correlation fixtures; these are not authenticated runtime mutations. */ +@Testcontainers(disabledWithoutDocker = true) +class AccountSecurityStateOperationPostgresIntegrationTest { + @Container + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Test + void pendingClaimAndExactRetryRetainOneOriginalCaptureWithoutSourceMutation() { + Fixture fixture = fixture(null); + Seed seed = seed(fixture); + var actualSource = + tx( + fixture, + () -> { + var sources = + new net.firedevops.firemud.accountservice.repository + .AccountAuthoritySourceEvidenceRepository( + fixture.dsl(), fixture.generations(), fixture.outbox()); + sources.initializeIssuerIfAbsent("firemud-account-service"); + return sources + .readCurrentIssuerAccountSources( + "firemud-account-service", seed.account().getAccountUuid()) + .account(); + }); + assertThat(actualSource.initializationProvenance()).isEqualTo("ACCOUNT_REPOSITORY_INSERT"); + assertThat(actualSource.checkpoint().sequence()).isZero(); + assertThat(actualSource.initializationTransactionId()) + .isEqualTo(actualSource.accountRepositoryInsertTransactionId()); + assertThat( + Objects.requireNonNull( + fixture + .dsl() + .fetchOne( + "SELECT last_sequence FROM account_authority_outbox_streams WHERE outbox_stream_key = ?", + stream(seed.account().getAccountUuid())), + "Expected persisted Account authority outbox stream row") + .get(0, Long.class)) + .isZero(); + Pending pending = pending(fixture, seed, state(false), state(true), 0L, new byte[0]); + var first = tx(fixture, () -> fixture.operations().claim(pending.request(), pending.capture())); + var retry = tx(fixture, () -> fixture.operations().claim(pending.request(), pending.capture())); + assertThat(first.claimed()).isTrue(); + assertThat(retry.claimed()).isFalse(); + assertThat(retry.operation().receipt()).isEmpty(); + assertThat( + AccountSecurityStateOperationRepository.captureBytes( + pending.request(), retry.operation().capture())) + .isEqualTo( + AccountSecurityStateOperationRepository.captureBytes( + pending.request(), pending.capture())); + assertThat( + tx( + fixture, + () -> + fixture + .generations() + .read(AuthorityScope.account(seed.account().getAccountUuid())))) + .isEqualTo(seed.source()); + assertThat( + Objects.requireNonNull( + fixture + .dsl() + .fetchOne( + "SELECT email_verified FROM accounts WHERE id = ?", + seed.account().getId()), + "Expected persisted Account row") + .get(0, Boolean.class)) + .isFalse(); + assertThat(fixture.dsl().fetchCount(DSL.table("account_authority_outbox_events"))).isZero(); + } + + @Test + void zeroReceiptRejectsAbsentMismatchedAndFabricatedV40BaselineWithoutMutation() { + for (String corruption : + List.of( + "DELETE FROM account_authority_source_records WHERE account_uuid = ?", + "UPDATE account_authority_source_records SET account_source_numeric_id = account_source_numeric_id + 1 WHERE account_uuid = ?", + "UPDATE account_authority_source_records SET initialization_transaction_id = initialization_transaction_id + 1, account_repository_insert_transaction_id = account_repository_insert_transaction_id + 1 WHERE account_uuid = ?")) { + Fixture fixture = fixture(null); + Seed seed = seed(fixture); + Pending pending = pending(fixture, seed, state(false), state(true), 0L, new byte[0]); + // Fault injection only after genuine owner insertion: never create a passing raw baseline. + fixture.dsl().execute("ALTER TABLE account_authority_source_records DISABLE TRIGGER USER"); + try { + fixture.dsl().execute(corruption, seed.account().getAccountUuid()); + } finally { + fixture.dsl().execute("ALTER TABLE account_authority_source_records ENABLE TRIGGER USER"); + } + assertThatThrownBy( + () -> + tx( + fixture, + () -> fixture.operations().claim(pending.request(), pending.capture()))) + .isInstanceOf(org.jooq.exception.DataAccessException.class) + .hasMessageContaining("Security-state pristine baseline is not proved"); + assertThat(fixture.dsl().fetchCount(DSL.table("account_security_state_operations"))).isZero(); + assertThat(fixture.dsl().fetchCount(DSL.table("account_authority_outbox_events"))).isZero(); + assertThat(tx(fixture, () -> fixture.generations().read(seed.source().scope()))) + .isEqualTo(seed.source()); + assertThat( + Objects.requireNonNull( + fixture + .dsl() + .fetchOne( + "SELECT email_verified FROM accounts WHERE id = ?", + seed.account().getId()), + "Expected persisted Account row after rejected security-state operation") + .get(0, Boolean.class)) + .isFalse(); + } + } + + @Test + void accountRepositoryRoleSavePersistsGenericHistoryButNotCanonicalRoleAuthority() { + Fixture fixture = fixture(null); + Seed seed = seed(fixture); + var roleSourceBefore = + fixture + .dsl() + .fetchOne( + "SELECT * FROM account_global_role_sources WHERE account_uuid = ?", + seed.account().getAccountUuid()); + assertThat(roleSourceBefore).isNotNull(); + assertThat(roleSourceBefore.get("global_roles", String[].class)).isEmpty(); + assertThat(roleSourceBefore.get("global_role_source_version", Long.class)).isEqualTo(1L); + + Account saved = + tx( + fixture, + () -> { + Account owner = + new AccountRepository(fixture.dsl()) + .findById(seed.account().getId()) + .orElseThrow(); + owner.setRole("player"); + return new AccountRepository(fixture.dsl()).save(owner); + }); + assertThat(saved.getRole()).isEqualTo("player"); + assertThat( + Objects.requireNonNull( + fixture + .dsl() + .fetchOne( + "SELECT role FROM accounts WHERE account_uuid = ?", + saved.getAccountUuid()), + "Expected persisted Account role row") + .get("role", String.class)) + .isEqualTo("player"); + + ScopeState current = + tx( + fixture, + () -> fixture.generations().read(AuthorityScope.account(saved.getAccountUuid()))); + assertThat(current.generation()).isEqualTo(2L); + assertThat(current.sourceVersion()).isEqualTo(2L); + assertThat(current.issuanceFence().value()).isEqualTo(2L); + assertThat(current.issuanceFence().sourceVersion()).isEqualTo(2L); + Event genericEvent = + tx( + fixture, + () -> fixture.outbox().findEvent(stream(saved.getAccountUuid()), 1L).orElseThrow()); + var verifiedGenericEvent = + (net.firedevops.firemud.common.account.authority.AccountAuthoritySourceEventV1Codec + .AccountEvent) + net.firedevops.firemud.common.account.authority.AccountAuthoritySourceEventV1Codec + .verify(new String(genericEvent.payload(), StandardCharsets.UTF_8)); + assertThat(verifiedGenericEvent.accountState().globalRole()).isEqualTo("player"); + assertThat(verifiedGenericEvent.mutationKinds()).containsExactly("GLOBAL_ROLE_CHANGED"); + assertThat(verifiedGenericEvent.accountAuthorityGeneration()) + .isEqualTo(Long.toString(current.generation())); + assertThat(verifiedGenericEvent.sourceVersion()) + .isEqualTo(Long.toString(current.sourceVersion())); + assertThat(verifiedGenericEvent.issuanceFence()) + .isEqualTo(Long.toString(current.issuanceFence().value())); + assertThat(verifiedGenericEvent.issuanceFenceSourceVersion()) + .isEqualTo(Long.toString(current.issuanceFence().sourceVersion())); + var currentSourceRecord = + fixture + .dsl() + .fetchOne( + "SELECT current_generation, current_source_version, current_issuance_fence, " + + "current_issuance_fence_source_version, last_outbox_sequence, last_event_id, " + + "last_event_digest FROM account_authority_source_records " + + "WHERE scope_kind = 'ACCOUNT' AND account_uuid = ?", + saved.getAccountUuid()); + assertThat(currentSourceRecord.get("current_generation", Long.class)).isEqualTo(2L); + assertThat(currentSourceRecord.get("current_source_version", Long.class)).isEqualTo(2L); + assertThat(currentSourceRecord.get("current_issuance_fence", Long.class)).isEqualTo(2L); + assertThat(currentSourceRecord.get("current_issuance_fence_source_version", Long.class)) + .isEqualTo(2L); + assertThat(currentSourceRecord.get("last_outbox_sequence", Long.class)).isEqualTo(1L); + assertThat(currentSourceRecord.get("last_event_id", String.class)) + .isEqualTo(genericEvent.eventId()); + assertThat(currentSourceRecord.get("last_event_digest", String.class)) + .isEqualTo(genericEvent.eventDigest()); + + var roleSourceAfter = + fixture + .dsl() + .fetchOne( + "SELECT * FROM account_global_role_sources WHERE account_uuid = ?", + saved.getAccountUuid()); + assertThat(roleSourceAfter).isEqualTo(roleSourceBefore); + assertThat(roleSourceAfter.get("global_roles", String[].class)).isEmpty(); + assertThat(roleSourceAfter.get("global_role_source_version", Long.class)).isEqualTo(1L); + assertThatThrownBy( + () -> + tx( + fixture, + () -> { + sourceReadback(fixture).requireCurrentLatest(saved, current); + return null; + })) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy(() -> sourceReader(fixture).readCurrent(saved.getAccountUuid())) + .isInstanceOf(IllegalStateException.class); + } + + @Test + void originalCallerAndFamilyBindingsCannotBeChangedOnRetry() { + Fixture fixture = fixture(null); + Seed seed = seed(fixture); + Pending pending = pending(fixture, seed, state(false), state(true), 0L, new byte[0]); + tx(fixture, () -> fixture.operations().claim(pending.request(), pending.capture())); + var request = pending.request(); + var changed = + new AccountSecurityStateMutationRequest( + request.requestId(), + request.accountUuid(), + correlation(UUID.randomUUID(), request.requestId()), + request.expectedGeneration(), + request.expectedSourceVersion(), + request.mutationKinds(), + request.desiredState()); + assertThatThrownBy( + () -> tx(fixture, () -> fixture.operations().claim(changed, pending.capture()))) + .isInstanceOf(AccountSecurityStateOperationRepository.OperationConflictException.class); + var wrongKinds = + new AccountSecurityStateMutationRequest( + UUID.randomUUID(), + request.accountUuid(), + request.callerProofBinding(), + 1L, + 1L, + List.of("LOGIN_AUTH_MODES_CHANGED"), + state(true)); + assertThatThrownBy( + () -> tx(fixture, () -> fixture.operations().claim(wrongKinds, pending.capture()))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("capture differs"); + assertThat(fixture.dsl().fetchCount(DSL.table("account_security_state_operations"))) + .isEqualTo(1); + } + + @Test + void concurrentExactClaimsSerializeToOneOriginalRequest() throws Exception { + Fixture fixture = fixture(null); + Seed seed = seed(fixture); + Pending pending = pending(fixture, seed, state(false), state(true), 0L, new byte[0]); + CountDownLatch ready = new CountDownLatch(2); + try (var executor = Executors.newFixedThreadPool(2)) { + var tasks = + List.of(1, 2).stream() + .map( + ignored -> + executor.submit( + () -> + tx( + fixture, + () -> { + ready.countDown(); + try { + if (!ready.await(10, TimeUnit.SECONDS)) + throw new IllegalStateException( + "Concurrent claims did not start"); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException(interrupted); + } + return fixture + .operations() + .claim(pending.request(), pending.capture()) + .claimed(); + }))) + .toList(); + assertThat( + List.of( + tasks.get(0).get(20, TimeUnit.SECONDS), tasks.get(1).get(20, TimeUnit.SECONDS))) + .containsExactlyInAnyOrder(true, false); + } + assertThat(fixture.dsl().fetchCount(DSL.table("account_security_state_operations"))) + .isEqualTo(1); + } + + @Test + void exactExistingOutboxReceiptCompletesOnceAndHistoricalImagesSurviveLaterAdvance() { + Fixture fixture = fixture(null); + Seed seed = seed(fixture); + Pending first = pending(fixture, seed, state(false), state(true), 0L, new byte[0]); + tx(fixture, () -> fixture.operations().claim(first.request(), first.capture())); + Event event = producerFixture(fixture, first, false); + var sourceHead = + fixture + .dsl() + .fetchOne( + "SELECT last_outbox_sequence, last_event_id, last_event_digest " + + "FROM account_authority_source_records WHERE account_uuid = ?", + seed.account().getAccountUuid()); + assertThat(sourceHead.get("last_outbox_sequence", Long.class)) + .isEqualTo(event.outboxSequence()); + assertThat(sourceHead.get("last_event_id", String.class)).isEqualTo(event.eventId()); + assertThat(sourceHead.get("last_event_digest", String.class)).isEqualTo(event.eventDigest()); + assertThat(sourceReader(fixture).readCurrent(seed.account().getAccountUuid()).latestEvent()) + .contains(event); + tx( + fixture, + () -> { + var latest = + sourceReadback(fixture) + .requireCurrentLatest( + new AccountRepository(fixture.dsl()) + .findById(seed.account().getId()) + .orElseThrow(), + fixture.generations().read(seed.source().scope())); + assertThat(latest.latestEvent()).contains(event); + return null; + }); + var retained = + tx( + fixture, + () -> fixture.operations().findByRequestId(first.request().requestId()).orElseThrow()); + assertThat(retained.receipt().orElseThrow().event()).isEqualTo(event); + ScopeState current = + tx( + fixture, + () -> + fixture + .generations() + .read(AuthorityScope.account(seed.account().getAccountUuid()))); + Seed newer = new Seed(seed.account(), current); + AccountState after = new AccountState(true, List.of("PASSWORD"), List.of(), "ACTIVE"); + Pending second = pending(fixture, newer, state(true), after, 1L, event.payload()); + tx(fixture, () -> fixture.operations().claim(second.request(), second.capture())); + producerFixture(fixture, second, false); + assertThat( + sourceReader(fixture) + .readCommittedEvent(seed.account().getAccountUuid(), 1L) + .requestedEvent()) + .isEqualTo(event); + tx( + fixture, + () -> { + var account = + new AccountRepository(fixture.dsl()).findById(seed.account().getId()).orElseThrow(); + var source = fixture.generations().read(seed.source().scope()); + sourceReadback(fixture).requireRetainedEvent(account, event, source); + assertThat(sourceReadback(fixture).requireCurrentLatest(account, source).outboxSequence()) + .isEqualTo(2L); + return null; + }); + var retry = tx(fixture, () -> fixture.operations().claim(first.request(), second.capture())); + assertThat(retry.claimed()).isFalse(); + assertThat(retry.operation().receipt().orElseThrow().event().payload()) + .isEqualTo(event.payload()); + assertThat(retry.operation().capture().beforeState()).isEqualTo(state(false)); + assertThat(retry.operation().request().desiredState()).isEqualTo(state(true)); + assertThat(fixture.dsl().fetchCount(DSL.table("account_authority_outbox_events"))).isEqualTo(2); + } + + @Test + void unownedPrivateFenceAdvanceIsRejectedWithoutChangingSourceOrOriginalReceipt() { + Fixture fixture = fixture(null); + Seed seed = seed(fixture); + Pending pending = pending(fixture, seed, state(false), state(true), 0L, new byte[0]); + tx(fixture, () -> fixture.operations().claim(pending.request(), pending.capture())); + Event event = producerFixture(fixture, pending, false); + var original = + tx( + fixture, + () -> + fixture.operations().findByRequestId(pending.request().requestId()).orElseThrow()); + var originalRow = + fixture + .dsl() + .fetchOne( + "SELECT * FROM account_security_state_operations WHERE request_id = ?", + pending.request().requestId()); + assertThatThrownBy( + () -> + tx( + fixture, + () -> { + var source = fixture.generations().read(seed.source().scope()); + fixture + .dsl() + .execute( + "UPDATE account_authority_issuance_fences " + + "SET issuance_fence = issuance_fence + 1, source_version = source_version + 1, updated_at = CURRENT_TIMESTAMP " + + "WHERE account_uuid = ? AND issuance_fence = ? AND source_version = ?", + seed.account().getAccountUuid(), + source.issuanceFence().value(), + source.issuanceFence().sourceVersion()); + return null; + })) + .rootCause() + .isInstanceOf(org.postgresql.util.PSQLException.class) + .hasMessageContaining("Account issuance fence advance lacks exact owner source evidence"); + var snapshot = sourceReader(fixture).readCurrent(seed.account().getAccountUuid()); + assertThat(snapshot.latestEvent()).contains(event); + assertThat(snapshot.sourceState()).isEqualTo(original.receipt().orElseThrow().sourceState()); + var retained = + tx( + fixture, + () -> + fixture.operations().findByRequestId(pending.request().requestId()).orElseThrow()); + assertThat(retained.receipt()).isEqualTo(original.receipt()); + assertThat( + fixture + .dsl() + .fetchOne( + "SELECT * FROM account_security_state_operations WHERE request_id = ?", + pending.request().requestId())) + .isEqualTo(originalRow); + assertThat(fixture.dsl().fetchCount(DSL.table("account_authority_outbox_events"))).isEqualTo(1); + } + + @Test + void lateReceiptFailureRollsBackEntireFixtureProducerButRetainsOriginalWaitingIntent() { + Fixture fixture = fixture(null); + Seed seed = seed(fixture); + Pending pending = pending(fixture, seed, state(false), state(true), 0L, new byte[0]); + tx(fixture, () -> fixture.operations().claim(pending.request(), pending.capture())); + assertThatThrownBy(() -> producerFixture(fixture, pending, true)) + .isInstanceOf(IllegalStateException.class); + assertThat( + tx( + fixture, + () -> + fixture + .operations() + .findByRequestId(pending.request().requestId()) + .orElseThrow()) + .receipt()) + .isEmpty(); + assertThat( + tx( + fixture, + () -> + fixture + .generations() + .read(AuthorityScope.account(seed.account().getAccountUuid())))) + .isEqualTo(seed.source()); + assertThat(fixture.dsl().fetchCount(DSL.table("account_authority_outbox_events"))).isZero(); + assertThat( + Objects.requireNonNull( + fixture + .dsl() + .fetchOne( + "SELECT email_verified FROM accounts WHERE id = ?", + seed.account().getId()), + "Expected persisted Account row after rollback") + .get(0, Boolean.class)) + .isFalse(); + assertThat( + Objects.requireNonNull( + fixture + .dsl() + .fetchOne( + "SELECT status FROM account_draft_authorization_source_changes WHERE change_id = ?", + pending.capture().sourceChange().changeId()), + "Expected original V76 source-change row after rollback") + .get(0, String.class)) + .isEqualTo("WAITING"); + } + + @Test + void requestCaptureResultsDeletesAndTruncationRemainGuarded() { + Fixture fixture = fixture(null); + Seed seed = seed(fixture); + Pending pending = pending(fixture, seed, state(false), state(true), 0L, new byte[0]); + tx(fixture, () -> fixture.operations().claim(pending.request(), pending.capture())); + for (String sql : + List.of( + "UPDATE account_security_state_operations SET request_digest = repeat('b',64)", + "UPDATE account_security_state_operations SET expected_generation = 2", + "DELETE FROM account_security_state_operations", + "TRUNCATE account_security_state_operations")) { + assertThatThrownBy(() -> fixture.dsl().execute(sql)) + .isInstanceOf(org.jooq.exception.DataAccessException.class); + } + producerFixture(fixture, pending, false); + assertThatThrownBy( + () -> + fixture + .dsl() + .execute("UPDATE account_security_state_operations SET event_id = 'changed'")) + .isInstanceOf(org.jooq.exception.DataAccessException.class); + assertThat(fixture.dsl().fetchCount(DSL.table("account_security_state_operations"))) + .isEqualTo(1); + } + + @Test + void substitutedEventStateCannotBecomeTheOriginalReceipt() { + Fixture fixture = fixture(null); + Seed seed = seed(fixture); + Pending pending = pending(fixture, seed, state(false), state(true), 0L, new byte[0]); + tx(fixture, () -> fixture.operations().claim(pending.request(), pending.capture())); + assertThatThrownBy( + () -> + tx( + fixture, + () -> { + var wrong = + AccountSecurityStateAuthorityEventV1Codec.seal( + AccountSecurityStateMutationRequest.eventPreimage( + pending.request().requestId(), + pending.request().accountUuid(), + "2", + "2", + "1", + pending.request().mutationKinds(), + state(false))); + var event = + fixture + .outbox() + .append( + stream(seed), + pending.request().requestId().toString(), + sequence -> + new EventEvidence( + wrong.eventId(), + wrong.eventDigest(), + wrong.canonicalJsonUtf8())); + fixture + .operations() + .complete( + pending.request(), + event, + new ScopeState( + seed.source().scope(), + 2L, + 2L, + new AccountAuthorityGenerationRepository.IssuanceFence( + seed.account().getAccountUuid(), 2L, 2L)), + 1L); + return null; + })) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("receipt differs"); + assertThat(fixture.dsl().fetchCount(DSL.table("account_authority_outbox_events"))).isZero(); + } + + @Test + void corruptPositiveCheckpointMetadataAndPayloadDenyBeforeNewIntentOrSourceMutation() { + for (String corruption : + List.of( + "event_id = 'substituted'", + "request_id = 'substituted'", + "event_digest = 'sha256:' || repeat('b',64)", + "payload = convert_to('{}','UTF8')")) { + Fixture fixture = fixture(null); + Seed seed = seed(fixture); + Pending first = pending(fixture, seed, state(false), state(true), 0L, new byte[0]); + tx(fixture, () -> fixture.operations().claim(first.request(), first.capture())); + Event event = producerFixture(fixture, first, false); + ScopeState current = + tx( + fixture, + () -> + fixture + .generations() + .read(AuthorityScope.account(seed.account().getAccountUuid()))); + Pending second = + pending( + fixture, + new Seed(seed.account(), current), + state(true), + new AccountState(true, List.of("PASSWORD"), List.of(), "ACTIVE"), + 1L, + event.payload()); + // Deliberately corrupt immutable storage as a superuser fixture, not a production operation. + fixture.dsl().execute("ALTER TABLE account_authority_outbox_events DISABLE TRIGGER USER"); + fixture.dsl().execute("UPDATE account_authority_outbox_events SET " + corruption); + fixture.dsl().execute("ALTER TABLE account_authority_outbox_events ENABLE TRIGGER USER"); + assertThatThrownBy( + () -> + tx(fixture, () -> fixture.operations().claim(second.request(), second.capture()))) + .isInstanceOf(RuntimeException.class); + assertThat(fixture.dsl().fetchCount(DSL.table("account_security_state_operations"))) + .isEqualTo(1); + assertThat( + tx( + fixture, + () -> + fixture + .generations() + .read(AuthorityScope.account(seed.account().getAccountUuid())))) + .isEqualTo(current); + } + } + + @Test + void retainedReceiptCannotLeadRegressedCurrentAuthorityOrCheckpoint() { + for (String table : + List.of("account_authority_generations", "account_authority_outbox_streams")) { + Fixture fixture = fixture(null); + Seed seed = seed(fixture); + Pending pending = pending(fixture, seed, state(false), state(true), 0L, new byte[0]); + tx(fixture, () -> fixture.operations().claim(pending.request(), pending.capture())); + producerFixture(fixture, pending, false); + fixture.dsl().execute("ALTER TABLE " + table + " DISABLE TRIGGER USER"); + fixture + .dsl() + .execute( + table.equals("account_authority_generations") + ? "UPDATE account_authority_generations SET generation = 1, source_version = 1" + : "UPDATE account_authority_outbox_streams SET last_sequence = 0"); + fixture.dsl().execute("ALTER TABLE " + table + " ENABLE TRIGGER USER"); + assertThatThrownBy( + () -> + tx( + fixture, + () -> fixture.operations().findByRequestId(pending.request().requestId()))) + .isInstanceOf(RuntimeException.class); + } + } + + @Test + void missingSecurityReceiptAndChangedCurrentPoststateCannotCommit() { + Fixture missing = fixture(null); + Seed seed = seed(missing); + Pending pending = pending(missing, seed, state(false), state(true), 0L, new byte[0]); + tx(missing, () -> missing.operations().claim(pending.request(), pending.capture())); + assertThatThrownBy(() -> producerFixture(missing, pending, false, false)) + .isInstanceOf(RuntimeException.class); + assertThat(missing.dsl().fetchCount(DSL.table("account_authority_outbox_events"))).isZero(); + assertThat( + Objects.requireNonNull( + missing + .dsl() + .fetchOne( + "SELECT email_verified FROM accounts WHERE id = ?", + seed.account().getId()), + "Expected persisted Account row after missing-receipt rejection") + .get(0, Boolean.class)) + .isFalse(); + + Fixture changed = fixture(null); + Seed other = seed(changed); + Pending original = pending(changed, other, state(false), state(true), 0L, new byte[0]); + tx(changed, () -> changed.operations().claim(original.request(), original.capture())); + producerFixture(changed, original, false); + assertThatThrownBy( + () -> + changed + .dsl() + .execute( + "UPDATE accounts SET email_verified = false WHERE id = ?", + other.account().getId())) + .isInstanceOf(RuntimeException.class); + assertThat( + Objects.requireNonNull( + changed + .dsl() + .fetchOne( + "SELECT email_verified FROM accounts WHERE id = ?", + other.account().getId()), + "Expected persisted Account row after rejected poststate change") + .get(0, Boolean.class)) + .isTrue(); + tx( + changed, + () -> { + sourceReadback(changed) + .requireCurrentLatest( + new AccountRepository(changed.dsl()) + .findById(other.account().getId()) + .orElseThrow(), + changed.generations().read(other.source().scope())); + return null; + }); + } + + @Test + void v78ToV79MigrationPreservesRetainedUnenrolledAccountWithoutBackfill() { + Fixture fixture = fixture("73"); + String suffix = UUID.randomUUID().toString(); + Long accountId = + Objects.requireNonNull( + fixture + .dsl() + .fetchOne( + "INSERT INTO accounts (username, email, password_hash, role) " + + "VALUES (?, ?, ?, 'player') RETURNING id", + "retained-" + suffix, + suffix + "@example.test", + "retained-password-" + suffix)) + .get(0, Long.class); + UUID accountUuid = + Objects.requireNonNull( + fixture.dsl().fetchOne("SELECT account_uuid FROM accounts WHERE id = ?", accountId)) + .get(0, UUID.class); + // This is the same historical raw-row fixture used by the Account retained-upgrade proof. + // Advance it to V78 before capturing the migration preimage; do not invent source or birth + // rows. + migrate(fixture.dataSource(), fixture.schema(), "78"); + var accountBefore = + fixture.dsl().fetch("SELECT * FROM accounts WHERE id = ?", accountId).intoMaps(); + var authorityBefore = + fixture + .dsl() + .fetch( + "SELECT * FROM account_authority_generations " + + "WHERE scope_kind = 'ACCOUNT' AND account_uuid = ?", + accountUuid) + .intoMaps(); + var sourceBefore = + fixture + .dsl() + .fetch( + "SELECT * FROM account_authority_source_records " + + "WHERE scope_kind = 'ACCOUNT' AND account_uuid = ?", + accountUuid) + .intoMaps(); + var fenceBefore = + fixture + .dsl() + .fetch( + "SELECT * FROM account_authority_issuance_fences WHERE account_uuid = ?", + accountUuid) + .intoMaps(); + var rolesBefore = + fixture + .dsl() + .fetch("SELECT * FROM account_global_role_sources WHERE account_uuid = ?", accountUuid) + .intoMaps(); + assertThat(authorityBefore).isEmpty(); + assertThat(sourceBefore).isEmpty(); + assertThat(fenceBefore).isEmpty(); + assertThat(rolesBefore).isEmpty(); + assertThat( + fixture + .dsl() + .resultQuery("SELECT to_regclass('account_platform_restriction_births')::TEXT") + .fetchOne(0, String.class)) + .isNull(); + + migrate(fixture.dataSource(), fixture.schema(), "79"); + assertThat(fixture.dsl().fetch("SELECT * FROM accounts WHERE id = ?", accountId).intoMaps()) + .isEqualTo(accountBefore); + assertThat( + fixture + .dsl() + .fetch( + "SELECT * FROM account_authority_generations " + + "WHERE scope_kind = 'ACCOUNT' AND account_uuid = ?", + accountUuid) + .intoMaps()) + .isEqualTo(authorityBefore); + assertThat( + fixture + .dsl() + .fetch( + "SELECT * FROM account_authority_source_records " + + "WHERE scope_kind = 'ACCOUNT' AND account_uuid = ?", + accountUuid) + .intoMaps()) + .isEqualTo(sourceBefore); + assertThat( + fixture + .dsl() + .fetch( + "SELECT * FROM account_authority_issuance_fences WHERE account_uuid = ?", + accountUuid) + .intoMaps()) + .isEqualTo(fenceBefore); + assertThat( + fixture + .dsl() + .fetch( + "SELECT * FROM account_global_role_sources WHERE account_uuid = ?", accountUuid) + .intoMaps()) + .isEqualTo(rolesBefore); + assertThat(fixture.dsl().fetchCount(DSL.table("account_security_state_operations"))).isZero(); + assertThat(accountUuid).isNotNull(); + assertThat( + fixture + .dsl() + .resultQuery("SELECT to_regclass('account_platform_restriction_births')::TEXT") + .fetchOne(0, String.class)) + .isNull(); + } + + @Test + void v78ToV79MigrationPreservesPopulatedHistoricalAccountAuthorityWithoutBackfill() { + Fixture fixture = fixture("78"); + HistoricalAccount historical = seedHistoricalV78Account(fixture); + + var accountBefore = snapshotRows(fixture.dsl(), "accounts", "id"); + var generationsBefore = + snapshotRows( + fixture.dsl(), + "account_authority_generations", + "scope_kind, issuer_id NULLS FIRST, account_uuid NULLS FIRST, tenant_uuid NULLS FIRST"); + var sourcesBefore = + snapshotRows(fixture.dsl(), "account_authority_source_records", "outbox_stream_key"); + var fencesBefore = + snapshotRows(fixture.dsl(), "account_authority_issuance_fences", "account_uuid"); + var rolesBefore = snapshotRows(fixture.dsl(), "account_global_role_sources", "account_uuid"); + var checkpointsBefore = + snapshotRows(fixture.dsl(), "account_authority_outbox_streams", "outbox_stream_key"); + var historyBefore = snapshotRows(fixture.dsl(), "flyway_schema_history", "installed_rank"); + var historicalBaseline = + Objects.requireNonNull( + fixture + .dsl() + .fetchOne( + "SELECT account_row.id, account_row.account_uuid, " + + "account_row.account_uuid_source_numeric_id, account_row.account_uuid_provenance, " + + "account_row.account_repository_insert_transaction_id, " + + "generation_row.created_transaction_id, generation_row.generation, " + + "generation_row.source_version, source_row.initialization_transaction_id, " + + "source_row.initialization_provenance, source_row.account_source_numeric_id, " + + "source_row.account_repository_insert_transaction_id AS source_insert_transaction_id, " + + "source_row.baseline_generation, source_row.baseline_source_version, " + + "source_row.baseline_issuance_fence, source_row.current_generation, " + + "source_row.current_source_version, source_row.current_issuance_fence, " + + "source_row.current_issuance_fence_source_version, source_row.last_outbox_sequence, " + + "fence_row.issuance_fence, fence_row.source_version AS fence_source_version, " + + "stream_row.last_sequence, role_row.global_roles, " + + "role_row.global_role_source_version " + + "FROM accounts AS account_row " + + "JOIN account_authority_generations AS generation_row " + + "ON generation_row.scope_kind = 'ACCOUNT' " + + "AND generation_row.account_uuid = account_row.account_uuid " + + "JOIN account_authority_source_records AS source_row " + + "ON source_row.scope_kind = 'ACCOUNT' " + + "AND source_row.account_uuid = account_row.account_uuid " + + "JOIN account_authority_issuance_fences AS fence_row " + + "ON fence_row.account_uuid = account_row.account_uuid " + + "JOIN account_authority_outbox_streams AS stream_row " + + "ON stream_row.outbox_stream_key = source_row.outbox_stream_key " + + "JOIN account_global_role_sources AS role_row " + + "ON role_row.account_uuid = account_row.account_uuid " + + "WHERE account_row.id = ? AND account_row.account_uuid = ?", + historical.accountId(), + historical.accountUuid()), + "Expected complete historical Account birth/source readback"); + assertThat(accountBefore).hasSize(1); + assertThat(generationsBefore).isNotEmpty(); + assertThat(sourcesBefore).isNotEmpty(); + assertThat(fencesBefore).hasSize(1); + assertThat(rolesBefore).hasSize(1); + assertThat(checkpointsBefore).isNotEmpty(); + assertThat(historyBefore).isNotEmpty(); + assertThat(historicalBaseline.get("account_uuid", UUID.class)) + .isEqualTo(historical.accountUuid()); + assertThat(historicalBaseline.get("id", Long.class)).isEqualTo(historical.accountId()); + assertThat(historicalBaseline.get("account_uuid_source_numeric_id", Long.class)) + .isEqualTo(historical.accountId()); + assertThat(historicalBaseline.get("account_uuid_provenance", String.class)) + .isEqualTo("ACCOUNT_REPOSITORY_INSERT"); + Long insertTransactionId = + historicalBaseline.get("account_repository_insert_transaction_id", Long.class); + assertThat(insertTransactionId).isPositive(); + assertThat(historicalBaseline.get("created_transaction_id", Long.class)) + .isEqualTo(insertTransactionId); + assertThat(historicalBaseline.get("initialization_transaction_id", Long.class)) + .isEqualTo(insertTransactionId); + assertThat(historicalBaseline.get("source_insert_transaction_id", Long.class)) + .isEqualTo(insertTransactionId); + assertThat(historicalBaseline.get("initialization_provenance", String.class)) + .isEqualTo("ACCOUNT_REPOSITORY_INSERT"); + assertThat(historicalBaseline.get("account_source_numeric_id", Long.class)) + .isEqualTo(historical.accountId()); + assertThat(historicalBaseline.get("generation", Long.class)).isEqualTo(1L); + assertThat(historicalBaseline.get("source_version", Long.class)).isEqualTo(1L); + assertThat(historicalBaseline.get("baseline_generation", Long.class)).isEqualTo(1L); + assertThat(historicalBaseline.get("baseline_source_version", Long.class)).isEqualTo(1L); + assertThat(historicalBaseline.get("baseline_issuance_fence", Long.class)).isEqualTo(1L); + assertThat(historicalBaseline.get("current_generation", Long.class)).isEqualTo(1L); + assertThat(historicalBaseline.get("current_source_version", Long.class)).isEqualTo(1L); + assertThat(historicalBaseline.get("issuance_fence", Long.class)).isEqualTo(1L); + assertThat(historicalBaseline.get("fence_source_version", Long.class)).isEqualTo(1L); + assertThat(historicalBaseline.get("current_issuance_fence", Long.class)).isEqualTo(1L); + assertThat(historicalBaseline.get("current_issuance_fence_source_version", Long.class)) + .isEqualTo(1L); + assertThat(historicalBaseline.get("last_outbox_sequence", Long.class)).isZero(); + assertThat(historicalBaseline.get("last_sequence", Long.class)).isZero(); + assertThat(historicalBaseline.get("global_roles", String[].class)).isEmpty(); + assertThat(historicalBaseline.get("global_role_source_version", Long.class)).isEqualTo(1L); + var appliedV78 = + Objects.requireNonNull( + fixture + .dsl() + .fetchOne("SELECT success FROM flyway_schema_history WHERE version = '78'"), + "Expected V78 Flyway history row before the V79 upgrade"); + assertThat(appliedV78.get("success", Boolean.class)).isTrue(); + assertThat( + fixture + .dsl() + .resultQuery("SELECT to_regclass('account_security_state_operations')::TEXT") + .fetchOne(0, String.class)) + .isNull(); + assertThat( + fixture + .dsl() + .resultQuery("SELECT to_regclass('account_platform_restriction_births')::TEXT") + .fetchOne(0, String.class)) + .isNull(); + assertThat(fixture.dsl().fetchCount(DSL.table("account_authority_outbox_events"))).isZero(); + + migrate(fixture.dataSource(), fixture.schema(), "79"); + + assertThat(snapshotRows(fixture.dsl(), "accounts", "id")).isEqualTo(accountBefore); + assertThat( + snapshotRows( + fixture.dsl(), + "account_authority_generations", + "scope_kind, issuer_id NULLS FIRST, account_uuid NULLS FIRST, tenant_uuid NULLS FIRST")) + .isEqualTo(generationsBefore); + assertThat(snapshotRows(fixture.dsl(), "account_authority_source_records", "outbox_stream_key")) + .isEqualTo(sourcesBefore); + assertThat(snapshotRows(fixture.dsl(), "account_authority_issuance_fences", "account_uuid")) + .isEqualTo(fencesBefore); + assertThat(snapshotRows(fixture.dsl(), "account_global_role_sources", "account_uuid")) + .isEqualTo(rolesBefore); + assertThat(snapshotRows(fixture.dsl(), "account_authority_outbox_streams", "outbox_stream_key")) + .isEqualTo(checkpointsBefore); + var historyAfter = snapshotRows(fixture.dsl(), "flyway_schema_history", "installed_rank"); + assertThat(historyAfter).hasSize(historyBefore.size() + 1); + assertThat(historyAfter.subList(0, historyBefore.size())).isEqualTo(historyBefore); + var appliedMigration = + Objects.requireNonNull( + fixture + .dsl() + .fetchOne( + "SELECT version, script, success FROM flyway_schema_history " + + "ORDER BY installed_rank DESC LIMIT 1"), + "Expected V79 Flyway history row"); + assertThat(appliedMigration.get("version", String.class)).isEqualTo("79"); + assertThat(appliedMigration.get("script", String.class)) + .isEqualTo("V79__account_security_state_operations.sql"); + assertThat(appliedMigration.get("success", Boolean.class)).isTrue(); + assertThat(fixture.dsl().fetchCount(DSL.table("account_security_state_operations"))).isZero(); + assertThat(fixture.dsl().fetchCount(DSL.table("account_authority_outbox_events"))).isZero(); + assertThat( + fixture + .dsl() + .resultQuery("SELECT to_regclass('account_platform_restriction_births')::TEXT") + .fetchOne(0, String.class)) + .isNull(); + } + + private Event producerFixture(Fixture fixture, Pending pending, boolean lateFailure) { + return producerFixture(fixture, pending, lateFailure, true); + } + + private Event producerFixture( + Fixture fixture, Pending pending, boolean lateFailure, boolean retainReceipt) { + return tx( + fixture, + () -> { + // Fixture-only sole mutation writer. Storage itself never calls these operations. + if (!fixture.fences().sourceMutationPermitted(pending.capture().sourceChange())) + throw new IllegalStateException("Fixture source is not settled"); + var sources = + new AccountAuthoritySourceEvidenceRepository( + fixture.dsl(), fixture.generations(), fixture.outbox()); + var currentSource = + sources + .readCurrentIssuerAccountSources( + "firemud-account-service", pending.request().accountUuid()) + .account(); + var retained = pending.capture().sourceState(); + if (!currentSource.scope().equals(retained.scope()) + || currentSource.generation() != retained.generation() + || currentSource.sourceVersion() != retained.sourceVersion() + || !currentSource.issuanceFence().equals(retained.issuanceFence())) { + throw new IllegalStateException( + "Fixture retained source differs from actual owner readback"); + } + ScopeState advanced = + sources.prepareClosedAccountAdvance(pending.request().accountUuid(), currentSource); + fixture + .dsl() + .execute( + "UPDATE accounts SET email_verified = ?, login_auth_modes = ?, lifecycle_state = ? WHERE account_uuid = ?", + pending.request().desiredState().emailVerified(), + AccountLoginAuthModes.normalize( + String.join(",", pending.request().desiredState().loginAuthModes())), + pending + .request() + .desiredState() + .lifecycleState() + .toLowerCase(java.util.Locale.ROOT), + pending.request().accountUuid()); + Event event = + fixture + .outbox() + .append( + stream(pending.request().accountUuid()), + pending.request().requestId().toString(), + sequence -> { + var sealed = + AccountSecurityStateAuthorityEventV1Codec.seal( + AccountSecurityStateMutationRequest.eventPreimage( + pending.request().requestId(), + pending.request().accountUuid(), + Long.toString(advanced.generation()), + Long.toString(advanced.sourceVersion()), + Long.toString(sequence), + pending.request().mutationKinds(), + pending.request().desiredState())); + return new EventEvidence( + sealed.eventId(), sealed.eventDigest(), sealed.canonicalJsonUtf8()); + }); + fixture.fences().markSourceCommitted(pending.capture().sourceChange()); + if (retainReceipt) fixture.operations().complete(pending.request(), event, advanced, 1L); + if (lateFailure) + throw new IllegalStateException("Late fixture failure after receipt completion"); + return event; + }); + } + + private Pending pending( + Fixture fixture, + Seed seed, + AccountState before, + AccountState after, + long checkpointSequence, + byte[] checkpointPayload) { + UUID requestId = UUID.randomUUID(); + UUID account = seed.account().getAccountUuid(); + var request = + new AccountSecurityStateMutationRequest( + requestId, + account, + correlation(account, requestId), + seed.source().generation(), + seed.source().sourceVersion(), + AccountSecurityStateOperationRepository.detectedKinds(before, after), + after); + var draft = + new Capture( + seed.account().getId(), + seed.account().getAccountUuidProvenance(), + before, + seed.source(), + checkpointSequence, + checkpointPayload, + 1L, + null); + byte[] captureBytes = AccountSecurityStateOperationRepository.captureBytes(request, draft); + var source = + new SourceEvidence( + SourceKind.ACCOUNT, + account.toString(), + Long.toString(seed.source().generation()), + Long.toString(seed.source().sourceVersion()), + stream(account), + Long.toString(checkpointSequence), + captureBytes); + var change = new SourceChange(UUID.randomUUID(), List.of(source), captureBytes); + var capture = + new Capture( + draft.accountId(), + draft.provenance(), + before, + seed.source(), + checkpointSequence, + checkpointPayload, + 1L, + change); + tx( + fixture, + () -> { + fixture.fences().requestSourceChange(change); + return null; + }); + return new Pending(request, capture); + } + + private AccountAuthoritySourceEventReadback sourceReadback(Fixture fixture) { + return new AccountAuthoritySourceEventReadback( + fixture.outbox(), + new AccountPasswordResetOperationRepository(fixture.dsl()), + new AccountLogoutAllOperationRepository(fixture.dsl()), + fixture.operations()); + } + + private AccountAuthoritySourceReader sourceReader(Fixture fixture) { + return new AccountAuthoritySourceReader( + new AccountRepository(fixture.dsl()), + fixture.generations(), + fixture.outbox(), + sourceReadback(fixture), + fixture.transaction().getTransactionManager()); + } + + private Fixture fixture(String version) { + String schema = "security_state_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setUrl( + postgres.getJdbcUrl() + + (postgres.getJdbcUrl().contains("?") ? "&" : "?") + + "currentSchema=" + + schema); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + migrate(dataSource, schema, version); + DSLContext dsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + return new Fixture( + schema, + dataSource, + dsl, + new TransactionTemplate(new DataSourceTransactionManager(dataSource)), + new AccountAuthorityGenerationRepository(dsl), + new AccountAuthorityOutboxRepository(dsl), + new DraftAuthorizationFenceRepository(dsl), + new AccountSecurityStateOperationRepository(dsl)); + } + + private Seed seed(Fixture fixture) { + return tx( + fixture, + () -> { + Account account = new Account(); + String id = UUID.randomUUID().toString().substring(0, 12); + account.setUsername("security-" + id); + account.setEmail(id + "@example.test"); + account.setPasswordHash("synthetic-verifier"); + account = new AccountRepository(fixture.dsl()).save(account); + new AccountAuthoritySourceEvidenceRepository( + fixture.dsl(), fixture.generations(), fixture.outbox()) + .initializeIssuerIfAbsent("firemud-account-service"); + ScopeState source = + fixture.generations().read(AuthorityScope.account(account.getAccountUuid())); + return new Seed(account, source); + }); + } + + private void migrate(DriverManagerDataSource dataSource, String schema, String version) { + var configuration = + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration"); + if (version != null) { + configuration.target(version); + } + configuration.load().migrate(); + } + + /** + * Stipulates a V78 historical Account birth using the storage sequence of the pre-V81 API. + * PostgreSQL generates the Account numeric identity and transaction provenance, and the installed + * identity and role triggers generate their paired values. The generation, fence, stream, and + * source inserts follow the V40 AccountRepository birth contract in this same transaction; this + * fixture asserts storage constraints only, not authenticated authority. + */ + private HistoricalAccount seedHistoricalV78Account(Fixture fixture) { + return tx( + fixture, + () -> { + UUID accountUuid = UUID.randomUUID(); + String suffix = UUID.randomUUID().toString(); + var accountRow = + Objects.requireNonNull( + fixture + .dsl() + .fetchOne( + "INSERT INTO accounts (account_uuid, account_uuid_provenance, username, " + + "email, password_hash, role, email_verified, login_auth_modes, " + + "lifecycle_state) " + + "VALUES (?, 'ACCOUNT_REPOSITORY_INSERT', ?, ?, ?, NULL, FALSE, " + + "'PASSWORD,EMAIL_OTP', 'active') " + + "RETURNING id, account_uuid, account_uuid_source_numeric_id, " + + "account_uuid_provenance, account_repository_insert_transaction_id", + accountUuid, + "historical-" + suffix, + suffix + "@example.test", + "historical-password-" + suffix), + "Expected V78 historical Account birth"); + Long accountId = + Objects.requireNonNull(accountRow.get("id", Long.class), "Expected Account id"); + String issuerId = "firemud-account-service"; + String issuerStreamKey = "account:auth-authority:v1:issuer/" + issuerId; + String accountStreamKey = "account:auth-authority:v1:account/" + accountUuid; + + fixture + .dsl() + .execute( + "INSERT INTO account_authority_generations " + + "(scope_kind, issuer_id, generation, source_version) " + + "VALUES ('ISSUER', ?, 1, 1)", + issuerId); + fixture + .dsl() + .execute( + "INSERT INTO account_authority_outbox_streams " + + "(outbox_stream_key, last_sequence) VALUES (?, 0)", + issuerStreamKey); + fixture + .dsl() + .execute( + "INSERT INTO account_authority_source_records " + + "(outbox_stream_key, scope_kind, issuer_id, account_uuid, " + + "baseline_generation, baseline_source_version, initialization_provenance, " + + "current_generation, current_source_version, last_outbox_sequence) " + + "VALUES (?, 'ISSUER', ?, NULL, 1, 1, 'ISSUER_SCOPE_INSERT', 1, 1, 0)", + issuerStreamKey, + issuerId); + + fixture + .dsl() + .execute( + "INSERT INTO account_authority_generations " + + "(scope_kind, account_uuid, generation, source_version) " + + "VALUES ('ACCOUNT', ?, 1, 1)", + accountUuid); + fixture + .dsl() + .execute( + "INSERT INTO account_authority_issuance_fences " + + "(account_uuid, issuance_fence, source_version) VALUES (?, 1, 1)", + accountUuid); + fixture + .dsl() + .execute( + "INSERT INTO account_authority_outbox_streams " + + "(outbox_stream_key, last_sequence) VALUES (?, 0)", + accountStreamKey); + int insertedSource = + fixture + .dsl() + .execute( + "INSERT INTO account_authority_source_records " + + "(outbox_stream_key, scope_kind, issuer_id, account_uuid, " + + "baseline_generation, baseline_source_version, baseline_issuance_fence, " + + "initialization_provenance, account_source_numeric_id, " + + "account_uuid_provenance, account_repository_insert_transaction_id, " + + "current_generation, current_source_version, current_issuance_fence, " + + "current_issuance_fence_source_version, last_outbox_sequence) " + + "SELECT ?, 'ACCOUNT', NULL, account_row.account_uuid, " + + "generation_row.generation, generation_row.source_version, " + + "fence_row.issuance_fence, account_row.account_uuid_provenance, " + + "account_row.account_uuid_source_numeric_id, " + + "account_row.account_uuid_provenance, " + + "account_row.account_repository_insert_transaction_id, " + + "generation_row.generation, generation_row.source_version, " + + "fence_row.issuance_fence, fence_row.source_version, " + + "stream_row.last_sequence " + + "FROM accounts AS account_row " + + "JOIN account_authority_generations AS generation_row " + + "ON generation_row.scope_kind = 'ACCOUNT' " + + "AND generation_row.account_uuid = account_row.account_uuid " + + "JOIN account_authority_issuance_fences AS fence_row " + + "ON fence_row.account_uuid = account_row.account_uuid " + + "JOIN account_authority_outbox_streams AS stream_row " + + "ON stream_row.outbox_stream_key = ? " + + "WHERE account_row.id = ? AND account_row.account_uuid = ?", + accountStreamKey, + accountStreamKey, + accountId, + accountUuid); + if (insertedSource != 1) { + throw new IllegalStateException("Historical Account source baseline was not inserted"); + } + return new HistoricalAccount(accountId, accountUuid); + }); + } + + private List> snapshotRows(DSLContext dsl, String table, String orderBy) { + return dsl.fetch( + "SELECT encode(convert_to(to_jsonb(retained_row)::TEXT, 'UTF8'), 'hex') " + + "AS row_bytes_hex, retained_row.xmin::TEXT AS xmin FROM " + + table + + " AS retained_row ORDER BY " + + orderBy) + .intoMaps(); + } + + private static T tx(Fixture fixture, Supplier work) { + return fixture.transaction().execute(status -> work.get()); + } + + private static AccountState state(boolean verified) { + return new AccountState(verified, List.of("EMAIL_OTP", "PASSWORD"), List.of(), "ACTIVE"); + } + + private static String stream(Seed seed) { + return stream(seed.account().getAccountUuid()); + } + + private static String stream(UUID account) { + return "account:auth-authority:v1:account/" + account; + } + + private static byte[] correlation(UUID actor, UUID operation) { + return ("{\"actorAccountUuid\":\"" + + actor + + "\",\"ownerEvidenceDigest\":\"sha256:" + + "a".repeat(64) + + "\",\"ownerOperationId\":\"" + + operation + + "\",\"schemaVersion\":\"account-security-state-caller-correlation/v1\"}") + .getBytes(StandardCharsets.UTF_8); + } + + private record Fixture( + String schema, + DriverManagerDataSource dataSource, + DSLContext dsl, + TransactionTemplate transaction, + AccountAuthorityGenerationRepository generations, + AccountAuthorityOutboxRepository outbox, + DraftAuthorizationFenceRepository fences, + AccountSecurityStateOperationRepository operations) {} + + private record Seed(Account account, ScopeState source) {} + + private record HistoricalAccount(Long accountId, UUID accountUuid) {} + + private record Pending(AccountSecurityStateMutationRequest request, Capture capture) {} +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountLogoutRequestDigestTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountLogoutRequestDigestTest.java new file mode 100644 index 0000000000..fc0fd83b27 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountLogoutRequestDigestTest.java @@ -0,0 +1,105 @@ +package unit.net.firedevops.firemud.accountservice.dto; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.AccountLogoutRequestDigest; +import org.junit.jupiter.api.Test; + +class AccountLogoutRequestDigestTest { + private static final UUID LOGOUT_ALL_ACCOUNT = + UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID TOKEN_LOGOUT_ACCOUNT = + UUID.fromString("22222222-2222-4222-8222-222222222222"); + + @Test + void accountLogoutAllMatchesFixedRequestDigestV1PreimageAndDigestVector() { + String tokenHash = "a".repeat(64); + + assertThat( + AccountLogoutRequestDigest.accountLogoutAllPreimageHex( + LOGOUT_ALL_ACCOUNT, "control-ui", tokenHash)) + .isEqualTo( + compactHex( + """ + 31363a726571756573744469676573742f763131333a6f7065726174696f6e4b696e64363a737472696e673131383a4143434f554e545f4c4f474f55545f414c4c31363a7375626a6563744163636f756e744964363a737472696e673133363a31313131313131312d313131312d343131312d383131312d31313131313131313131313131323a746f6b656e50726f66696c65363a737472696e673131303a636f6e74726f6c2d756931383a70726573656e746564546f6b656e48617368363a737472696e673136343a61616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161 + """)); + assertThat( + AccountLogoutRequestDigest.accountLogoutAll( + LOGOUT_ALL_ACCOUNT, "control-ui", tokenHash)) + .isEqualTo("78f999be5a5bdb0a5bc4517336ad6899b2383c8058b0bb8f76fe67eb67dea020"); + } + + @Test + void tokenLogoutMatchesFixedRequestDigestV1PreimageAndDigestVector() { + String tokenHash = "b".repeat(64); + + assertThat( + AccountLogoutRequestDigest.tokenLogoutPreimageHex( + TOKEN_LOGOUT_ACCOUNT, "player-bootstrap", tokenHash)) + .isEqualTo( + compactHex( + """ + 31363a726571756573744469676573742f763131333a6f7065726174696f6e4b696e64363a737472696e673131323a544f4b454e5f4c4f474f555431363a7375626a6563744163636f756e744964363a737472696e673133363a32323232323232322d323232322d343232322d383232322d32323232323232323232323231323a746f6b656e50726f66696c65363a737472696e673131363a706c617965722d626f6f747374726170393a746f6b656e48617368363a737472696e673136343a62626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262 + """)); + assertThat( + AccountLogoutRequestDigest.tokenLogout( + TOKEN_LOGOUT_ACCOUNT, "player-bootstrap", tokenHash)) + .isEqualTo("21c085ddf384d4ab3d32c04f37601e710240d11ffe1be64531ee780cf2fcdee0"); + } + + @Test + void eachClosedTupleFieldChangesTheDigest() { + String tokenHash = "a".repeat(64); + String original = + AccountLogoutRequestDigest.accountLogoutAll(LOGOUT_ALL_ACCOUNT, "control-ui", tokenHash); + + assertThat(AccountLogoutRequestDigest.tokenLogout(LOGOUT_ALL_ACCOUNT, "control-ui", tokenHash)) + .isNotEqualTo(original); + assertThat( + AccountLogoutRequestDigest.accountLogoutAll( + TOKEN_LOGOUT_ACCOUNT, "control-ui", tokenHash)) + .isNotEqualTo(original); + assertThat( + AccountLogoutRequestDigest.accountLogoutAll( + LOGOUT_ALL_ACCOUNT, "player-bootstrap", tokenHash)) + .isNotEqualTo(original); + assertThat( + AccountLogoutRequestDigest.accountLogoutAll( + LOGOUT_ALL_ACCOUNT, "control-ui", "b".repeat(64))) + .isNotEqualTo(original); + } + + @Test + void rejectsUnsupportedProfilesNoncanonicalAccountIdentityAndMalformedTokenHashes() { + assertThatThrownBy( + () -> + AccountLogoutRequestDigest.accountLogoutAll( + LOGOUT_ALL_ACCOUNT, "private-player-delegation", "a".repeat(64))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("token profile"); + assertThatThrownBy( + () -> + AccountLogoutRequestDigest.accountLogoutAll( + new UUID(0L, 0L), "control-ui", "a".repeat(64))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("non-nil Account UUID"); + assertThatThrownBy( + () -> + AccountLogoutRequestDigest.tokenLogout( + LOGOUT_ALL_ACCOUNT, "control-ui", "A".repeat(64))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("lowercase SHA-256 hex"); + assertThatThrownBy( + () -> + AccountLogoutRequestDigest.tokenLogout( + LOGOUT_ALL_ACCOUNT, "control-ui", "a".repeat(63))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("lowercase SHA-256 hex"); + } + + private static String compactHex(String hex) { + return hex.replaceAll("\\s+", ""); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountSecurityStateMutationRequestTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountSecurityStateMutationRequestTest.java new file mode 100644 index 0000000000..d1085cf5b3 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountSecurityStateMutationRequestTest.java @@ -0,0 +1,182 @@ +package unit.net.firedevops.firemud.accountservice.dto; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.AccountSecurityStateMutationRequest; +import net.firedevops.firemud.accountservice.dto.AccountSecurityStateRequestDigest; +import net.firedevops.firemud.common.account.authority.AccountSecurityStateAuthorityEventV1Codec.AccountState; +import org.junit.jupiter.api.Test; + +class AccountSecurityStateMutationRequestTest { + private static final UUID REQUEST = UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID ACCOUNT = UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final List KINDS = List.of("EMAIL_LOGIN_ELIGIBILITY_CHANGED"); + + @Test + void exactRequestFramesRetainCallerAndStateBytesAndFixedDigest() { + var request = + request( + REQUEST, ACCOUNT, caller(ACCOUNT, REQUEST, "a".repeat(64)), 1L, 1L, KINDS, state(true)); + ByteBuffer bytes = ByteBuffer.wrap(AccountSecurityStateRequestDigest.requestBytes(request)); + assertThat(readFrame(bytes)).isEqualTo("firemud/account/security-state/request/v1"); + assertThat(readFrame(bytes)).isEqualTo(REQUEST.toString()); + assertThat(readFrame(bytes)).isEqualTo(ACCOUNT.toString()); + assertThat(readFrame(bytes)) + .isEqualTo(new String(request.callerProofBinding(), StandardCharsets.UTF_8)); + assertThat(readFrame(bytes)).isEqualTo("1"); + assertThat(readFrame(bytes)).isEqualTo("1"); + assertThat(readFrame(bytes)).isEqualTo("1"); + assertThat(readFrame(bytes)).isEqualTo("EMAIL_LOGIN_ELIGIBILITY_CHANGED"); + assertThat(readFrame(bytes)) + .isEqualTo( + "{\"emailVerified\":true,\"globalRoles\":[],\"lifecycleState\":\"ACTIVE\",\"loginAuthModes\":[\"EMAIL_OTP\",\"PASSWORD\"]}"); + assertThat(bytes.hasRemaining()).isFalse(); + assertThat(AccountSecurityStateRequestDigest.digest(request)) + .isEqualTo("604a354594c3a0b5f882224d44ad40bc8a5ce67c2afa704e6f470f79d0e8ee30"); + } + + @Test + void everyOriginalSemanticBindingChangesDigestIncludingCallerTargetStateAndKinds() { + var original = + request( + REQUEST, ACCOUNT, caller(ACCOUNT, REQUEST, "a".repeat(64)), 1L, 1L, KINDS, state(true)); + UUID other = UUID.fromString("33333333-3333-4333-8333-333333333333"); + for (var changed : + List.of( + request(other, ACCOUNT, original.callerProofBinding(), 1L, 1L, KINDS, state(true)), + request(REQUEST, other, original.callerProofBinding(), 1L, 1L, KINDS, state(true)), + request( + REQUEST, + ACCOUNT, + caller(other, REQUEST, "a".repeat(64)), + 1L, + 1L, + KINDS, + state(true)), + request( + REQUEST, + ACCOUNT, + caller(ACCOUNT, other, "a".repeat(64)), + 1L, + 1L, + KINDS, + state(true)), + request( + REQUEST, + ACCOUNT, + caller(ACCOUNT, REQUEST, "b".repeat(64)), + 1L, + 1L, + KINDS, + state(true)), + request(REQUEST, ACCOUNT, original.callerProofBinding(), 2L, 1L, KINDS, state(true)), + request(REQUEST, ACCOUNT, original.callerProofBinding(), 1L, 2L, KINDS, state(true)), + request(REQUEST, ACCOUNT, original.callerProofBinding(), 1L, 1L, KINDS, state(false)), + request( + REQUEST, + ACCOUNT, + original.callerProofBinding(), + 1L, + 1L, + List.of("LOGIN_AUTH_MODES_CHANGED"), + state(true)))) { + assertThat(AccountSecurityStateRequestDigest.digest(changed)) + .isNotEqualTo(AccountSecurityStateRequestDigest.digest(original)); + } + } + + @Test + void closedCorrelationRejectsAssertionsCredentialsNullsAndUnknownFields() { + byte[] original = caller(ACCOUNT, REQUEST, "a".repeat(64)); + for (String extra : List.of("password", "token", "otp", "authenticated", "globalRoles")) { + String value = new String(original, StandardCharsets.UTF_8); + byte[] changed = + (value.substring(0, value.length() - 1) + ",\"" + extra + "\":\"asserted\"}") + .getBytes(StandardCharsets.UTF_8); + assertThatThrownBy(() -> request(REQUEST, ACCOUNT, changed, 1L, 1L, KINDS, state(true))) + .isInstanceOf(IllegalArgumentException.class); + } + assertThatThrownBy( + () -> + request( + REQUEST, + ACCOUNT, + "{}".getBytes(StandardCharsets.UTF_8), + 1L, + 1L, + KINDS, + state(true))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> request(REQUEST, ACCOUNT, original, 0L, 1L, KINDS, state(true))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + request(REQUEST, ACCOUNT, original, 1L, 1L, List.of("PASSWORD_RESET"), state(true))) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void requestCopiesInputsAndStateHasOnlySharedCodecPolicyVocabulary() { + byte[] bytes = caller(ACCOUNT, REQUEST, "a".repeat(64)); + var request = request(REQUEST, ACCOUNT, bytes, 1L, 1L, KINDS, state(true)); + byte[] retained = request.callerProofBinding(); + bytes[0] = 0; + retained[0] = 0; + assertThat(request.callerProofBinding()[0]).isEqualTo((byte) '{'); + assertThatThrownBy(() -> request.mutationKinds().clear()) + .isInstanceOf(UnsupportedOperationException.class); + assertThatThrownBy( + () -> + request( + REQUEST, + ACCOUNT, + request.callerProofBinding(), + 1L, + 1L, + KINDS, + new AccountState(true, List.of("PASSWORD"), List.of("admin"), "ACTIVE"))) + .isInstanceOf(IllegalArgumentException.class); + assertThat( + AccountSecurityStateMutationRequest.parseCanonicalState( + request.canonicalDesiredState())) + .isEqualTo(request.desiredState()); + } + + private static AccountSecurityStateMutationRequest request( + UUID request, + UUID account, + byte[] caller, + long generation, + long version, + List kinds, + AccountState state) { + return new AccountSecurityStateMutationRequest( + request, account, caller, generation, version, kinds, state); + } + + private static AccountState state(boolean verified) { + return new AccountState(verified, List.of("EMAIL_OTP", "PASSWORD"), List.of(), "ACTIVE"); + } + + private static byte[] caller(UUID actor, UUID operation, String digest) { + return ("{\"actorAccountUuid\":\"" + + actor + + "\",\"ownerEvidenceDigest\":\"sha256:" + + digest + + "\",\"ownerOperationId\":\"" + + operation + + "\",\"schemaVersion\":\"account-security-state-caller-correlation/v1\"}") + .getBytes(StandardCharsets.UTF_8); + } + + private static String readFrame(ByteBuffer bytes) { + byte[] field = new byte[bytes.getInt()]; + bytes.get(field); + return new String(field, StandardCharsets.UTF_8); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountLogoutAllAuthorityEventV1CodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountLogoutAllAuthorityEventV1CodecTest.java index 552b2b9195..bb1b25f379 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountLogoutAllAuthorityEventV1CodecTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountLogoutAllAuthorityEventV1CodecTest.java @@ -3,21 +3,146 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.util.Map; import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; class AccountLogoutAllAuthorityEventV1CodecTest { + private static final String VECTOR_RESOURCE = + "/net/firedevops/firemud/common/account/authority/" + + "account-auth-logout-all-event-v1-vectors.json"; private static final String ACCOUNT_ID = "11111111-1111-4111-8111-111111111111"; private static final String REQUEST_ID = "22222222-2222-4222-8222-222222222222"; private static final String STREAM = AccountLogoutAllAuthorityEventV1Codec.EVENT_STREAM_PREFIX + "account/" + ACCOUNT_ID; private static final String LARGE_COUNTER = "9223372036854775807"; private static final ObjectMapper JSON = new ObjectMapper(); + private static JsonNode vectors; + + @BeforeAll + static void loadVectors() throws IOException { + try (InputStream stream = + AccountLogoutAllAuthorityEventV1CodecTest.class.getResourceAsStream(VECTOR_RESOURCE)) { + if (stream == null) { + throw new IOException("Missing shared event vectors: " + VECTOR_RESOURCE); + } + vectors = JSON.readTree(stream); + } + } + + @Test + void fixedVectorsVerifySealAndArbitraryPrecisionCounters() throws Exception { + assertThat(vectors.path("schemaVersion").asText()) + .isEqualTo("account-auth-logout-all-event-vectors/v1"); + + for (JsonNode vector : vectors.path("validEvents")) { + JsonNode wireEvent = vector.path("event"); + var verified = AccountLogoutAllAuthorityEventV1Codec.verify(wireEvent.toString()); + assertThat(verified.eventDigest()).isEqualTo(vector.path("expectedEventDigest").asText()); + assertThat(verified.eventDigest()).isEqualTo(wireEvent.path("eventDigest").asText()); + assertThat(verified.canonicalJson()).isEqualTo(vector.path("expectedCanonicalJson").asText()); + assertThat(verified.canonicalJsonUtf8()) + .isEqualTo( + vector.path("expectedCanonicalJson").asText().getBytes(StandardCharsets.UTF_8)); + assertThat(verified.canonicalJsonUtf8()) + .isEqualTo(Rfc8785CanonicalJson.canonicalizeUtf8(wireEvent.toString())); + + ObjectNode preimage = (ObjectNode) wireEvent.deepCopy(); + preimage.remove("eventDigest"); + Map preimageMap = JSON.convertValue(preimage, new TypeReference<>() {}); + var sealed = AccountLogoutAllAuthorityEventV1Codec.seal(preimageMap); + assertThat(sealed.eventDigest()).isEqualTo(vector.path("expectedEventDigest").asText()); + assertThat(sealed.canonicalJson()).isEqualTo(vector.path("expectedCanonicalJson").asText()); + } + + var large = + AccountLogoutAllAuthorityEventV1Codec.verify( + vectors.path("validEvents").get(1).path("event").toString()); + assertThat(large.outboxSequence()).isEqualTo("18446744073709551616000000000000000001"); + assertThat(large.accountAuthorityGeneration()) + .isEqualTo("92233720368547758081234567890123456789"); + assertThat(large.sourceVersion()).isEqualTo("90071992547409931234567890123456789"); + } + + @Test + void changedDeclaredFieldsCannotReuseTheOriginalDigest() { + ObjectNode baseline = (ObjectNode) vectors.path("validEvents").get(0).path("event").deepCopy(); + String originalDigest = baseline.path("eventDigest").asText(); + + for (JsonNode mutation : vectors.path("changedDeclaredFieldMutations")) { + ObjectNode changedWire = (ObjectNode) baseline.deepCopy(); + JsonNode changes = mutation.path("changes"); + changes + .fieldNames() + .forEachRemaining(field -> changedWire.set(field, changes.get(field).deepCopy())); + ObjectNode changedPreimage = (ObjectNode) changedWire.deepCopy(); + changedPreimage.remove("eventDigest"); + Map preimageMap = + JSON.convertValue(changedPreimage, new TypeReference<>() {}); + + var sealed = AccountLogoutAllAuthorityEventV1Codec.seal(preimageMap); + assertThat(sealed.eventDigest()) + .as(mutation.path("name").asText()) + .isNotEqualTo(originalDigest); + assertThatThrownBy(() -> AccountLogoutAllAuthorityEventV1Codec.verify(changedWire.toString())) + .as(mutation.path("name").asText()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("eventDigest"); + } + } + + @Test + void canonicalPropertyReorderingPreservesTheFixedEvent() { + JsonNode vector = vectors.path("validEvents").get(0); + JsonNode event = vector.path("event"); + ObjectNode reordered = JSON.createObjectNode(); + for (JsonNode field : vectors.path("canonicalReorderedPropertyOrder")) { + String fieldName = field.asText(); + reordered.set(fieldName, event.path(fieldName).deepCopy()); + } + + var verified = AccountLogoutAllAuthorityEventV1Codec.verify(reordered.toString()); + assertThat(verified.eventDigest()).isEqualTo(vector.path("expectedEventDigest").asText()); + assertThat(verified.canonicalJson()).isEqualTo(vector.path("expectedCanonicalJson").asText()); + } + + @Test + void invalidMutationVectorsAreRejected() { + ObjectNode baseline = (ObjectNode) vectors.path("validEvents").get(0).path("event").deepCopy(); + for (JsonNode mutation : vectors.path("invalidMutations")) { + ObjectNode changed = (ObjectNode) baseline.deepCopy(); + applyMutation(changed, mutation); + assertThatThrownBy(() -> AccountLogoutAllAuthorityEventV1Codec.verify(changed.toString())) + .as(mutation.path("name").asText()) + .isInstanceOf(IllegalArgumentException.class); + } + } + + private static void applyMutation(ObjectNode root, JsonNode mutation) { + String[] path = mutation.path("path").asText().substring(1).split("/"); + JsonNode parent = root; + for (int index = 0; index < path.length - 1; index++) { + parent = parent.path(path[index]); + } + if (!(parent instanceof ObjectNode object)) { + throw new IllegalArgumentException("Mutation parent must be an object: " + mutation); + } + String field = path[path.length - 1]; + switch (mutation.path("op").asText()) { + case "add", "replace" -> object.set(field, mutation.path("value").deepCopy()); + case "remove" -> object.remove(field); + default -> throw new IllegalArgumentException("Unsupported mutation operation: " + mutation); + } + } @Test void sealsAndVerifiesRequestDerivedLogoutIdentityAndLargeCounters() throws Exception { diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/PasswordResetAuthorityEventV1CodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/PasswordResetAuthorityEventV1CodecTest.java index e4c64d4a54..1b1cbcfece 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/PasswordResetAuthorityEventV1CodecTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/PasswordResetAuthorityEventV1CodecTest.java @@ -3,20 +3,145 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.util.Map; import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; class PasswordResetAuthorityEventV1CodecTest { + private static final String VECTOR_RESOURCE = + "/net/firedevops/firemud/common/account/authority/" + + "account-auth-password-reset-event-v1-vectors.json"; private static final String ACCOUNT_ID = "11111111-1111-4111-8111-111111111111"; private static final String STREAM = PasswordResetAuthorityEventV1Codec.EVENT_STREAM_PREFIX + "account/" + ACCOUNT_ID; private static final String LARGE_COUNTER = "9223372036854775807"; private static final ObjectMapper JSON = new ObjectMapper(); + private static JsonNode vectors; + + @BeforeAll + static void loadVectors() throws IOException { + try (InputStream stream = + PasswordResetAuthorityEventV1CodecTest.class.getResourceAsStream(VECTOR_RESOURCE)) { + if (stream == null) { + throw new IOException("Missing shared event vectors: " + VECTOR_RESOURCE); + } + vectors = JSON.readTree(stream); + } + } + + @Test + void fixedVectorsVerifySealAndArbitraryPrecisionCounters() throws Exception { + assertThat(vectors.path("schemaVersion").asText()) + .isEqualTo("account-auth-password-reset-event-vectors/v1"); + + for (JsonNode vector : vectors.path("validEvents")) { + JsonNode wireEvent = vector.path("event"); + var verified = PasswordResetAuthorityEventV1Codec.verify(wireEvent.toString()); + assertThat(verified.eventDigest()).isEqualTo(vector.path("expectedEventDigest").asText()); + assertThat(verified.eventDigest()).isEqualTo(wireEvent.path("eventDigest").asText()); + assertThat(verified.canonicalJson()).isEqualTo(vector.path("expectedCanonicalJson").asText()); + assertThat(verified.canonicalJsonUtf8()) + .isEqualTo( + vector.path("expectedCanonicalJson").asText().getBytes(StandardCharsets.UTF_8)); + assertThat(verified.canonicalJsonUtf8()) + .isEqualTo(Rfc8785CanonicalJson.canonicalizeUtf8(wireEvent.toString())); + + ObjectNode preimage = (ObjectNode) wireEvent.deepCopy(); + preimage.remove("eventDigest"); + Map preimageMap = JSON.convertValue(preimage, new TypeReference<>() {}); + var sealed = PasswordResetAuthorityEventV1Codec.seal(preimageMap); + assertThat(sealed.eventDigest()).isEqualTo(vector.path("expectedEventDigest").asText()); + assertThat(sealed.canonicalJson()).isEqualTo(vector.path("expectedCanonicalJson").asText()); + } + + var large = + PasswordResetAuthorityEventV1Codec.verify( + vectors.path("validEvents").get(1).path("event").toString()); + assertThat(large.outboxSequence()).isEqualTo("18446744073709551616000000000000000001"); + assertThat(large.accountAuthorityGeneration()) + .isEqualTo("92233720368547758081234567890123456789"); + assertThat(large.sourceVersion()).isEqualTo("90071992547409931234567890123456789"); + } + + @Test + void changedDeclaredFieldsCannotReuseTheOriginalDigest() { + ObjectNode baseline = (ObjectNode) vectors.path("validEvents").get(0).path("event").deepCopy(); + String originalDigest = baseline.path("eventDigest").asText(); + + for (JsonNode mutation : vectors.path("changedDeclaredFieldMutations")) { + ObjectNode changedWire = (ObjectNode) baseline.deepCopy(); + JsonNode changes = mutation.path("changes"); + changes + .fieldNames() + .forEachRemaining(field -> changedWire.set(field, changes.get(field).deepCopy())); + ObjectNode changedPreimage = (ObjectNode) changedWire.deepCopy(); + changedPreimage.remove("eventDigest"); + Map preimageMap = + JSON.convertValue(changedPreimage, new TypeReference<>() {}); + + var sealed = PasswordResetAuthorityEventV1Codec.seal(preimageMap); + assertThat(sealed.eventDigest()) + .as(mutation.path("name").asText()) + .isNotEqualTo(originalDigest); + assertThatThrownBy(() -> PasswordResetAuthorityEventV1Codec.verify(changedWire.toString())) + .as(mutation.path("name").asText()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("eventDigest"); + } + } + + @Test + void canonicalPropertyReorderingPreservesTheFixedEvent() { + JsonNode vector = vectors.path("validEvents").get(0); + JsonNode event = vector.path("event"); + ObjectNode reordered = JSON.createObjectNode(); + for (JsonNode field : vectors.path("canonicalReorderedPropertyOrder")) { + String fieldName = field.asText(); + reordered.set(fieldName, event.path(fieldName).deepCopy()); + } + + var verified = PasswordResetAuthorityEventV1Codec.verify(reordered.toString()); + assertThat(verified.eventDigest()).isEqualTo(vector.path("expectedEventDigest").asText()); + assertThat(verified.canonicalJson()).isEqualTo(vector.path("expectedCanonicalJson").asText()); + } + + @Test + void invalidMutationVectorsAreRejected() { + ObjectNode baseline = (ObjectNode) vectors.path("validEvents").get(0).path("event").deepCopy(); + for (JsonNode mutation : vectors.path("invalidMutations")) { + ObjectNode changed = (ObjectNode) baseline.deepCopy(); + applyMutation(changed, mutation); + assertThatThrownBy(() -> PasswordResetAuthorityEventV1Codec.verify(changed.toString())) + .as(mutation.path("name").asText()) + .isInstanceOf(IllegalArgumentException.class); + } + } + + private static void applyMutation(ObjectNode root, JsonNode mutation) { + String[] path = mutation.path("path").asText().substring(1).split("/"); + JsonNode parent = root; + for (int index = 0; index < path.length - 1; index++) { + parent = parent.path(path[index]); + } + if (!(parent instanceof ObjectNode object)) { + throw new IllegalArgumentException("Mutation parent must be an object: " + mutation); + } + String field = path[path.length - 1]; + switch (mutation.path("op").asText()) { + case "add", "replace" -> object.set(field, mutation.path("value").deepCopy()); + case "remove" -> object.remove(field); + default -> throw new IllegalArgumentException("Unsupported mutation operation: " + mutation); + } + } @Test void sealsAndVerifiesBoundPasswordResetEvidenceWithLargeStringCounters() throws Exception { diff --git a/services/common-platform-core/src/test/resources/net/firedevops/firemud/common/account/authority/account-auth-logout-all-event-v1-vectors.json b/services/common-platform-core/src/test/resources/net/firedevops/firemud/common/account/authority/account-auth-logout-all-event-v1-vectors.json new file mode 100644 index 0000000000..ca03aeb191 --- /dev/null +++ b/services/common-platform-core/src/test/resources/net/firedevops/firemud/common/account/authority/account-auth-logout-all-event-v1-vectors.json @@ -0,0 +1,103 @@ +{ + "schemaVersion": "account-auth-logout-all-event-vectors/v1", + "validEvents": [ + { + "name": "standard-account-logout-all-cutoff", + "expectedEventDigest": "sha256:8bcd1a2c82b807a59f01cab599dfabc43d7b687fba80709ef9aa54590272f439", + "expectedCanonicalJson": "{\"accountAuthorityGeneration\":\"2\",\"accountId\":\"11111111-1111-4111-8111-111111111111\",\"accountSecurityCutoff\":{\"accountAuthorityGeneration\":\"2\",\"outboxSequence\":\"1\",\"outboxStreamKey\":\"account:auth-authority:v1:account/11111111-1111-4111-8111-111111111111\"},\"eventDigest\":\"sha256:8bcd1a2c82b807a59f01cab599dfabc43d7b687fba80709ef9aa54590272f439\",\"eventId\":\"account-logout-all-event-v1:22222222-2222-4222-8222-222222222222\",\"eventType\":\"LOGOUT_ALL_COMMITTED\",\"outboxSequence\":\"1\",\"outboxStreamKey\":\"account:auth-authority:v1:account/11111111-1111-4111-8111-111111111111\",\"requestId\":\"22222222-2222-4222-8222-222222222222\",\"schemaVersion\":\"account-auth-logout-all-event/v1\",\"sourceScope\":\"account/11111111-1111-4111-8111-111111111111\",\"sourceVersion\":\"2\"}", + "event": { + "schemaVersion": "account-auth-logout-all-event/v1", + "eventType": "LOGOUT_ALL_COMMITTED", + "eventId": "account-logout-all-event-v1:22222222-2222-4222-8222-222222222222", + "requestId": "22222222-2222-4222-8222-222222222222", + "accountId": "11111111-1111-4111-8111-111111111111", + "sourceScope": "account/11111111-1111-4111-8111-111111111111", + "outboxStreamKey": "account:auth-authority:v1:account/11111111-1111-4111-8111-111111111111", + "outboxSequence": "1", + "accountAuthorityGeneration": "2", + "sourceVersion": "2", + "accountSecurityCutoff": { + "accountAuthorityGeneration": "2", + "outboxStreamKey": "account:auth-authority:v1:account/11111111-1111-4111-8111-111111111111", + "outboxSequence": "1" + }, + "eventDigest": "sha256:8bcd1a2c82b807a59f01cab599dfabc43d7b687fba80709ef9aa54590272f439" + } + }, + { + "name": "counters-above-javascript-safe-integer-and-signed-long", + "expectedEventDigest": "sha256:c5938750b1da3b163fdadc80913667430052797e91671f098189f86e120e44d7", + "expectedCanonicalJson": "{\"accountAuthorityGeneration\":\"92233720368547758081234567890123456789\",\"accountId\":\"11111111-1111-4111-8111-111111111111\",\"accountSecurityCutoff\":{\"accountAuthorityGeneration\":\"92233720368547758081234567890123456789\",\"outboxSequence\":\"18446744073709551616000000000000000001\",\"outboxStreamKey\":\"account:auth-authority:v1:account/11111111-1111-4111-8111-111111111111\"},\"eventDigest\":\"sha256:c5938750b1da3b163fdadc80913667430052797e91671f098189f86e120e44d7\",\"eventId\":\"account-logout-all-event-v1:22222222-2222-4222-8222-222222222222\",\"eventType\":\"LOGOUT_ALL_COMMITTED\",\"outboxSequence\":\"18446744073709551616000000000000000001\",\"outboxStreamKey\":\"account:auth-authority:v1:account/11111111-1111-4111-8111-111111111111\",\"requestId\":\"22222222-2222-4222-8222-222222222222\",\"schemaVersion\":\"account-auth-logout-all-event/v1\",\"sourceScope\":\"account/11111111-1111-4111-8111-111111111111\",\"sourceVersion\":\"90071992547409931234567890123456789\"}", + "event": { + "schemaVersion": "account-auth-logout-all-event/v1", + "eventType": "LOGOUT_ALL_COMMITTED", + "eventId": "account-logout-all-event-v1:22222222-2222-4222-8222-222222222222", + "requestId": "22222222-2222-4222-8222-222222222222", + "accountId": "11111111-1111-4111-8111-111111111111", + "sourceScope": "account/11111111-1111-4111-8111-111111111111", + "outboxStreamKey": "account:auth-authority:v1:account/11111111-1111-4111-8111-111111111111", + "outboxSequence": "18446744073709551616000000000000000001", + "accountAuthorityGeneration": "92233720368547758081234567890123456789", + "sourceVersion": "90071992547409931234567890123456789", + "accountSecurityCutoff": { + "accountAuthorityGeneration": "92233720368547758081234567890123456789", + "outboxStreamKey": "account:auth-authority:v1:account/11111111-1111-4111-8111-111111111111", + "outboxSequence": "18446744073709551616000000000000000001" + }, + "eventDigest": "sha256:c5938750b1da3b163fdadc80913667430052797e91671f098189f86e120e44d7" + } + } + ], + "changedDeclaredFieldMutations": [ + {"name": "request-and-derived-event-identities", "changes": {"requestId": "33333333-3333-4333-8333-333333333333", "eventId": "account-logout-all-event-v1:33333333-3333-4333-8333-333333333333"}}, + {"name": "account-identity-and-derived-scope", "changes": {"accountId": "44444444-4444-4444-8444-444444444444", "sourceScope": "account/44444444-4444-4444-8444-444444444444", "outboxStreamKey": "account:auth-authority:v1:account/44444444-4444-4444-8444-444444444444", "accountSecurityCutoff": {"accountAuthorityGeneration": "2", "outboxStreamKey": "account:auth-authority:v1:account/44444444-4444-4444-8444-444444444444", "outboxSequence": "1"}}}, + {"name": "outbox-sequence-and-cutoff", "changes": {"outboxSequence": "3", "accountSecurityCutoff": {"accountAuthorityGeneration": "2", "outboxStreamKey": "account:auth-authority:v1:account/11111111-1111-4111-8111-111111111111", "outboxSequence": "3"}}}, + {"name": "account-authority-generation-and-cutoff", "changes": {"accountAuthorityGeneration": "4", "accountSecurityCutoff": {"accountAuthorityGeneration": "4", "outboxStreamKey": "account:auth-authority:v1:account/11111111-1111-4111-8111-111111111111", "outboxSequence": "1"}}}, + {"name": "source-version", "changes": {"sourceVersion": "3"}} + ], + "canonicalReorderedPropertyOrder": [ + "sourceVersion", "requestId", "outboxSequence", "outboxStreamKey", "eventType", + "eventId", "eventDigest", "accountId", "accountAuthorityGeneration", + "accountSecurityCutoff", "schemaVersion", "sourceScope" + ], + "invalidMutations": [ + {"name": "unsupported-schema", "op": "replace", "path": "/schemaVersion", "value": "account-auth-logout-all-event/v2"}, + {"name": "password-reset-schema-is-not-an-alias", "op": "replace", "path": "/schemaVersion", "value": "account-auth-password-reset-event/v1"}, + {"name": "unsupported-event-type", "op": "replace", "path": "/eventType", "value": "PASSWORD_RESET_COMMITTED"}, + {"name": "numeric-event-type", "op": "replace", "path": "/eventType", "value": 7}, + {"name": "missing-event-id", "op": "remove", "path": "/eventId"}, + {"name": "null-event-id", "op": "replace", "path": "/eventId", "value": null}, + {"name": "missing-request-id", "op": "remove", "path": "/requestId"}, + {"name": "nil-request-id", "op": "replace", "path": "/requestId", "value": "00000000-0000-0000-0000-000000000000"}, + {"name": "uppercase-request-id", "op": "replace", "path": "/requestId", "value": "22222222-2222-4222-8222-22222222222A"}, + {"name": "request-event-identity-mismatch", "op": "replace", "path": "/requestId", "value": "33333333-3333-4333-8333-333333333333"}, + {"name": "wrong-event-id-prefix", "op": "replace", "path": "/eventId", "value": "password-reset-event-v1:22222222-2222-4222-8222-222222222222"}, + {"name": "nil-account-id", "op": "replace", "path": "/accountId", "value": "00000000-0000-0000-0000-000000000000"}, + {"name": "uppercase-account-id", "op": "replace", "path": "/accountId", "value": "11111111-1111-4111-8111-11111111111A"}, + {"name": "numeric-account-id", "op": "replace", "path": "/accountId", "value": 111}, + {"name": "mismatched-source-scope", "op": "replace", "path": "/sourceScope", "value": "account/22222222-2222-4222-8222-222222222222"}, + {"name": "mismatched-stream-key", "op": "replace", "path": "/outboxStreamKey", "value": "account:auth-authority:v1:account/22222222-2222-4222-8222-222222222222"}, + {"name": "numeric-outbox-sequence", "op": "replace", "path": "/outboxSequence", "value": 1}, + {"name": "zero-outbox-sequence", "op": "replace", "path": "/outboxSequence", "value": "0"}, + {"name": "leading-zero-outbox-sequence", "op": "replace", "path": "/outboxSequence", "value": "01"}, + {"name": "negative-outbox-sequence", "op": "replace", "path": "/outboxSequence", "value": "-1"}, + {"name": "numeric-account-generation", "op": "replace", "path": "/accountAuthorityGeneration", "value": 2}, + {"name": "zero-source-version", "op": "replace", "path": "/sourceVersion", "value": "0"}, + {"name": "null-source-version", "op": "replace", "path": "/sourceVersion", "value": null}, + {"name": "null-security-cutoff", "op": "replace", "path": "/accountSecurityCutoff", "value": null}, + {"name": "array-security-cutoff", "op": "replace", "path": "/accountSecurityCutoff", "value": []}, + {"name": "missing-cutoff-sequence", "op": "remove", "path": "/accountSecurityCutoff/outboxSequence"}, + {"name": "extra-cutoff-field", "op": "add", "path": "/accountSecurityCutoff/issuanceFence", "value": "4"}, + {"name": "numeric-cutoff-generation", "op": "replace", "path": "/accountSecurityCutoff/accountAuthorityGeneration", "value": 2}, + {"name": "mismatched-cutoff-generation", "op": "replace", "path": "/accountSecurityCutoff/accountAuthorityGeneration", "value": "3"}, + {"name": "mismatched-cutoff-stream", "op": "replace", "path": "/accountSecurityCutoff/outboxStreamKey", "value": "account:auth-authority:v1:account/22222222-2222-4222-8222-222222222222"}, + {"name": "mismatched-cutoff-sequence", "op": "replace", "path": "/accountSecurityCutoff/outboxSequence", "value": "2"}, + {"name": "unknown-fence-field", "op": "add", "path": "/issuanceFence", "value": "9"}, + {"name": "forbidden-authority-tuple", "op": "add", "path": "/authorityTuple", "value": {}}, + {"name": "forbidden-presented-token-identity", "op": "add", "path": "/tokenHash", "value": "sha256:1111111111111111111111111111111111111111111111111111111111111111"}, + {"name": "forbidden-recipient-tuple", "op": "add", "path": "/recipientAuthorityTuple", "value": {}}, + {"name": "missing-digest", "op": "remove", "path": "/eventDigest"}, + {"name": "malformed-digest", "op": "replace", "path": "/eventDigest", "value": "SHA256:1111111111111111111111111111111111111111111111111111111111111111"}, + {"name": "digest-mismatch", "op": "replace", "path": "/eventDigest", "value": "sha256:1111111111111111111111111111111111111111111111111111111111111111"} + ] +} diff --git a/services/common-platform-core/src/test/resources/net/firedevops/firemud/common/account/authority/account-auth-password-reset-event-v1-vectors.json b/services/common-platform-core/src/test/resources/net/firedevops/firemud/common/account/authority/account-auth-password-reset-event-v1-vectors.json new file mode 100644 index 0000000000..d564498b3c --- /dev/null +++ b/services/common-platform-core/src/test/resources/net/firedevops/firemud/common/account/authority/account-auth-password-reset-event-v1-vectors.json @@ -0,0 +1,95 @@ +{ + "schemaVersion": "account-auth-password-reset-event-vectors/v1", + "validEvents": [ + { + "name": "standard-password-reset-cutoff", + "expectedEventDigest": "sha256:9d276449fcd7388ff4dee66f5d69f92c666e15c641ab0f21990104ac9b9bea07", + "expectedCanonicalJson": "{\"accountAuthorityGeneration\":\"7\",\"accountId\":\"018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a\",\"accountSecurityCutoff\":{\"accountAuthorityGeneration\":\"7\",\"outboxSequence\":\"3\",\"outboxStreamKey\":\"account:auth-authority:v1:account/018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a\"},\"eventDigest\":\"sha256:9d276449fcd7388ff4dee66f5d69f92c666e15c641ab0f21990104ac9b9bea07\",\"eventId\":\"password-reset-event-001\",\"eventType\":\"PASSWORD_RESET_COMMITTED\",\"outboxSequence\":\"3\",\"outboxStreamKey\":\"account:auth-authority:v1:account/018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a\",\"requestId\":\"password-reset-request-001\",\"schemaVersion\":\"account-auth-password-reset-event/v1\",\"sourceScope\":\"account/018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a\",\"sourceVersion\":\"12\"}", + "event": { + "schemaVersion": "account-auth-password-reset-event/v1", + "eventType": "PASSWORD_RESET_COMMITTED", + "eventId": "password-reset-event-001", + "requestId": "password-reset-request-001", + "accountId": "018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a", + "sourceScope": "account/018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a", + "outboxStreamKey": "account:auth-authority:v1:account/018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a", + "outboxSequence": "3", + "accountAuthorityGeneration": "7", + "sourceVersion": "12", + "accountSecurityCutoff": { + "accountAuthorityGeneration": "7", + "outboxStreamKey": "account:auth-authority:v1:account/018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a", + "outboxSequence": "3" + }, + "eventDigest": "sha256:9d276449fcd7388ff4dee66f5d69f92c666e15c641ab0f21990104ac9b9bea07" + } + }, + { + "name": "counters-above-javascript-safe-integer-and-signed-long", + "expectedEventDigest": "sha256:2fef25b7ec2fc79dc95e07352e0477214835f09ee287d0233bd937488c8b2f65", + "expectedCanonicalJson": "{\"accountAuthorityGeneration\":\"92233720368547758081234567890123456789\",\"accountId\":\"018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a\",\"accountSecurityCutoff\":{\"accountAuthorityGeneration\":\"92233720368547758081234567890123456789\",\"outboxSequence\":\"18446744073709551616000000000000000001\",\"outboxStreamKey\":\"account:auth-authority:v1:account/018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a\"},\"eventDigest\":\"sha256:2fef25b7ec2fc79dc95e07352e0477214835f09ee287d0233bd937488c8b2f65\",\"eventId\":\"password-reset-event-large-counters\",\"eventType\":\"PASSWORD_RESET_COMMITTED\",\"outboxSequence\":\"18446744073709551616000000000000000001\",\"outboxStreamKey\":\"account:auth-authority:v1:account/018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a\",\"requestId\":\"password-reset-request-large-counters\",\"schemaVersion\":\"account-auth-password-reset-event/v1\",\"sourceScope\":\"account/018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a\",\"sourceVersion\":\"90071992547409931234567890123456789\"}", + "event": { + "schemaVersion": "account-auth-password-reset-event/v1", + "eventType": "PASSWORD_RESET_COMMITTED", + "eventId": "password-reset-event-large-counters", + "requestId": "password-reset-request-large-counters", + "accountId": "018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a", + "sourceScope": "account/018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a", + "outboxStreamKey": "account:auth-authority:v1:account/018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a", + "outboxSequence": "18446744073709551616000000000000000001", + "accountAuthorityGeneration": "92233720368547758081234567890123456789", + "sourceVersion": "90071992547409931234567890123456789", + "accountSecurityCutoff": { + "accountAuthorityGeneration": "92233720368547758081234567890123456789", + "outboxStreamKey": "account:auth-authority:v1:account/018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a", + "outboxSequence": "18446744073709551616000000000000000001" + }, + "eventDigest": "sha256:2fef25b7ec2fc79dc95e07352e0477214835f09ee287d0233bd937488c8b2f65" + } + } + ], + "changedDeclaredFieldMutations": [ + {"name": "event-id", "changes": {"eventId": "password-reset-event-002"}}, + {"name": "request-id", "changes": {"requestId": "password-reset-request-002"}}, + {"name": "account-identity-and-derived-scope", "changes": {"accountId": "018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0b", "sourceScope": "account/018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0b", "outboxStreamKey": "account:auth-authority:v1:account/018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0b", "accountSecurityCutoff": {"accountAuthorityGeneration": "7", "outboxStreamKey": "account:auth-authority:v1:account/018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0b", "outboxSequence": "3"}}}, + {"name": "outbox-sequence-and-cutoff", "changes": {"outboxSequence": "4", "accountSecurityCutoff": {"accountAuthorityGeneration": "7", "outboxStreamKey": "account:auth-authority:v1:account/018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a", "outboxSequence": "4"}}}, + {"name": "account-authority-generation-and-cutoff", "changes": {"accountAuthorityGeneration": "8", "accountSecurityCutoff": {"accountAuthorityGeneration": "8", "outboxStreamKey": "account:auth-authority:v1:account/018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a", "outboxSequence": "3"}}}, + {"name": "source-version", "changes": {"sourceVersion": "13"}} + ], + "canonicalReorderedPropertyOrder": [ + "sourceVersion", "requestId", "outboxSequence", "outboxStreamKey", "eventType", + "eventId", "eventDigest", "accountId", "accountAuthorityGeneration", + "accountSecurityCutoff", "schemaVersion", "sourceScope" + ], + "invalidMutations": [ + {"name": "unsupported-schema", "op": "replace", "path": "/schemaVersion", "value": "account-auth-password-reset-event/v2"}, + {"name": "unsupported-event-type", "op": "replace", "path": "/eventType", "value": "PASSWORD_RESET_REQUESTED"}, + {"name": "missing-required-event-id", "op": "remove", "path": "/eventId"}, + {"name": "empty-event-id", "op": "replace", "path": "/eventId", "value": ""}, + {"name": "missing-required-request-id", "op": "remove", "path": "/requestId"}, + {"name": "null-account-id", "op": "replace", "path": "/accountId", "value": null}, + {"name": "nil-account-id", "op": "replace", "path": "/accountId", "value": "00000000-0000-0000-0000-000000000000"}, + {"name": "uppercase-account-id", "op": "replace", "path": "/accountId", "value": "018F8F0A-1A6B-7B13-8D04-5F6E7D8C9B0A"}, + {"name": "mismatched-source-scope", "op": "replace", "path": "/sourceScope", "value": "account/018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0b"}, + {"name": "mismatched-stream-key", "op": "replace", "path": "/outboxStreamKey", "value": "account:auth-authority:v1:account/018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0b"}, + {"name": "numeric-outbox-sequence", "op": "replace", "path": "/outboxSequence", "value": 3}, + {"name": "zero-outbox-sequence", "op": "replace", "path": "/outboxSequence", "value": "0"}, + {"name": "leading-zero-outbox-sequence", "op": "replace", "path": "/outboxSequence", "value": "03"}, + {"name": "negative-outbox-sequence", "op": "replace", "path": "/outboxSequence", "value": "-3"}, + {"name": "exponent-outbox-sequence", "op": "replace", "path": "/outboxSequence", "value": "3e0"}, + {"name": "numeric-account-generation", "op": "replace", "path": "/accountAuthorityGeneration", "value": 7}, + {"name": "zero-source-version", "op": "replace", "path": "/sourceVersion", "value": "0"}, + {"name": "null-security-cutoff", "op": "replace", "path": "/accountSecurityCutoff", "value": null}, + {"name": "missing-cutoff-sequence", "op": "remove", "path": "/accountSecurityCutoff/outboxSequence"}, + {"name": "extra-cutoff-field", "op": "add", "path": "/accountSecurityCutoff/issuanceFence", "value": "4"}, + {"name": "mismatched-cutoff-generation", "op": "replace", "path": "/accountSecurityCutoff/accountAuthorityGeneration", "value": "8"}, + {"name": "mismatched-cutoff-stream", "op": "replace", "path": "/accountSecurityCutoff/outboxStreamKey", "value": "account:auth-authority:v1:account/018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0b"}, + {"name": "mismatched-cutoff-sequence", "op": "replace", "path": "/accountSecurityCutoff/outboxSequence", "value": "4"}, + {"name": "unknown-fence-field", "op": "add", "path": "/issuanceFence", "value": "9"}, + {"name": "forbidden-authority-tuple", "op": "add", "path": "/authorityTuple", "value": {}}, + {"name": "forbidden-credential-material", "op": "add", "path": "/passwordVerifier", "value": "secret"}, + {"name": "missing-digest", "op": "remove", "path": "/eventDigest"}, + {"name": "malformed-digest", "op": "replace", "path": "/eventDigest", "value": "SHA256:1111111111111111111111111111111111111111111111111111111111111111"}, + {"name": "digest-mismatch", "op": "replace", "path": "/eventDigest", "value": "sha256:1111111111111111111111111111111111111111111111111111111111111111"} + ] +} From 91cb3e0583e44f5ff2a2c6a5f1b25d484cf76d97 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 31 Oct 2026 21:02:23 +1300 Subject: [PATCH 9/9] Prove authority field and corruption guards independently --- .../player-access-and-session.md | 2 +- ...StateOperationPostgresIntegrationTest.java | 122 ++++++++++++++++-- ...untLogoutAllAuthorityEventV1CodecTest.java | 46 ++++++- ...asswordResetAuthorityEventV1CodecTest.java | 30 ++++- 4 files changed, 177 insertions(+), 23 deletions(-) diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index 4aca54b9bf..e79b1b2fdc 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -398,7 +398,7 @@ The current Account source/currentness cut preserves V1–V40, V40.1, V53, and V Proof qualification for the Account source/currentness cut: historical `7a665c83e81f5cec85fcd7ec9a205c291bc0eba2` results remain historical evidence only. Physical Account job `114042562197` on `c69fa3645f3ddf16d2eaafd3838a29a52141736f` executed 98 integration cases with zero skips and one canonical-order Game Logic fixture failure; its correction passed Account job `114050124577` on `fb6ca4dd29fa3f39407f7f2cc32a016fab155403`. The subsequent `f1ed94a42dfdcb1f63bf52c95c60e9e5744af4b7` Account job `114059401680` in run `38001172632`, artifact `11648894382`, executed 101 PostgreSQL integration cases with zero skips and one trigger-catalog fixture failure. The new inspection-lock, immutable TRUNCATE and exact disclosure-source regressions passed. PostgreSQL truncates identifiers to its `name` type's capacity; the catalog assertion now compares through `?::name` while retaining enabled statement-level TRUNCATE checks and actual rejection tests. The final `14eaa6c9568928f0079830159ac66f37ead2c146` Account job `114067421524` in run `38003644164` passed its physical integration task with Docker active, including the corrected settlement/source-vector fixture classes in its aggregate JaCoCo execution inventory. Successful case-level JUnit totals were not retained, so no new exact per-case counts are claimed. All five required exact-head gates and subsequent metadata-preservation gates passed. This bounded evidence does not establish runtime activation or playable closure. -Current Account authority proof receiving in #3034 preserves the canonical production and migration owners while adapting eight retained test/resource paths. R1369 freshly passes 14 Common logout/reset codec cases, eight Account request-binding cases, and 25 PostgreSQL cases across source guards and security-state operations, with zero failures, errors or skips. The database cases cover observed lock contention, mixed-owner outcomes, rollback, immutable terminal retry, forged checkpoint refusal, retained receipts and populated V78→V79 history without backfill. Affected enabled test/static analysis and Java formatting pass. The retained v1 vector values are unchanged; obsolete issuer schemas, historical migration names and weaker source guards are not restored. These are controlled storage/source fixtures, not authenticated production mutation, runtime registration, genuine issuer custody or public-admission proof. Earlier snapshots below retain their original source attribution. +Current Account authority proof receiving in #3034 preserves the canonical production and migration owners while adapting eight retained test/resource paths. R1369 freshly passes 14 Common logout/reset codec cases, eight Account request-binding cases, and 25 PostgreSQL cases across source guards and security-state operations, with zero failures, errors or skips. The database cases cover observed lock contention, mixed-owner outcomes, rollback, immutable terminal retry, forged checkpoint refusal, retained receipts and populated V78→V79 history without backfill. Affected enabled test/static analysis and Java formatting pass. The retained v1 vector values are unchanged; obsolete issuer schemas, historical migration names and weaker source guards are not restored. These are controlled storage/source fixtures, not authenticated production mutation, runtime registration, genuine issuer custody or public-admission proof. Earlier snapshots below retain their original source attribution. R1382 strengthens the accepted CLI proof gaps without changing production or fixed vector JSON: every vector collection must be nonempty, malformed non-digest preimages must independently fail sealing, and uppercase logout request IDs fail with a coherent event identity. Corruption fixtures first prove committed, settled source evidence and then require the exact owner or PostgreSQL guard, including SQLSTATE and message for receipt protection. Fifteen Common codec cases and all 15 security-state PostgreSQL cases pass with zero failures, errors or skips, alongside enabled affected static analysis, full Java formatting and documentation checks. Its initial PostgreSQL command failed compilation on a test-only void-lambda error before execution; the corrected native recovery is separate. Canonical first-JOIN membership-event production requires current public-JOIN entitlement; a bare fresh tenant 1/1 baseline is denied and does not preserve admission. Tenant authority requires Account's exact typed tenant event, fresh Game Design provenance, and matching composite generation/source-version and billing coordinates. No entitlement caller wires this producer, so this does not activate public JOIN or gameplay admission. Historical gate 108 passed 593 Account unit cases and five focused shared World hold cases. Later gate 123 passed 598 Account unit cases, and gate 124 passed 27 focused shared-evidence cases across a broader selection; these are distinct executed snapshots and suite scopes, not conflicting totals. jOOQ generation and integration-test compilation passed. Published checkpoint `b5234acd7f93440170178d1b808e19b4a00ac644` subsequently passed required CI. PostgreSQL-backed integration sources, including the later-generation JOIN and exact outbox replay cases, remain unexecuted locally; neither unit proof nor historical CI establishes fresh-image playable proof for subsequent corrections. diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSecurityStateOperationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSecurityStateOperationPostgresIntegrationTest.java index f3e4f29184..1fa9e678d0 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSecurityStateOperationPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSecurityStateOperationPostgresIntegrationTest.java @@ -2,6 +2,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.catchThrowable; import java.nio.charset.StandardCharsets; import java.util.List; @@ -41,6 +42,7 @@ import org.jooq.SQLDialect; import org.jooq.impl.DSL; import org.junit.jupiter.api.Test; +import org.postgresql.util.PSQLException; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; @@ -615,6 +617,17 @@ void corruptPositiveCheckpointMetadataAndPayloadDenyBeforeNewIntentOrSourceMutat Pending first = pending(fixture, seed, state(false), state(true), 0L, new byte[0]); tx(fixture, () -> fixture.operations().claim(first.request(), first.capture())); Event event = producerFixture(fixture, first, false); + var committed = + tx( + fixture, + () -> + fixture.operations().findByRequestId(first.request().requestId()).orElseThrow()); + assertThat(committed.receipt()).isPresent(); + assertThat( + tx( + fixture, + () -> fixture.fences().readSourceChange(first.capture().sourceChange()).status())) + .isEqualTo("SOURCE_COMMITTED"); ScopeState current = tx( fixture, @@ -634,10 +647,15 @@ void corruptPositiveCheckpointMetadataAndPayloadDenyBeforeNewIntentOrSourceMutat fixture.dsl().execute("ALTER TABLE account_authority_outbox_events DISABLE TRIGGER USER"); fixture.dsl().execute("UPDATE account_authority_outbox_events SET " + corruption); fixture.dsl().execute("ALTER TABLE account_authority_outbox_events ENABLE TRIGGER USER"); + String expectedMessage = + corruption.startsWith("payload = ") + ? "Original checkpoint capture differs" + : "Account source event readback is inconsistent"; assertThatThrownBy( () -> tx(fixture, () -> fixture.operations().claim(second.request(), second.capture()))) - .isInstanceOf(RuntimeException.class); + .isExactlyInstanceOf(IllegalStateException.class) + .hasMessage(expectedMessage); assertThat(fixture.dsl().fetchCount(DSL.table("account_security_state_operations"))) .isEqualTo(1); assertThat( @@ -660,6 +678,21 @@ void retainedReceiptCannotLeadRegressedCurrentAuthorityOrCheckpoint() { Pending pending = pending(fixture, seed, state(false), state(true), 0L, new byte[0]); tx(fixture, () -> fixture.operations().claim(pending.request(), pending.capture())); producerFixture(fixture, pending, false); + var committed = + tx( + fixture, + () -> + fixture + .operations() + .findByRequestId(pending.request().requestId()) + .orElseThrow()); + assertThat(committed.receipt()).isPresent(); + assertThat( + tx( + fixture, + () -> + fixture.fences().readSourceChange(pending.capture().sourceChange()).status())) + .isEqualTo("SOURCE_COMMITTED"); fixture.dsl().execute("ALTER TABLE " + table + " DISABLE TRIGGER USER"); fixture .dsl() @@ -668,12 +701,21 @@ void retainedReceiptCannotLeadRegressedCurrentAuthorityOrCheckpoint() { ? "UPDATE account_authority_generations SET generation = 1, source_version = 1" : "UPDATE account_authority_outbox_streams SET last_sequence = 0"); fixture.dsl().execute("ALTER TABLE " + table + " ENABLE TRIGGER USER"); + String expectedMessage = + table.equals("account_authority_generations") + ? "Account source snapshot is inconsistent" + : "Account authority outbox zero checkpoint has event evidence"; + Class expectedException = + table.equals("account_authority_generations") + ? IllegalArgumentException.class + : IllegalStateException.class; assertThatThrownBy( () -> tx( fixture, () -> fixture.operations().findByRequestId(pending.request().requestId()))) - .isInstanceOf(RuntimeException.class); + .isExactlyInstanceOf(expectedException) + .hasMessage(expectedMessage); } } @@ -683,9 +725,50 @@ void missingSecurityReceiptAndChangedCurrentPoststateCannotCommit() { Seed seed = seed(missing); Pending pending = pending(missing, seed, state(false), state(true), 0L, new byte[0]); tx(missing, () -> missing.operations().claim(pending.request(), pending.capture())); - assertThatThrownBy(() -> producerFixture(missing, pending, false, false)) - .isInstanceOf(RuntimeException.class); - assertThat(missing.dsl().fetchCount(DSL.table("account_authority_outbox_events"))).isZero(); + Event event = producerFixture(missing, pending, false); + var committed = + tx( + missing, + () -> + missing.operations().findByRequestId(pending.request().requestId()).orElseThrow()); + assertThat(committed.receipt()).isPresent(); + assertThat( + tx( + missing, + () -> missing.fences().readSourceChange(pending.capture().sourceChange()).status())) + .isEqualTo("SOURCE_COMMITTED"); + ScopeState current = tx(missing, () -> missing.generations().read(seed.source().scope())); + var checkpoint = tx(missing, () -> missing.outbox().readCheckpoint(event.outboxStreamKey())); + assertThat(sourceReader(missing).readCurrent(seed.account().getAccountUuid()).latestEvent()) + .contains(event); + + // Simulate a missing immutable receipt only after proving the original source mutation settled. + missing.dsl().execute("ALTER TABLE account_security_state_operations DISABLE TRIGGER USER"); + try { + assertThat( + missing + .dsl() + .execute( + "DELETE FROM account_security_state_operations WHERE request_id = ?", + pending.request().requestId())) + .isEqualTo(1); + } finally { + missing.dsl().execute("ALTER TABLE account_security_state_operations ENABLE TRIGGER USER"); + } + assertPostgresCheckViolation( + () -> + missing + .dsl() + .execute( + "UPDATE accounts SET email_verified = false WHERE id = ?", + seed.account().getId()), + "V79 security-state event has no exact committed Account operation receipt"); + assertThat(missing.dsl().fetchCount(DSL.table("account_security_state_operations"))).isZero(); + assertThat(missing.dsl().fetchCount(DSL.table("account_authority_outbox_events"))).isEqualTo(1); + assertThat(tx(missing, () -> missing.generations().read(seed.source().scope()))) + .isEqualTo(current); + assertThat(tx(missing, () -> missing.outbox().readCheckpoint(event.outboxStreamKey()))) + .isEqualTo(checkpoint); assertThat( Objects.requireNonNull( missing @@ -695,21 +778,21 @@ void missingSecurityReceiptAndChangedCurrentPoststateCannotCommit() { seed.account().getId()), "Expected persisted Account row after missing-receipt rejection") .get(0, Boolean.class)) - .isFalse(); + .isTrue(); Fixture changed = fixture(null); Seed other = seed(changed); Pending original = pending(changed, other, state(false), state(true), 0L, new byte[0]); tx(changed, () -> changed.operations().claim(original.request(), original.capture())); producerFixture(changed, original, false); - assertThatThrownBy( - () -> - changed - .dsl() - .execute( - "UPDATE accounts SET email_verified = false WHERE id = ?", - other.account().getId())) - .isInstanceOf(RuntimeException.class); + assertPostgresCheckViolation( + () -> + changed + .dsl() + .execute( + "UPDATE accounts SET email_verified = false WHERE id = ?", + other.account().getId()), + "V79 security-state receipt does not bind the exact original and current Account states"); assertThat( Objects.requireNonNull( changed @@ -1340,6 +1423,17 @@ private static T tx(Fixture fixture, Supplier work) { return fixture.transaction().execute(status -> work.get()); } + private static void assertPostgresCheckViolation(Runnable operation, String expectedMessage) { + Throwable failure = catchThrowable(operation::run); + assertThat(failure).isInstanceOf(org.jooq.exception.DataAccessException.class); + Throwable cause = failure; + while (cause.getCause() != null) cause = cause.getCause(); + assertThat(cause) + .isExactlyInstanceOf(PSQLException.class) + .hasMessageContaining(expectedMessage); + assertThat(((PSQLException) cause).getSQLState()).isEqualTo("23514"); + } + private static AccountState state(boolean verified) { return new AccountState(verified, List.of("EMAIL_OTP", "PASSWORD"), List.of(), "ACTIVE"); } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountLogoutAllAuthorityEventV1CodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountLogoutAllAuthorityEventV1CodecTest.java index bb1b25f379..303ae52eb2 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountLogoutAllAuthorityEventV1CodecTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountLogoutAllAuthorityEventV1CodecTest.java @@ -44,7 +44,10 @@ void fixedVectorsVerifySealAndArbitraryPrecisionCounters() throws Exception { assertThat(vectors.path("schemaVersion").asText()) .isEqualTo("account-auth-logout-all-event-vectors/v1"); - for (JsonNode vector : vectors.path("validEvents")) { + JsonNode validEvents = vectors.path("validEvents"); + assertThat(validEvents.isArray()).as("validEvents is an array").isTrue(); + assertThat(validEvents.size()).as("validEvents is nonempty").isPositive(); + for (JsonNode vector : validEvents) { JsonNode wireEvent = vector.path("event"); var verified = AccountLogoutAllAuthorityEventV1Codec.verify(wireEvent.toString()); assertThat(verified.eventDigest()).isEqualTo(vector.path("expectedEventDigest").asText()); @@ -78,7 +81,10 @@ void changedDeclaredFieldsCannotReuseTheOriginalDigest() { ObjectNode baseline = (ObjectNode) vectors.path("validEvents").get(0).path("event").deepCopy(); String originalDigest = baseline.path("eventDigest").asText(); - for (JsonNode mutation : vectors.path("changedDeclaredFieldMutations")) { + JsonNode mutations = vectors.path("changedDeclaredFieldMutations"); + assertThat(mutations.isArray()).as("changedDeclaredFieldMutations is an array").isTrue(); + assertThat(mutations.size()).as("changedDeclaredFieldMutations is nonempty").isPositive(); + for (JsonNode mutation : mutations) { ObjectNode changedWire = (ObjectNode) baseline.deepCopy(); JsonNode changes = mutation.path("changes"); changes @@ -105,7 +111,10 @@ void canonicalPropertyReorderingPreservesTheFixedEvent() { JsonNode vector = vectors.path("validEvents").get(0); JsonNode event = vector.path("event"); ObjectNode reordered = JSON.createObjectNode(); - for (JsonNode field : vectors.path("canonicalReorderedPropertyOrder")) { + JsonNode propertyOrder = vectors.path("canonicalReorderedPropertyOrder"); + assertThat(propertyOrder.isArray()).as("canonicalReorderedPropertyOrder is an array").isTrue(); + assertThat(propertyOrder.size()).as("canonicalReorderedPropertyOrder is nonempty").isPositive(); + for (JsonNode field : propertyOrder) { String fieldName = field.asText(); reordered.set(fieldName, event.path(fieldName).deepCopy()); } @@ -118,15 +127,44 @@ void canonicalPropertyReorderingPreservesTheFixedEvent() { @Test void invalidMutationVectorsAreRejected() { ObjectNode baseline = (ObjectNode) vectors.path("validEvents").get(0).path("event").deepCopy(); - for (JsonNode mutation : vectors.path("invalidMutations")) { + JsonNode mutations = vectors.path("invalidMutations"); + assertThat(mutations.isArray()).as("invalidMutations is an array").isTrue(); + assertThat(mutations.size()).as("invalidMutations is nonempty").isPositive(); + for (JsonNode mutation : mutations) { ObjectNode changed = (ObjectNode) baseline.deepCopy(); applyMutation(changed, mutation); assertThatThrownBy(() -> AccountLogoutAllAuthorityEventV1Codec.verify(changed.toString())) .as(mutation.path("name").asText()) .isInstanceOf(IllegalArgumentException.class); + + if (!"/eventDigest".equals(mutation.path("path").asText())) { + ObjectNode changedPreimage = (ObjectNode) changed.deepCopy(); + changedPreimage.remove("eventDigest"); + Map preimageMap = + JSON.convertValue(changedPreimage, new TypeReference<>() {}); + assertThatThrownBy(() -> AccountLogoutAllAuthorityEventV1Codec.seal(preimageMap)) + .as(mutation.path("name").asText() + " invalid preimage") + .isInstanceOf(IllegalArgumentException.class); + } } } + @Test + void rejectsUppercaseRequestIdWhenEventIdentityBindingMatches() { + String uppercaseRequestId = "22222222-2222-4222-8222-22222222222A"; + ObjectNode changed = (ObjectNode) vectors.path("validEvents").get(0).path("event").deepCopy(); + changed.put("requestId", uppercaseRequestId); + changed.put( + "eventId", AccountLogoutAllAuthorityEventV1Codec.EVENT_ID_PREFIX + uppercaseRequestId); + changed.remove("eventDigest"); + Map preimageMap = JSON.convertValue(changed, new TypeReference<>() {}); + + assertThatThrownBy(() -> AccountLogoutAllAuthorityEventV1Codec.seal(preimageMap)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("requestId") + .hasMessageContaining("canonical lowercase non-nil UUID"); + } + private static void applyMutation(ObjectNode root, JsonNode mutation) { String[] path = mutation.path("path").asText().substring(1).split("/"); JsonNode parent = root; diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/PasswordResetAuthorityEventV1CodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/PasswordResetAuthorityEventV1CodecTest.java index 1b1cbcfece..39c330da6e 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/PasswordResetAuthorityEventV1CodecTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/PasswordResetAuthorityEventV1CodecTest.java @@ -43,7 +43,10 @@ void fixedVectorsVerifySealAndArbitraryPrecisionCounters() throws Exception { assertThat(vectors.path("schemaVersion").asText()) .isEqualTo("account-auth-password-reset-event-vectors/v1"); - for (JsonNode vector : vectors.path("validEvents")) { + JsonNode validEvents = vectors.path("validEvents"); + assertThat(validEvents.isArray()).as("validEvents is an array").isTrue(); + assertThat(validEvents.size()).as("validEvents is nonempty").isPositive(); + for (JsonNode vector : validEvents) { JsonNode wireEvent = vector.path("event"); var verified = PasswordResetAuthorityEventV1Codec.verify(wireEvent.toString()); assertThat(verified.eventDigest()).isEqualTo(vector.path("expectedEventDigest").asText()); @@ -77,7 +80,10 @@ void changedDeclaredFieldsCannotReuseTheOriginalDigest() { ObjectNode baseline = (ObjectNode) vectors.path("validEvents").get(0).path("event").deepCopy(); String originalDigest = baseline.path("eventDigest").asText(); - for (JsonNode mutation : vectors.path("changedDeclaredFieldMutations")) { + JsonNode mutations = vectors.path("changedDeclaredFieldMutations"); + assertThat(mutations.isArray()).as("changedDeclaredFieldMutations is an array").isTrue(); + assertThat(mutations.size()).as("changedDeclaredFieldMutations is nonempty").isPositive(); + for (JsonNode mutation : mutations) { ObjectNode changedWire = (ObjectNode) baseline.deepCopy(); JsonNode changes = mutation.path("changes"); changes @@ -104,7 +110,10 @@ void canonicalPropertyReorderingPreservesTheFixedEvent() { JsonNode vector = vectors.path("validEvents").get(0); JsonNode event = vector.path("event"); ObjectNode reordered = JSON.createObjectNode(); - for (JsonNode field : vectors.path("canonicalReorderedPropertyOrder")) { + JsonNode propertyOrder = vectors.path("canonicalReorderedPropertyOrder"); + assertThat(propertyOrder.isArray()).as("canonicalReorderedPropertyOrder is an array").isTrue(); + assertThat(propertyOrder.size()).as("canonicalReorderedPropertyOrder is nonempty").isPositive(); + for (JsonNode field : propertyOrder) { String fieldName = field.asText(); reordered.set(fieldName, event.path(fieldName).deepCopy()); } @@ -117,12 +126,25 @@ void canonicalPropertyReorderingPreservesTheFixedEvent() { @Test void invalidMutationVectorsAreRejected() { ObjectNode baseline = (ObjectNode) vectors.path("validEvents").get(0).path("event").deepCopy(); - for (JsonNode mutation : vectors.path("invalidMutations")) { + JsonNode mutations = vectors.path("invalidMutations"); + assertThat(mutations.isArray()).as("invalidMutations is an array").isTrue(); + assertThat(mutations.size()).as("invalidMutations is nonempty").isPositive(); + for (JsonNode mutation : mutations) { ObjectNode changed = (ObjectNode) baseline.deepCopy(); applyMutation(changed, mutation); assertThatThrownBy(() -> PasswordResetAuthorityEventV1Codec.verify(changed.toString())) .as(mutation.path("name").asText()) .isInstanceOf(IllegalArgumentException.class); + + if (!"/eventDigest".equals(mutation.path("path").asText())) { + ObjectNode changedPreimage = (ObjectNode) changed.deepCopy(); + changedPreimage.remove("eventDigest"); + Map preimageMap = + JSON.convertValue(changedPreimage, new TypeReference<>() {}); + assertThatThrownBy(() -> PasswordResetAuthorityEventV1Codec.seal(preimageMap)) + .as(mutation.path("name").asText() + " invalid preimage") + .isInstanceOf(IllegalArgumentException.class); + } } }