From 23cd5112e3df7d47a647c4deb2346acfb8e38d8d Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 26 Oct 2026 23:03:12 +1300 Subject: [PATCH 01/26] Retain independently generated issuer binding-local acknowledgements --- ...playIssuerBindingLocalAcknowledgement.java | 463 +++++++++++ ...ssuerBindingLocalAcknowledgementCodec.java | 479 +++++++++++ ...BindingLocalAcknowledgementRepository.java | 757 ++++++++++++++++++ ...ssuerBindingLocalProjectionRepository.java | 19 + ...lGameplayIssuerBindingLocalRedisOwner.java | 15 +- ...l_issuer_binding_local_acknowledgement.sql | 244 ++++++ ...eplayAdmissionAbortCompositionFixture.java | 28 +- ...BindingLocalRedisOwnerIntegrationTest.java | 116 +++ ...rBindingLocalAcknowledgementCodecTest.java | 231 ++++++ 9 files changed, 2345 insertions(+), 7 deletions(-) create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalAcknowledgement.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalAcknowledgementCodec.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalAcknowledgementRepository.java create mode 100644 services/game-session-service/src/main/resources/db/migration/V1039__canonical_issuer_binding_local_acknowledgement.sql create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalAcknowledgementCodecTest.java diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalAcknowledgement.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalAcknowledgement.java new file mode 100644 index 0000000000..daf39ed857 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalAcknowledgement.java @@ -0,0 +1,463 @@ +package net.firedevops.firemud.gamesession.repository; + +import java.math.BigInteger; +import java.util.Arrays; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.gamesession.binding.CanonicalIssuerPartitionReservation; + +/** + * Durable, versioned proof for one ordinary NEW issuer member and its reservation readback. Its + * positive transition evidence generation is issued only with the accepted SQL receipt and is + * separate from both the preparatory member-operation generation and the anchor's global coverage + * generation. This binding-local evidence does not establish issuer-wide coverage, barrier OPEN, or + * tenant admission. + */ +final class CanonicalGameplayIssuerBindingLocalAcknowledgement { + static final int SCHEMA_VERSION = 1; + static final String SCOPE = "ISSUER_BINDING_LOCAL"; + static final String GLOBAL_COVERAGE_GENERATION = "NOT_YET_ISSUED"; + + private final Evidence evidence; + private final byte[] exactBytes; + private final String digest; + + private CanonicalGameplayIssuerBindingLocalAcknowledgement(Evidence evidence, byte[] exactBytes) { + this.evidence = Objects.requireNonNull(evidence, "evidence"); + this.exactBytes = Objects.requireNonNull(exactBytes, "exactBytes").clone(); + this.digest = CanonicalGameplayIssuerMemberV2Codec.sha256(this.exactBytes); + if (!Arrays.equals( + this.exactBytes, + CanonicalGameplayIssuerBindingLocalAcknowledgementCodec.encode(evidence))) { + throw new IllegalArgumentException( + "Issuer binding-local acknowledgement bytes are not canonical"); + } + } + + static CanonicalGameplayIssuerBindingLocalAcknowledgement create(Evidence evidence) { + return new CanonicalGameplayIssuerBindingLocalAcknowledgement( + evidence, CanonicalGameplayIssuerBindingLocalAcknowledgementCodec.encode(evidence)); + } + + static CanonicalGameplayIssuerBindingLocalAcknowledgement decode(byte[] exactBytes) { + Evidence evidence = CanonicalGameplayIssuerBindingLocalAcknowledgementCodec.decode(exactBytes); + return new CanonicalGameplayIssuerBindingLocalAcknowledgement(evidence, exactBytes); + } + + Evidence evidence() { + return evidence; + } + + UUID operationId() { + return evidence.operationId(); + } + + UUID requestId() { + return evidence.requestId(); + } + + UUID transitionId() { + return evidence.transitionId(); + } + + byte[] exactBytes() { + return exactBytes.clone(); + } + + String digest() { + return digest; + } + + record Evidence( + UUID operationId, + BigInteger issuerBindingLocalAcknowledgementGeneration, + UUID requestId, + UUID transitionId, + UUID candidateAccountIndexFence, + String issuerId, + byte[] bindingRef, + BigInteger bindingGeneration, + byte[] memberValueBytes, + String memberValueDigest, + Reservation reservation, + Anchor anchor, + MemberOperation memberOperation, + CurrentSource currentSource, + PhysicalReadback physicalReadback, + Capacity capacity, + String sqlCurrentnessDigest) { + Evidence { + requireNonNil(operationId, "operationId"); + issuerBindingLocalAcknowledgementGeneration = + positive( + issuerBindingLocalAcknowledgementGeneration, + "issuerBindingLocalAcknowledgementGeneration"); + requireNonNil(requestId, "requestId"); + requireNonNil(transitionId, "transitionId"); + requireNonNil(candidateAccountIndexFence, "candidateAccountIndexFence"); + if (requestId.equals(transitionId)) { + throw new IllegalArgumentException("Request and transition identity must be distinct"); + } + if (!GameSessionAccountDelegationProfile.ISSUER.equals(issuerId)) { + throw new IllegalArgumentException("Issuer is not the exact Account environment issuer"); + } + bindingRef = nonEmpty(bindingRef, "bindingRef"); + bindingGeneration = positive(bindingGeneration, "bindingGeneration"); + memberValueBytes = nonEmpty(memberValueBytes, "memberValueBytes"); + memberValueDigest = digest(memberValueDigest, "memberValueDigest"); + reservation = Objects.requireNonNull(reservation, "reservation"); + anchor = Objects.requireNonNull(anchor, "anchor"); + memberOperation = Objects.requireNonNull(memberOperation, "memberOperation"); + currentSource = Objects.requireNonNull(currentSource, "currentSource"); + physicalReadback = Objects.requireNonNull(physicalReadback, "physicalReadback"); + capacity = Objects.requireNonNull(capacity, "capacity"); + sqlCurrentnessDigest = digest(sqlCurrentnessDigest, "sqlCurrentnessDigest"); + + CanonicalGameplayIssuerMemberV2Value member = + CanonicalGameplayIssuerMemberV2Codec.decode(memberValueBytes); + if (!memberValueDigest.equals(CanonicalGameplayIssuerMemberV2Codec.sha256(memberValueBytes)) + || !member.owner().issuerId().equals(issuerId) + || !Arrays.equals(member.owner().bindingRef().bytes(), bindingRef) + || !member.bindingGeneration().equals(bindingGeneration) + || !reservation.matches(member) + || !anchor.matches(member) + || !memberOperation.matches(member) + || !currentSource.matches(member) + || !physicalReadback.matches(memberValueBytes, bindingRef, reservation.reservationId()) + || !capacity.matches(member, physicalReadback)) { + throw new IllegalArgumentException( + "Issuer binding-local acknowledgement differs from its exact member and proof tuples"); + } + } + + @Override + public byte[] bindingRef() { + return bindingRef.clone(); + } + + @Override + public byte[] memberValueBytes() { + return memberValueBytes.clone(); + } + } + + record Reservation( + UUID reservationId, + UUID transitionId, + UUID reservationFence, + BigInteger partitionId, + String lifecycle, + UUID issuerCoverageOperationId, + BigInteger issuerCoverageOperationFence, + BigInteger coverageFence, + BigInteger inventorySnapshotRevision, + BigInteger inventoryRevision) { + Reservation { + requireNonNil(reservationId, "reservationId"); + requireNonNil(transitionId, "reservation transitionId"); + requireNonNil(reservationFence, "reservationFence"); + partitionId = nonNegative(partitionId, "partitionId"); + if (!CanonicalIssuerPartitionReservation.Lifecycle.RESERVED.name().equals(lifecycle)) { + throw new IllegalArgumentException( + "An issuer binding-local acknowledgement requires RESERVED"); + } + requireNonNil(issuerCoverageOperationId, "original issuerCoverageOperationId"); + issuerCoverageOperationFence = + positive(issuerCoverageOperationFence, "original operationFence"); + coverageFence = positive(coverageFence, "original coverageFence"); + inventorySnapshotRevision = + positive(inventorySnapshotRevision, "original inventorySnapshotRevision"); + inventoryRevision = positive(inventoryRevision, "local inventoryRevision"); + } + + private boolean matches(CanonicalGameplayIssuerMemberV2Value member) { + var value = member.reservation(); + return reservationId.equals(value.reservationId()) + && transitionId.equals(value.transitionId()) + && reservationFence.equals(value.reservationFence()) + && partitionId.equals(value.partitionId()) + && lifecycle.equals(value.lifecycle().name()) + && issuerCoverageOperationId.equals(value.issuerCoverageOperationId()) + && issuerCoverageOperationFence.equals(value.issuerCoverageOperationFence()) + && coverageFence.equals(value.coverageFence()) + && inventorySnapshotRevision.equals(value.inventorySnapshotRevision()) + && inventoryRevision.equals(value.inventoryRevision()); + } + } + + record Anchor( + UUID bootstrapOperationId, + UUID issuerCoverageOperationId, + BigInteger operationFence, + BigInteger coverageFence, + BigInteger inventorySnapshotRevision, + BigInteger globalCoverageGeneration, + BigInteger controlEpoch, + BigInteger layoutVersion, + BigInteger partitionCount, + BigInteger partitionCapacity, + String mappingIdentity, + byte[] layoutDescriptorBytes, + String layoutDescriptorDigest, + byte[] exactBytes, + String exactDigest) { + Anchor { + requireNonNil(bootstrapOperationId, "bootstrapOperationId"); + requireNonNil(issuerCoverageOperationId, "anchor issuerCoverageOperationId"); + operationFence = positive(operationFence, "anchor operationFence"); + coverageFence = positive(coverageFence, "anchor coverageFence"); + inventorySnapshotRevision = + positive(inventorySnapshotRevision, "anchor inventorySnapshotRevision"); + globalCoverageGeneration = + positive(globalCoverageGeneration, "anchor globalCoverageGeneration"); + controlEpoch = positive(controlEpoch, "issuerControlEpoch"); + layoutVersion = positive(layoutVersion, "layoutVersion"); + partitionCount = positive(partitionCount, "partitionCount"); + partitionCapacity = positive(partitionCapacity, "partitionCapacity"); + if (operationFence.equals(coverageFence) || !operationFence.equals(controlEpoch)) { + throw new IllegalArgumentException("Installed issuer control tuple is not exact"); + } + if (!bootstrapOperationId.equals(issuerCoverageOperationId)) { + throw new IllegalArgumentException("Installed anchor differs from its bootstrap operation"); + } + if (!CanonicalGameplayIssuerLayoutBootstrapIntent.MAPPING_IDENTITY.equals(mappingIdentity)) { + throw new IllegalArgumentException("Issuer mapping identity is unsupported"); + } + layoutDescriptorBytes = nonEmpty(layoutDescriptorBytes, "layoutDescriptorBytes"); + layoutDescriptorDigest = digest(layoutDescriptorDigest, "layoutDescriptorDigest"); + exactBytes = nonEmpty(exactBytes, "exactAnchorBytes"); + exactDigest = digest(exactDigest, "exactAnchorDigest"); + requireMatches(layoutDescriptorBytes, layoutDescriptorDigest, "layout descriptor"); + requireMatches(exactBytes, exactDigest, "installed anchor"); + } + + @Override + public byte[] layoutDescriptorBytes() { + return layoutDescriptorBytes.clone(); + } + + @Override + public byte[] exactBytes() { + return exactBytes.clone(); + } + + private boolean matches(CanonicalGameplayIssuerMemberV2Value member) { + var value = member.anchor(); + return issuerCoverageOperationId.equals(value.issuerCoverageOperationId()) + && operationFence.equals(value.operationFence()) + && coverageFence.equals(value.coverageFence()) + && inventorySnapshotRevision.equals(value.issuerInventorySnapshotRevision()) + && controlEpoch.equals(member.issuerControlEpoch()) + && layoutVersion.equals(member.layoutDescriptor().layoutVersion()) + && partitionCount.equals(member.layoutDescriptor().partitionCount()) + && partitionCapacity.equals(member.layoutDescriptor().partitionCapacity()) + && mappingIdentity.equals(member.layoutDescriptor().mappingIdentity()) + && Arrays.equals(layoutDescriptorBytes, member.layoutDescriptor().exactDescriptorBytes()); + } + } + + record MemberOperation(UUID operationId, BigInteger operationFence, BigInteger generation) { + MemberOperation { + requireNonNil(operationId, "member operationId"); + operationFence = positive(operationFence, "member operationFence"); + generation = positive(generation, "member operation generation"); + } + + private boolean matches(CanonicalGameplayIssuerMemberV2Value member) { + var value = member.memberOperation(); + return operationId.equals(value.operationId()) + && operationFence.equals(value.operationFence()) + && generation.equals(value.coverageGeneration()); + } + } + + record CurrentSource( + BigInteger issuerAuthGeneration, + byte[] checkpointBytes, + String checkpointDigest, + byte[] eventBytes, + String eventDigest, + byte[] incarnationBytes, + String incarnationDigest) { + CurrentSource { + issuerAuthGeneration = positive(issuerAuthGeneration, "issuerAuthGeneration"); + checkpointBytes = nonEmpty(checkpointBytes, "current source checkpoint bytes"); + checkpointDigest = digest(checkpointDigest, "current source checkpoint digest"); + eventBytes = eventBytes == null ? null : nonEmpty(eventBytes, "current source event bytes"); + eventDigest = eventDigest == null ? null : digest(eventDigest, "current source event digest"); + if ((eventBytes == null) != (eventDigest == null)) { + throw new IllegalArgumentException( + "Current issuer source event bytes and digest must be paired"); + } + incarnationBytes = nonEmpty(incarnationBytes, "current stable incarnation bytes"); + incarnationDigest = digest(incarnationDigest, "current stable incarnation digest"); + requireMatches(checkpointBytes, checkpointDigest, "current source checkpoint"); + if (eventBytes != null) requireMatches(eventBytes, eventDigest, "current source event"); + requireMatches(incarnationBytes, incarnationDigest, "current stable incarnation"); + } + + @Override + public byte[] checkpointBytes() { + return checkpointBytes.clone(); + } + + @Override + public byte[] eventBytes() { + return eventBytes == null ? null : eventBytes.clone(); + } + + @Override + public byte[] incarnationBytes() { + return incarnationBytes.clone(); + } + + private boolean matches(CanonicalGameplayIssuerMemberV2Value member) { + var source = member.sourceCheckpoint(); + return issuerAuthGeneration.equals(member.owner().issuerAuthGeneration()) + && Arrays.equals(checkpointBytes, source.exactCheckpointBytes()) + && checkpointDigest.equals(source.checkpointDigest()) + && Arrays.equals(eventBytes, source.latestIssuerEventBytes()) + && Objects.equals(eventDigest, source.latestIssuerEventDigest()) + && Arrays.equals( + incarnationBytes, + CanonicalGameplayIssuerInstalledAnchor.encodeIncarnation(member.incarnation())); + } + } + + record PhysicalReadback( + byte[] bindingValueBytes, + String bindingValueDigest, + byte[] capacityValueBytes, + String capacityValueDigest, + String partitionFieldSetDigest, + int scriptOutcome, + int fieldCount, + int reservationCount, + int bindingCount, + int countedCapacity) { + PhysicalReadback { + bindingValueBytes = nonEmpty(bindingValueBytes, "physical binding readback"); + bindingValueDigest = digest(bindingValueDigest, "physical binding readback digest"); + capacityValueBytes = nonEmpty(capacityValueBytes, "physical capacity readback"); + capacityValueDigest = digest(capacityValueDigest, "physical capacity readback digest"); + partitionFieldSetDigest = digest(partitionFieldSetDigest, "physical field-set digest"); + if (scriptOutcome < 1 || scriptOutcome > 3) { + throw new IllegalArgumentException("Physical issuer script outcome is unsupported"); + } + if (fieldCount < 1 || reservationCount < 1 || bindingCount < 1 || countedCapacity < 1) { + throw new IllegalArgumentException("Physical issuer readback counts must be positive"); + } + if (fieldCount != 1 + reservationCount + bindingCount || bindingCount > reservationCount) { + throw new IllegalArgumentException("Physical issuer field counts are inconsistent"); + } + requireMatches(bindingValueBytes, bindingValueDigest, "physical binding value"); + requireMatches(capacityValueBytes, capacityValueDigest, "physical capacity value"); + if (!Arrays.equals(bindingValueBytes, capacityValueBytes)) { + throw new IllegalArgumentException("Binding and reservation readbacks differ"); + } + } + + @Override + public byte[] bindingValueBytes() { + return bindingValueBytes.clone(); + } + + @Override + public byte[] capacityValueBytes() { + return capacityValueBytes.clone(); + } + + private boolean matches(byte[] memberBytes, byte[] bindingRef, UUID reservationId) { + if (!Arrays.equals(bindingValueBytes, memberBytes) + || !Arrays.equals(capacityValueBytes, memberBytes)) return false; + var member = CanonicalGameplayIssuerMemberV2Codec.decode(memberBytes); + return Arrays.equals(member.owner().bindingRef().bytes(), bindingRef) + && reservationId.equals(member.reservation().reservationId()); + } + } + + record Capacity( + BigInteger partitionId, + BigInteger partitionCapacity, + BigInteger baselineCountedCapacity, + BigInteger baselineReservationCount, + BigInteger baselineBindingCount, + BigInteger sqlPartitionCapacity, + BigInteger sqlAggregateCapacity, + BigInteger issuerAggregateBound) { + Capacity { + partitionId = nonNegative(partitionId, "capacity partitionId"); + partitionCapacity = positive(partitionCapacity, "capacity partitionCapacity"); + baselineCountedCapacity = nonNegative(baselineCountedCapacity, "baselineCountedCapacity"); + baselineReservationCount = nonNegative(baselineReservationCount, "baselineReservationCount"); + baselineBindingCount = nonNegative(baselineBindingCount, "baselineBindingCount"); + sqlPartitionCapacity = positive(sqlPartitionCapacity, "sqlPartitionCapacity"); + sqlAggregateCapacity = nonNegative(sqlAggregateCapacity, "sqlAggregateCapacity"); + issuerAggregateBound = positive(issuerAggregateBound, "issuerAggregateBound"); + if (baselineCountedCapacity.compareTo(partitionCapacity) > 0 + || sqlPartitionCapacity.compareTo(partitionCapacity) > 0 + || sqlAggregateCapacity.signum() == 0 + || sqlAggregateCapacity.compareTo(issuerAggregateBound) > 0) { + throw new IllegalArgumentException("Issuer local capacity proof exceeds its pinned bound"); + } + } + + private boolean matches( + CanonicalGameplayIssuerMemberV2Value member, PhysicalReadback readback) { + return partitionId.equals(member.reservation().partitionId()) + && partitionCapacity.equals(member.layoutDescriptor().partitionCapacity()) + && partitionId.compareTo(member.layoutDescriptor().partitionCount()) < 0 + && BigInteger.valueOf(readback.countedCapacity()).compareTo(partitionCapacity) <= 0 + && BigInteger.valueOf(readback.countedCapacity()) + .compareTo(baselineCountedCapacity.add(BigInteger.ONE)) + >= 0 + && BigInteger.valueOf(readback.reservationCount()) + .compareTo(baselineReservationCount.add(BigInteger.ONE)) + >= 0 + && BigInteger.valueOf(readback.bindingCount()) + .compareTo(baselineBindingCount.add(BigInteger.ONE)) + >= 0 + && BigInteger.valueOf(readback.countedCapacity()).compareTo(sqlPartitionCapacity) <= 0 + && sqlPartitionCapacity.compareTo(baselineCountedCapacity.add(BigInteger.ONE)) >= 0; + } + } + + private static void requireNonNil(UUID value, String name) { + Objects.requireNonNull(value, name); + if (value.equals(new UUID(0L, 0L))) + throw new IllegalArgumentException(name + " must not be nil"); + } + + private static byte[] nonEmpty(byte[] value, String name) { + Objects.requireNonNull(value, name); + if (value.length == 0) throw new IllegalArgumentException(name + " must not be empty"); + return value.clone(); + } + + private static BigInteger positive(BigInteger value, String name) { + Objects.requireNonNull(value, name); + if (value.signum() <= 0) throw new IllegalArgumentException(name + " must be positive"); + return value; + } + + private static BigInteger nonNegative(BigInteger value, String name) { + Objects.requireNonNull(value, name); + if (value.signum() < 0) throw new IllegalArgumentException(name + " must not be negative"); + return value; + } + + private static String digest(String value, String name) { + Objects.requireNonNull(value, name); + if (!value.matches("sha256:[0-9a-f]{64}")) { + throw new IllegalArgumentException(name + " must be canonical SHA-256"); + } + return value; + } + + private static void requireMatches(byte[] value, String expected, String name) { + if (!CanonicalGameplayIssuerMemberV2Codec.sha256(value).equals(expected)) { + throw new IllegalArgumentException(name + " digest does not match its exact bytes"); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalAcknowledgementCodec.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalAcknowledgementCodec.java new file mode 100644 index 0000000000..1ea58dd5b5 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalAcknowledgementCodec.java @@ -0,0 +1,479 @@ +package net.firedevops.firemud.gamesession.repository; + +import com.fasterxml.jackson.core.JsonFactory; +import com.fasterxml.jackson.core.StreamReadConstraints; +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.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.Base64; +import java.util.Iterator; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; + +/** Closed, bounded RFC 8785 codec for the separate issuer binding-local acknowledgement. */ +final class CanonicalGameplayIssuerBindingLocalAcknowledgementCodec { + static final int MAX_ACKNOWLEDGEMENT_BYTES = 1024 * 1024; + private static final Pattern POSITIVE_DECIMAL = Pattern.compile("[1-9][0-9]{0,255}"); + private static final Pattern NON_NEGATIVE_DECIMAL = Pattern.compile("(?:0|[1-9][0-9]{0,255})"); + private static final Pattern SHA256 = Pattern.compile("sha256:[0-9a-f]{64}"); + private static final JsonFactory JSON_FACTORY = + JsonFactory.builder() + .streamReadConstraints( + StreamReadConstraints.builder() + .maxNestingDepth(8) + .maxStringLength(MAX_ACKNOWLEDGEMENT_BYTES) + .maxNumberLength(8) + .build()) + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .build(); + private static final ObjectMapper JSON = + new ObjectMapper(JSON_FACTORY).enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS); + private static final Set ROOT_FIELDS = + Set.of( + "schemaVersion", + "scope", + "issuerBindingLocalAcknowledgementGeneration", + "globalIssuerCoverageGeneration", + "operation", + "binding", + "reservation", + "anchor", + "memberOperation", + "currentSource", + "physicalReadback", + "capacity", + "sqlCurrentnessDigest"); + private static final Set OPERATION_FIELDS = + Set.of("issuerId", "operationId", "requestId", "transitionId", "candidateAccountIndexFence"); + private static final Set BINDING_FIELDS = + Set.of("bindingRef", "bindingGeneration", "memberValueBytes", "memberValueDigest"); + private static final Set RESERVATION_FIELDS = + Set.of( + "reservationId", + "transitionId", + "reservationFence", + "partitionId", + "lifecycle", + "issuerCoverageOperationId", + "issuerCoverageOperationFence", + "coverageFence", + "inventorySnapshotRevision", + "inventoryRevision"); + private static final Set ANCHOR_FIELDS = + Set.of( + "bootstrapOperationId", + "issuerCoverageOperationId", + "operationFence", + "coverageFence", + "inventorySnapshotRevision", + "globalCoverageGeneration", + "controlEpoch", + "layoutVersion", + "partitionCount", + "partitionCapacity", + "mappingIdentity", + "layoutDescriptorBytes", + "layoutDescriptorDigest", + "exactBytes", + "exactDigest"); + private static final Set MEMBER_OPERATION_FIELDS = + Set.of("operationId", "operationFence", "generation"); + private static final Set CURRENT_SOURCE_FIELDS = + Set.of( + "issuerAuthGeneration", + "checkpointBytes", + "checkpointDigest", + "eventBytes", + "eventDigest", + "incarnationBytes", + "incarnationDigest"); + private static final Set PHYSICAL_READBACK_FIELDS = + Set.of( + "bindingValueBytes", + "bindingValueDigest", + "capacityValueBytes", + "capacityValueDigest", + "partitionFieldSetDigest", + "scriptOutcome", + "fieldCount", + "reservationCount", + "bindingCount", + "countedCapacity"); + private static final Set CAPACITY_FIELDS = + Set.of( + "partitionId", + "partitionCapacity", + "baselineCountedCapacity", + "baselineReservationCount", + "baselineBindingCount", + "sqlPartitionCapacity", + "sqlAggregateCapacity", + "issuerAggregateBound"); + + private CanonicalGameplayIssuerBindingLocalAcknowledgementCodec() {} + + static byte[] encode(CanonicalGameplayIssuerBindingLocalAcknowledgement.Evidence evidence) { + Objects.requireNonNull(evidence, "evidence"); + try { + ObjectNode root = JSON.createObjectNode(); + root.put("schemaVersion", CanonicalGameplayIssuerBindingLocalAcknowledgement.SCHEMA_VERSION); + root.put("scope", CanonicalGameplayIssuerBindingLocalAcknowledgement.SCOPE); + root.put( + "issuerBindingLocalAcknowledgementGeneration", + evidence.issuerBindingLocalAcknowledgementGeneration().toString()); + root.put( + "globalIssuerCoverageGeneration", + CanonicalGameplayIssuerBindingLocalAcknowledgement.GLOBAL_COVERAGE_GENERATION); + + var operation = root.putObject("operation"); + operation.put("issuerId", evidence.issuerId()); + operation.put("operationId", evidence.operationId().toString()); + operation.put("requestId", evidence.requestId().toString()); + operation.put("transitionId", evidence.transitionId().toString()); + operation.put("candidateAccountIndexFence", evidence.candidateAccountIndexFence().toString()); + + var binding = root.putObject("binding"); + binding.put("bindingRef", encodeBase64(evidence.bindingRef())); + binding.put("bindingGeneration", evidence.bindingGeneration().toString()); + binding.put("memberValueBytes", encodeBase64(evidence.memberValueBytes())); + binding.put("memberValueDigest", evidence.memberValueDigest()); + + var reservation = root.putObject("reservation"); + var r = evidence.reservation(); + reservation.put("reservationId", r.reservationId().toString()); + reservation.put("transitionId", r.transitionId().toString()); + reservation.put("reservationFence", r.reservationFence().toString()); + reservation.put("partitionId", r.partitionId().toString()); + reservation.put("lifecycle", r.lifecycle()); + reservation.put("issuerCoverageOperationId", r.issuerCoverageOperationId().toString()); + reservation.put("issuerCoverageOperationFence", r.issuerCoverageOperationFence().toString()); + reservation.put("coverageFence", r.coverageFence().toString()); + reservation.put("inventorySnapshotRevision", r.inventorySnapshotRevision().toString()); + reservation.put("inventoryRevision", r.inventoryRevision().toString()); + + var anchor = root.putObject("anchor"); + var a = evidence.anchor(); + anchor.put("bootstrapOperationId", a.bootstrapOperationId().toString()); + anchor.put("issuerCoverageOperationId", a.issuerCoverageOperationId().toString()); + anchor.put("operationFence", a.operationFence().toString()); + anchor.put("coverageFence", a.coverageFence().toString()); + anchor.put("inventorySnapshotRevision", a.inventorySnapshotRevision().toString()); + anchor.put("globalCoverageGeneration", a.globalCoverageGeneration().toString()); + anchor.put("controlEpoch", a.controlEpoch().toString()); + anchor.put("layoutVersion", a.layoutVersion().toString()); + anchor.put("partitionCount", a.partitionCount().toString()); + anchor.put("partitionCapacity", a.partitionCapacity().toString()); + anchor.put("mappingIdentity", a.mappingIdentity()); + anchor.put("layoutDescriptorBytes", encodeBase64(a.layoutDescriptorBytes())); + anchor.put("layoutDescriptorDigest", a.layoutDescriptorDigest()); + anchor.put("exactBytes", encodeBase64(a.exactBytes())); + anchor.put("exactDigest", a.exactDigest()); + + var memberOperation = root.putObject("memberOperation"); + memberOperation.put("operationId", evidence.memberOperation().operationId().toString()); + memberOperation.put("operationFence", evidence.memberOperation().operationFence().toString()); + memberOperation.put("generation", evidence.memberOperation().generation().toString()); + + var source = root.putObject("currentSource"); + var s = evidence.currentSource(); + source.put("issuerAuthGeneration", s.issuerAuthGeneration().toString()); + source.put("checkpointBytes", encodeBase64(s.checkpointBytes())); + source.put("checkpointDigest", s.checkpointDigest()); + source.put("eventBytes", s.eventBytes() == null ? null : encodeBase64(s.eventBytes())); + source.put("eventDigest", s.eventDigest()); + source.put("incarnationBytes", encodeBase64(s.incarnationBytes())); + source.put("incarnationDigest", s.incarnationDigest()); + + var physical = root.putObject("physicalReadback"); + var p = evidence.physicalReadback(); + physical.put("bindingValueBytes", encodeBase64(p.bindingValueBytes())); + physical.put("bindingValueDigest", p.bindingValueDigest()); + physical.put("capacityValueBytes", encodeBase64(p.capacityValueBytes())); + physical.put("capacityValueDigest", p.capacityValueDigest()); + physical.put("partitionFieldSetDigest", p.partitionFieldSetDigest()); + physical.put("scriptOutcome", p.scriptOutcome()); + physical.put("fieldCount", p.fieldCount()); + physical.put("reservationCount", p.reservationCount()); + physical.put("bindingCount", p.bindingCount()); + physical.put("countedCapacity", p.countedCapacity()); + + var capacity = root.putObject("capacity"); + var c = evidence.capacity(); + capacity.put("partitionId", c.partitionId().toString()); + capacity.put("partitionCapacity", c.partitionCapacity().toString()); + capacity.put("baselineCountedCapacity", c.baselineCountedCapacity().toString()); + capacity.put("baselineReservationCount", c.baselineReservationCount().toString()); + capacity.put("baselineBindingCount", c.baselineBindingCount().toString()); + capacity.put("sqlPartitionCapacity", c.sqlPartitionCapacity().toString()); + capacity.put("sqlAggregateCapacity", c.sqlAggregateCapacity().toString()); + capacity.put("issuerAggregateBound", c.issuerAggregateBound().toString()); + root.put("sqlCurrentnessDigest", evidence.sqlCurrentnessDigest()); + + byte[] result = Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(root)); + if (result.length == 0 || result.length > MAX_ACKNOWLEDGEMENT_BYTES) { + throw invalid("Issuer binding-local acknowledgement exceeds its 1 MiB bound"); + } + return result; + } catch (IOException failure) { + throw new IllegalArgumentException( + "Could not encode issuer binding-local acknowledgement", failure); + } + } + + static CanonicalGameplayIssuerBindingLocalAcknowledgement.Evidence decode(byte[] encoded) { + Objects.requireNonNull(encoded, "encoded"); + if (encoded.length == 0 || encoded.length > MAX_ACKNOWLEDGEMENT_BYTES) { + throw invalid("Issuer binding-local acknowledgement is empty or exceeds its bound"); + } + JsonNode root = parse(encoded); + requireFields(root, ROOT_FIELDS, "root"); + if (intValue(root, "schemaVersion") + != CanonicalGameplayIssuerBindingLocalAcknowledgement.SCHEMA_VERSION + || !text(root, "scope").equals(CanonicalGameplayIssuerBindingLocalAcknowledgement.SCOPE) + || !text(root, "globalIssuerCoverageGeneration") + .equals( + CanonicalGameplayIssuerBindingLocalAcknowledgement.GLOBAL_COVERAGE_GENERATION)) { + throw invalid("Issuer binding-local acknowledgement version or scope is unsupported"); + } + + JsonNode operation = object(root, "operation", OPERATION_FIELDS); + JsonNode binding = object(root, "binding", BINDING_FIELDS); + JsonNode reservation = object(root, "reservation", RESERVATION_FIELDS); + JsonNode anchor = object(root, "anchor", ANCHOR_FIELDS); + JsonNode memberOperation = object(root, "memberOperation", MEMBER_OPERATION_FIELDS); + JsonNode currentSource = object(root, "currentSource", CURRENT_SOURCE_FIELDS); + JsonNode physicalReadback = object(root, "physicalReadback", PHYSICAL_READBACK_FIELDS); + JsonNode capacity = object(root, "capacity", CAPACITY_FIELDS); + + CanonicalGameplayIssuerBindingLocalAcknowledgement.Reservation reservationValue = + new CanonicalGameplayIssuerBindingLocalAcknowledgement.Reservation( + uuid(reservation, "reservationId"), + uuid(reservation, "transitionId"), + uuid(reservation, "reservationFence"), + nonNegative(reservation, "partitionId"), + text(reservation, "lifecycle"), + uuid(reservation, "issuerCoverageOperationId"), + positive(reservation, "issuerCoverageOperationFence"), + positive(reservation, "coverageFence"), + positive(reservation, "inventorySnapshotRevision"), + positive(reservation, "inventoryRevision")); + CanonicalGameplayIssuerBindingLocalAcknowledgement.Anchor anchorValue = + new CanonicalGameplayIssuerBindingLocalAcknowledgement.Anchor( + uuid(anchor, "bootstrapOperationId"), + uuid(anchor, "issuerCoverageOperationId"), + positive(anchor, "operationFence"), + positive(anchor, "coverageFence"), + positive(anchor, "inventorySnapshotRevision"), + positive(anchor, "globalCoverageGeneration"), + positive(anchor, "controlEpoch"), + positive(anchor, "layoutVersion"), + positive(anchor, "partitionCount"), + positive(anchor, "partitionCapacity"), + text(anchor, "mappingIdentity"), + base64(anchor, "layoutDescriptorBytes"), + digest(anchor, "layoutDescriptorDigest"), + base64(anchor, "exactBytes"), + digest(anchor, "exactDigest")); + CanonicalGameplayIssuerBindingLocalAcknowledgement.MemberOperation memberOperationValue = + new CanonicalGameplayIssuerBindingLocalAcknowledgement.MemberOperation( + uuid(memberOperation, "operationId"), + positive(memberOperation, "operationFence"), + positive(memberOperation, "generation")); + CanonicalGameplayIssuerBindingLocalAcknowledgement.CurrentSource currentSourceValue = + new CanonicalGameplayIssuerBindingLocalAcknowledgement.CurrentSource( + positive(currentSource, "issuerAuthGeneration"), + base64(currentSource, "checkpointBytes"), + digest(currentSource, "checkpointDigest"), + nullableBase64(currentSource, "eventBytes"), + nullableDigest(currentSource, "eventDigest"), + base64(currentSource, "incarnationBytes"), + digest(currentSource, "incarnationDigest")); + CanonicalGameplayIssuerBindingLocalAcknowledgement.PhysicalReadback physicalReadbackValue = + new CanonicalGameplayIssuerBindingLocalAcknowledgement.PhysicalReadback( + base64(physicalReadback, "bindingValueBytes"), + digest(physicalReadback, "bindingValueDigest"), + base64(physicalReadback, "capacityValueBytes"), + digest(physicalReadback, "capacityValueDigest"), + digest(physicalReadback, "partitionFieldSetDigest"), + intValue(physicalReadback, "scriptOutcome"), + nonNegativeInt(physicalReadback, "fieldCount"), + nonNegativeInt(physicalReadback, "reservationCount"), + nonNegativeInt(physicalReadback, "bindingCount"), + nonNegativeInt(physicalReadback, "countedCapacity")); + CanonicalGameplayIssuerBindingLocalAcknowledgement.Capacity capacityValue = + new CanonicalGameplayIssuerBindingLocalAcknowledgement.Capacity( + nonNegative(capacity, "partitionId"), + positive(capacity, "partitionCapacity"), + nonNegative(capacity, "baselineCountedCapacity"), + nonNegative(capacity, "baselineReservationCount"), + nonNegative(capacity, "baselineBindingCount"), + positive(capacity, "sqlPartitionCapacity"), + nonNegative(capacity, "sqlAggregateCapacity"), + positive(capacity, "issuerAggregateBound")); + + var evidence = + new CanonicalGameplayIssuerBindingLocalAcknowledgement.Evidence( + uuid(operation, "operationId"), + positive(root, "issuerBindingLocalAcknowledgementGeneration"), + uuid(operation, "requestId"), + uuid(operation, "transitionId"), + uuid(operation, "candidateAccountIndexFence"), + text(operation, "issuerId"), + base64(binding, "bindingRef"), + positive(binding, "bindingGeneration"), + base64(binding, "memberValueBytes"), + digest(binding, "memberValueDigest"), + reservationValue, + anchorValue, + memberOperationValue, + currentSourceValue, + physicalReadbackValue, + capacityValue, + digest(root, "sqlCurrentnessDigest")); + if (!Arrays.equals(encoded, encode(evidence))) { + throw invalid("Issuer binding-local acknowledgement is not canonical"); + } + return evidence; + } + + private static JsonNode parse(byte[] encoded) { + try { + String json = + StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(encoded)) + .toString(); + JsonNode root = JSON.readTree(json); + if (root == null || !root.isObject()) throw invalid("Acknowledgement root must be an object"); + return root; + } catch (IOException malformed) { + throw new IllegalArgumentException( + "Issuer binding-local acknowledgement is malformed", malformed); + } + } + + private static JsonNode object(JsonNode parent, String name, Set fields) { + JsonNode value = parent.get(name); + requireFields(value, fields, name); + return value; + } + + private static void requireFields(JsonNode value, Set expected, String name) { + if (value == null || !value.isObject()) throw invalid(name + " must be an object"); + Set actual = new java.util.HashSet<>(); + Iterator names = value.fieldNames(); + while (names.hasNext()) actual.add(names.next()); + if (!actual.equals(expected)) throw invalid(name + " contains missing or unknown fields"); + } + + private static String text(JsonNode object, String field) { + JsonNode value = object.get(field); + if (value == null || !value.isTextual() || value.textValue().isEmpty()) { + throw invalid(field + " must be nonempty text"); + } + return value.textValue(); + } + + private static int intValue(JsonNode object, String field) { + JsonNode value = object.get(field); + if (value == null || !value.isIntegralNumber() || !value.canConvertToInt()) { + throw invalid(field + " must be an exact integer"); + } + return value.intValue(); + } + + private static int nonNegativeInt(JsonNode object, String field) { + int value = intValue(object, field); + if (value < 0) throw invalid(field + " must not be negative"); + return value; + } + + private static BigInteger positive(JsonNode object, String field) { + return decimal(text(object, field), field, true); + } + + private static BigInteger nonNegative(JsonNode object, String field) { + return decimal(text(object, field), field, false); + } + + private static BigInteger decimal(String value, String name, boolean positive) { + Pattern pattern = positive ? POSITIVE_DECIMAL : NON_NEGATIVE_DECIMAL; + if (!pattern.matcher(value).matches()) throw invalid(name + " is not canonical decimal"); + return new BigInteger(value); + } + + private static UUID uuid(JsonNode object, String field) { + String value = text(object, field); + try { + UUID parsed = UUID.fromString(value); + if (!parsed.toString().equals(value) || parsed.equals(new UUID(0L, 0L))) { + throw invalid(field + " is not a canonical non-nil UUID"); + } + return parsed; + } catch (IllegalArgumentException malformed) { + throw invalid(field + " is not a canonical non-nil UUID", malformed); + } + } + + private static String digest(JsonNode object, String field) { + String value = text(object, field); + if (!SHA256.matcher(value).matches()) throw invalid(field + " is not canonical SHA-256"); + return value; + } + + private static String nullableDigest(JsonNode object, String field) { + JsonNode value = object.get(field); + if (value == null || value.isNull()) return null; + if (!value.isTextual() || !SHA256.matcher(value.textValue()).matches()) { + throw invalid(field + " is not canonical SHA-256 or null"); + } + return value.textValue(); + } + + private static byte[] base64(JsonNode object, String field) { + String value = text(object, field); + try { + byte[] decoded = Base64.getDecoder().decode(value); + if (decoded.length == 0 || !Base64.getEncoder().encodeToString(decoded).equals(value)) { + throw invalid(field + " is not canonical padded Base64"); + } + return decoded; + } catch (IllegalArgumentException malformed) { + throw invalid(field + " is not canonical padded Base64", malformed); + } + } + + private static byte[] nullableBase64(JsonNode object, String field) { + JsonNode value = object.get(field); + if (value == null || value.isNull()) return null; + if (!value.isTextual()) throw invalid(field + " must be canonical Base64 or null"); + ObjectNode wrapper = JSON.createObjectNode(); + wrapper.set(field, value); + return base64(wrapper, field); + } + + private static String encodeBase64(byte[] value) { + return Base64.getEncoder().encodeToString(value); + } + + private static IllegalArgumentException invalid(String message) { + return new IllegalArgumentException(message); + } + + private static IllegalArgumentException invalid(String message, Throwable cause) { + return new IllegalArgumentException(message, cause); + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalAcknowledgementRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalAcknowledgementRepository.java new file mode 100644 index 0000000000..6cf2a3966f --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalAcknowledgementRepository.java @@ -0,0 +1,757 @@ +package net.firedevops.firemud.gamesession.repository; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.gamesession.binding.CanonicalIssuerPartitionReservation; +import net.firedevops.firemud.gamesession.repository.CanonicalGameplayIssuerBindingLocalAcknowledgement.Anchor; +import net.firedevops.firemud.gamesession.repository.CanonicalGameplayIssuerBindingLocalAcknowledgement.Capacity; +import net.firedevops.firemud.gamesession.repository.CanonicalGameplayIssuerBindingLocalAcknowledgement.CurrentSource; +import net.firedevops.firemud.gamesession.repository.CanonicalGameplayIssuerBindingLocalAcknowledgement.Evidence; +import net.firedevops.firemud.gamesession.repository.CanonicalGameplayIssuerBindingLocalAcknowledgement.MemberOperation; +import net.firedevops.firemud.gamesession.repository.CanonicalGameplayIssuerBindingLocalAcknowledgement.PhysicalReadback; +import net.firedevops.firemud.gamesession.repository.CanonicalGameplayIssuerBindingLocalAcknowledgement.Reservation; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** SQL owner for immutable ordinary NEW issuer binding-local physical acknowledgement receipts. */ +final class CanonicalGameplayIssuerBindingLocalAcknowledgementRepository { + private static final String ACKNOWLEDGEMENT = + "game_session_canonical_issuer_binding_local_acknowledgement"; + private static final String GENERATION_COUNTER = + "game_session_canonical_issuer_binding_local_ack_gen_counter"; + private static final int MAX_FIELD_COUNT = + CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.MAX_HASH_FIELDS + + 2 * CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.MAX_MEMBER_OPERATIONS; + + private final DSLContext dsl; + private final CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerStateSource + currentIssuerStateSource; + private final CanonicalGameplayIssuerBindingLocalProjectionRepository projectionRepository; + + CanonicalGameplayIssuerBindingLocalAcknowledgementRepository( + DSLContext dsl, + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerStateSource + currentIssuerStateSource) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + this.currentIssuerStateSource = + Objects.requireNonNull(currentIssuerStateSource, "currentIssuerStateSource"); + this.projectionRepository = + new CanonicalGameplayIssuerBindingLocalProjectionRepository(dsl, currentIssuerStateSource); + } + + /** + * Records the exact first physical acknowledgement only from the private readback produced by the + * real one-key Redis owner. SQL rechecks the installed anchor and all current source rows under + * the inventory clock; no transaction spans Redis or the external current-source reads. + */ + CanonicalGameplayIssuerBindingLocalAcknowledgement acknowledge( + CanonicalGameplayIssuerBindingLocalRedisOwner.Readback readback) { + Objects.requireNonNull(readback, "readback"); + requireNoAmbientTransaction(); + CanonicalGameplayIssuerBindingLocalOperation operation = readback.operation(); + var before = readCurrentIssuerState("before acknowledgement"); + CanonicalGameplayIssuerBindingLocalAcknowledgement acknowledged = + dsl.transactionResult( + configuration -> { + DSLContext transaction = org.jooq.impl.DSL.using(configuration); + CanonicalGameplayBindingInventoryRepository.lockInventoryRevision(transaction); + var work = + projectionRepository.readPreparedPartitionWorkInTransaction( + transaction, operation, before); + requireCurrentIssuerSource(operation, before); + requireEligibleCandidate(work); + + Record existing = + transaction.fetchOne( + "SELECT * FROM " + ACKNOWLEDGEMENT + " WHERE operation_id = ? FOR UPDATE", + operation.operationId()); + if (existing != null) { + var prior = readAcknowledgement(transaction, existing); + requireSameOperation(prior.evidence(), operation); + requireSameCurrentSources(prior.evidence(), operation, before); + requireReadbackTargetStillMatches(prior.evidence(), readback); + return prior; + } + + if (!Arrays.equals(readback.sqlCurrentnessDigest(), work.sqlCurrentnessDigest())) { + throw unavailable( + "SQL issuer cohort changed after physical readback; retry the original operation"); + } + ReadbackProof proof = validateReadback(operation, work, readback, before); + // The independent transition generation advances only in this SQL transaction, + // after both the exact current SQL operation and private physical readback validate. + // Counter advancement and immutable receipt insertion commit or roll back together. + BigInteger acknowledgementGeneration = + allocateAcknowledgementGeneration(transaction, operation.anchor().issuerId()); + Evidence evidence = + buildEvidence(operation, readback, before, proof, acknowledgementGeneration); + var result = CanonicalGameplayIssuerBindingLocalAcknowledgement.create(evidence); + insert(transaction, result); + Record stored = + transaction.fetchOne( + "SELECT * FROM " + ACKNOWLEDGEMENT + " WHERE operation_id = ? FOR UPDATE", + operation.operationId()); + if (stored == null) throw unavailable("Durable issuer acknowledgement disappeared"); + var durable = readAcknowledgement(transaction, stored); + if (!Arrays.equals(result.exactBytes(), durable.exactBytes()) + || !result.digest().equals(durable.digest())) { + throw unavailable( + "Durable issuer acknowledgement readback differs from its source"); + } + return durable; + }); + var after = readCurrentIssuerState("after acknowledgement"); + if (!sameCurrentIssuerState(before, after)) { + throw unavailable( + "Issuer source or storage incarnation moved after acknowledgement persistence; the exact historical receipt remains retained"); + } + return acknowledged; + } + + /** Reads and integrity-checks retained evidence without implying that it is currently usable. */ + CanonicalGameplayIssuerBindingLocalAcknowledgement readHistorical(UUID operationId) { + Objects.requireNonNull(operationId, "operationId"); + requireNoAmbientTransaction(); + Record row = + dsl.fetchOne("SELECT * FROM " + ACKNOWLEDGEMENT + " WHERE operation_id = ?", operationId); + if (row == null) return null; + return readAcknowledgement(dsl, row); + } + + private void insert( + DSLContext transaction, CanonicalGameplayIssuerBindingLocalAcknowledgement acknowledgement) { + Evidence evidence = acknowledgement.evidence(); + Reservation reservation = evidence.reservation(); + Anchor anchor = evidence.anchor(); + MemberOperation memberOperation = evidence.memberOperation(); + transaction.execute( + "INSERT INTO " + + ACKNOWLEDGEMENT + + " (operation_id, acknowledgement_generation, issuer_id, request_id, transition_id, binding_ref, binding_generation," + + " reservation_id, reservation_fence, original_issuer_coverage_operation_id," + + " original_issuer_coverage_operation_fence, original_coverage_fence," + + " original_inventory_snapshot_revision, original_inventory_revision," + + " anchor_bootstrap_operation_id, anchor_issuer_coverage_operation_id," + + " anchor_operation_fence, anchor_coverage_fence, anchor_inventory_snapshot_revision," + + " anchor_global_coverage_generation," + + " issuer_control_epoch, local_member_operation_id, local_member_operation_fence," + + " local_member_generation, physical_partition_id, physical_field_set_digest," + + " sql_currentness_digest, acknowledgement_schema_version, acknowledgement_bytes," + + " acknowledgement_digest)" + + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)" + + " ON CONFLICT (operation_id) DO NOTHING", + evidence.operationId(), + evidence.issuerBindingLocalAcknowledgementGeneration(), + evidence.issuerId(), + evidence.requestId(), + evidence.transitionId(), + evidence.bindingRef(), + evidence.bindingGeneration(), + reservation.reservationId(), + reservation.reservationFence(), + reservation.issuerCoverageOperationId(), + reservation.issuerCoverageOperationFence(), + reservation.coverageFence(), + reservation.inventorySnapshotRevision(), + reservation.inventoryRevision(), + anchor.bootstrapOperationId(), + anchor.issuerCoverageOperationId(), + anchor.operationFence(), + anchor.coverageFence(), + anchor.inventorySnapshotRevision(), + anchor.globalCoverageGeneration(), + anchor.controlEpoch(), + memberOperation.operationId(), + memberOperation.operationFence(), + memberOperation.generation(), + reservation.partitionId(), + evidence.physicalReadback().partitionFieldSetDigest(), + evidence.sqlCurrentnessDigest(), + (short) CanonicalGameplayIssuerBindingLocalAcknowledgement.SCHEMA_VERSION, + acknowledgement.exactBytes(), + acknowledgement.digest()); + } + + private static BigInteger allocateAcknowledgementGeneration( + DSLContext transaction, String issuerId) { + transaction.execute( + "INSERT INTO " + + GENERATION_COUNTER + + " (issuer_id, last_issued_binding_local_acknowledgement_generation, counter_version)" + + " VALUES (?, 0, 0) ON CONFLICT (issuer_id) DO NOTHING", + issuerId); + Record counter = + transaction.fetchOne( + "SELECT * FROM " + GENERATION_COUNTER + " WHERE issuer_id = ? FOR UPDATE", issuerId); + if (counter == null) + throw unavailable("Issuer binding-local ACK generation counter is missing"); + + BigInteger previous = + nonnegative(counter, "last_issued_binding_local_acknowledgement_generation"); + Long versionValue = counter.get("counter_version", Long.class); + if (versionValue == null + || versionValue < 0 + || (versionValue == 0 && previous.signum() != 0) + || (versionValue > 0 && previous.signum() == 0)) { + throw unavailable("Issuer binding-local ACK generation counter is malformed"); + } + Record latestReceipt = + transaction.fetchOne( + "SELECT MAX(acknowledgement_generation) AS latest_generation FROM " + + ACKNOWLEDGEMENT + + " WHERE issuer_id = ?", + issuerId); + Object latestValue = latestReceipt == null ? null : latestReceipt.get("latest_generation"); + BigInteger latest = + latestValue == null + ? BigInteger.ZERO + : numberValue(latestValue, "latest acknowledgement generation"); + if (!previous.equals(latest)) { + throw unavailable( + "Issuer binding-local ACK generation counter differs from retained receipts"); + } + + BigInteger next = previous.add(BigInteger.ONE); + if (next.toString().length() > 256) { + throw unavailable("Issuer binding-local ACK generation is outside its bound"); + } + long nextVersion; + try { + nextVersion = Math.addExact(versionValue, 1L); + } catch (ArithmeticException overflow) { + throw unavailable( + "Issuer binding-local ACK generation counter version is exhausted", overflow); + } + Record updated = + transaction.fetchOne( + "UPDATE " + + GENERATION_COUNTER + + " SET last_issued_binding_local_acknowledgement_generation = ?," + + " counter_version = ?, updated_at = CURRENT_TIMESTAMP" + + " WHERE issuer_id = ? AND last_issued_binding_local_acknowledgement_generation = ?" + + " AND counter_version = ? RETURNING issuer_id", + next, + nextVersion, + issuerId, + previous, + versionValue); + if (updated == null) { + throw unavailable("Issuer binding-local ACK generation compare-and-set lost"); + } + return next; + } + + private static BigInteger numberValue(Object value, String field) { + if (!(value instanceof Number number)) throw unavailable(field + " is missing or nonnumeric"); + try { + if (number instanceof BigDecimal decimal) return decimal.toBigIntegerExact(); + return BigInteger.valueOf(number.longValue()); + } catch (ArithmeticException malformed) { + throw unavailable(field + " is not an exact integer", malformed); + } + } + + private static CanonicalGameplayIssuerBindingLocalAcknowledgement readAcknowledgement( + DSLContext query, Record row) { + byte[] exactBytes = bytes(row, "acknowledgement_bytes"); + CanonicalGameplayIssuerBindingLocalAcknowledgement acknowledgement; + try { + acknowledgement = CanonicalGameplayIssuerBindingLocalAcknowledgement.decode(exactBytes); + } catch (RuntimeException malformed) { + throw unavailable("Stored issuer binding-local acknowledgement is malformed", malformed); + } + Evidence evidence = acknowledgement.evidence(); + Record operation = + query.fetchOne( + "SELECT * FROM " + + "game_session_canonical_issuer_binding_local_operation" + + " WHERE operation_id = ?", + evidence.operationId()); + Record installedAnchor = + query.fetchOne( + "SELECT global_coverage_generation, exact_anchor_bytes" + + " FROM game_session_canonical_issuer_installed_anchor WHERE issuer_id = ?", + evidence.issuerId()); + Record generationCounter = + query.fetchOne( + "SELECT last_issued_binding_local_acknowledgement_generation" + + " FROM game_session_canonical_issuer_binding_local_ack_gen_counter" + + " WHERE issuer_id = ?", + evidence.issuerId()); + if (!uuid(row, "operation_id").equals(evidence.operationId()) + || !positive(row, "acknowledgement_generation") + .equals(evidence.issuerBindingLocalAcknowledgementGeneration()) + || !GameSessionAccountDelegationProfile.ISSUER.equals(text(row, "issuer_id")) + || !text(row, "issuer_id").equals(evidence.issuerId()) + || !uuid(row, "request_id").equals(evidence.requestId()) + || !uuid(row, "transition_id").equals(evidence.transitionId()) + || !Arrays.equals(bytes(row, "binding_ref"), evidence.bindingRef()) + || !positive(row, "binding_generation").equals(evidence.bindingGeneration()) + || !uuid(row, "reservation_id").equals(evidence.reservation().reservationId()) + || !uuid(row, "reservation_fence").equals(evidence.reservation().reservationFence()) + || !uuid(row, "original_issuer_coverage_operation_id") + .equals(evidence.reservation().issuerCoverageOperationId()) + || !positive(row, "original_issuer_coverage_operation_fence") + .equals(evidence.reservation().issuerCoverageOperationFence()) + || !positive(row, "original_coverage_fence").equals(evidence.reservation().coverageFence()) + || !positive(row, "original_inventory_snapshot_revision") + .equals(evidence.reservation().inventorySnapshotRevision()) + || !positive(row, "original_inventory_revision") + .equals(evidence.reservation().inventoryRevision()) + || !uuid(row, "anchor_bootstrap_operation_id") + .equals(evidence.anchor().bootstrapOperationId()) + || !uuid(row, "anchor_issuer_coverage_operation_id") + .equals(evidence.anchor().issuerCoverageOperationId()) + || !positive(row, "anchor_operation_fence").equals(evidence.anchor().operationFence()) + || !positive(row, "anchor_coverage_fence").equals(evidence.anchor().coverageFence()) + || !positive(row, "anchor_inventory_snapshot_revision") + .equals(evidence.anchor().inventorySnapshotRevision()) + || !positive(row, "anchor_global_coverage_generation") + .equals(evidence.anchor().globalCoverageGeneration()) + || !positive(row, "issuer_control_epoch").equals(evidence.anchor().controlEpoch()) + || !uuid(row, "local_member_operation_id").equals(evidence.memberOperation().operationId()) + || !positive(row, "local_member_operation_fence") + .equals(evidence.memberOperation().operationFence()) + || !positive(row, "local_member_generation").equals(evidence.memberOperation().generation()) + || !nonnegative(row, "physical_partition_id").equals(evidence.reservation().partitionId()) + || !text(row, "physical_field_set_digest") + .equals(evidence.physicalReadback().partitionFieldSetDigest()) + || !text(row, "sql_currentness_digest").equals(evidence.sqlCurrentnessDigest()) + || !Objects.equals(row.get("acknowledgement_schema_version", Short.class), (short) 1) + || !acknowledgement.digest().equals(text(row, "acknowledgement_digest")) + || installedAnchor == null + || !positive(installedAnchor, "global_coverage_generation") + .equals(evidence.anchor().globalCoverageGeneration()) + || !Arrays.equals( + bytes(installedAnchor, "exact_anchor_bytes"), evidence.anchor().exactBytes()) + || generationCounter == null + || nonnegative(generationCounter, "last_issued_binding_local_acknowledgement_generation") + .compareTo(evidence.issuerBindingLocalAcknowledgementGeneration()) + < 0 + || operation == null + || !"PENDING_PHYSICAL_PROOF".equals(text(operation, "member_status")) + || !Objects.equals(operation.get("member_schema_version", Short.class), (short) 2) + || !text(operation, "issuer_id").equals(evidence.issuerId()) + || !uuid(operation, "request_id").equals(evidence.requestId()) + || !uuid(operation, "transition_id").equals(evidence.transitionId()) + || !uuid(operation, "candidate_account_index_fence") + .equals(evidence.candidateAccountIndexFence()) + || !Arrays.equals(bytes(operation, "binding_ref"), evidence.bindingRef()) + || !positive(operation, "binding_generation").equals(evidence.bindingGeneration()) + || !uuid(operation, "reservation_id").equals(evidence.reservation().reservationId()) + || !uuid(operation, "reservation_fence").equals(evidence.reservation().reservationFence()) + || !positive(operation, "original_issuer_coverage_operation_fence") + .equals(evidence.reservation().issuerCoverageOperationFence()) + || !uuid(operation, "original_issuer_coverage_operation_id") + .equals(evidence.reservation().issuerCoverageOperationId()) + || !positive(operation, "original_coverage_fence") + .equals(evidence.reservation().coverageFence()) + || !positive(operation, "original_inventory_snapshot_revision") + .equals(evidence.reservation().inventorySnapshotRevision()) + || !positive(operation, "local_inventory_snapshot_revision") + .equals(evidence.reservation().inventoryRevision()) + || !uuid(operation, "anchor_bootstrap_operation_id") + .equals(evidence.anchor().bootstrapOperationId()) + || !uuid(operation, "anchor_issuer_coverage_operation_id") + .equals(evidence.anchor().issuerCoverageOperationId()) + || !positive(operation, "anchor_operation_fence").equals(evidence.anchor().operationFence()) + || !positive(operation, "anchor_coverage_fence").equals(evidence.anchor().coverageFence()) + || !positive(operation, "anchor_issuer_inventory_snapshot_revision") + .equals(evidence.anchor().inventorySnapshotRevision()) + || !positive(operation, "anchor_control_epoch").equals(evidence.anchor().controlEpoch()) + || !Arrays.equals(bytes(operation, "exact_anchor_bytes"), evidence.anchor().exactBytes()) + || !text(operation, "exact_anchor_digest").equals(evidence.anchor().exactDigest()) + || !Arrays.equals( + bytes(operation, "anchor_layout_descriptor_bytes"), + evidence.anchor().layoutDescriptorBytes()) + || !text(operation, "anchor_layout_descriptor_digest") + .equals(evidence.anchor().layoutDescriptorDigest()) + || !Arrays.equals( + bytes(operation, "anchor_source_checkpoint_bytes"), + evidence.currentSource().checkpointBytes()) + || !text(operation, "anchor_source_checkpoint_digest") + .equals(evidence.currentSource().checkpointDigest()) + || !Arrays.equals( + operation.get("anchor_source_event_bytes", byte[].class), + evidence.currentSource().eventBytes()) + || !Objects.equals( + operation.get("anchor_source_event_digest", String.class), + evidence.currentSource().eventDigest()) + || !Arrays.equals( + bytes(operation, "anchor_incarnation_bytes"), + evidence.currentSource().incarnationBytes()) + || !text(operation, "anchor_incarnation_digest") + .equals(evidence.currentSource().incarnationDigest()) + || !uuid(operation, "operation_id").equals(evidence.memberOperation().operationId()) + || !positive(operation, "operation_fence") + .equals(evidence.memberOperation().operationFence()) + || !positive(operation, "local_member_generation") + .equals(evidence.memberOperation().generation()) + || !nonnegative(operation, "partition_id").equals(evidence.reservation().partitionId()) + || !Arrays.equals(bytes(operation, "member_value_bytes"), evidence.memberValueBytes()) + || !text(operation, "member_value_digest").equals(evidence.memberValueDigest())) { + throw unavailable( + "Stored issuer acknowledgement columns differ from their exact receipt bytes"); + } + return acknowledgement; + } + + private static ReadbackProof validateReadback( + CanonicalGameplayIssuerBindingLocalOperation operation, + CanonicalGameplayIssuerBindingLocalProjectionRepository.PreparedPartitionWork work, + CanonicalGameplayIssuerBindingLocalRedisOwner.Readback readback, + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState currentState) { + var member = operation.memberValue(); + var anchor = operation.anchor(); + if (!sameCurrentIssuerStateForOperation(operation, currentState)) { + throw unavailable("Current issuer source or incarnation differs from the installed anchor"); + } + if (!work.targetEntry().bindingPresent() + || !work.targetEntry().countsTowardCapacity() + || !"PROVISIONAL".equals(work.targetEntry().transitionStatus())) { + throw unavailable("Issuer local acknowledgement requires the current provisional binding"); + } + Map fieldSet = decodeReadback(readback.exactReadbackBytes()); + String bindingField = new String(member.owner().bindingRef().bytes(), StandardCharsets.UTF_8); + String capacityField = + CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.reservationField( + member.reservation().reservationId()); + byte[] bindingBytes = fieldSet.get(bindingField); + byte[] capacityBytes = fieldSet.get(capacityField); + if (!Arrays.equals(bindingBytes, operation.exactMemberValueBytes()) + || !Arrays.equals(capacityBytes, operation.exactMemberValueBytes())) { + throw unavailable("Physical issuer readback lacks the exact member and reservation fields"); + } + + int reservations = 0; + int bindings = 0; + int countedCapacity = 0; + for (Map.Entry entry : fieldSet.entrySet()) { + if (entry + .getKey() + .startsWith( + CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.RESERVATION_FIELD_PREFIX)) { + var value = CanonicalGameplayIssuerMemberV2Codec.decode(entry.getValue()); + reservations++; + if (value.reservation().lifecycle() + != CanonicalIssuerPartitionReservation.Lifecycle.RELEASED) countedCapacity++; + } else if (!entry + .getKey() + .equals(CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.METADATA_FIELD)) { + CanonicalGameplayIssuerMemberV2Codec.decode(entry.getValue()); + bindings++; + } + } + var proof = work.baselineProof(); + byte[] readbackBytes = readback.exactReadbackBytes(); + var physical = + new PhysicalReadback( + bindingBytes, + CanonicalGameplayIssuerMemberV2Codec.sha256(bindingBytes), + capacityBytes, + CanonicalGameplayIssuerMemberV2Codec.sha256(capacityBytes), + CanonicalGameplayIssuerMemberV2Codec.sha256(readbackBytes), + Math.toIntExact(readback.scriptOutcome()), + fieldSet.size(), + reservations, + bindings, + countedCapacity); + var capacity = + new Capacity( + member.reservation().partitionId(), + anchor.partitionCapacity(), + BigInteger.valueOf(proof.physicalCountedCapacityCount()), + BigInteger.valueOf(proof.physicalReservationCount()), + BigInteger.valueOf(proof.physicalBindingCount()), + work.partitionCapacity(), + work.aggregateCapacity(), + work.aggregateBound()); + return new ReadbackProof(physical, capacity); + } + + private static Evidence buildEvidence( + CanonicalGameplayIssuerBindingLocalOperation operation, + CanonicalGameplayIssuerBindingLocalRedisOwner.Readback readback, + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState currentState, + ReadbackProof proof, + BigInteger acknowledgementGeneration) { + var member = operation.memberValue(); + var anchor = operation.anchor(); + var stateSource = currentState.accountCheckpoint(); + byte[] sourceCheckpointBytes = stateSource.exactCheckpointBytes(); + byte[] sourceEventBytes = stateSource.latestIssuerEventBytes(); + byte[] incarnationBytes = + CanonicalGameplayIssuerInstalledAnchor.encodeIncarnation(currentState.incarnation()); + var originalReservation = member.reservation(); + var anchorTuple = member.anchor(); + return new Evidence( + operation.operationId(), + acknowledgementGeneration, + operation.request().requestId(), + operation.request().transitionId(), + operation.candidateAccountIndexFence(), + member.owner().issuerId(), + member.owner().bindingRef().bytes(), + member.bindingGeneration(), + operation.exactMemberValueBytes(), + operation.memberValueDigest(), + new Reservation( + originalReservation.reservationId(), + originalReservation.transitionId(), + originalReservation.reservationFence(), + originalReservation.partitionId(), + originalReservation.lifecycle().name(), + originalReservation.issuerCoverageOperationId(), + originalReservation.issuerCoverageOperationFence(), + originalReservation.coverageFence(), + originalReservation.inventorySnapshotRevision(), + originalReservation.inventoryRevision()), + new Anchor( + anchor.bootstrapOperationId(), + anchorTuple.issuerCoverageOperationId(), + anchorTuple.operationFence(), + anchorTuple.coverageFence(), + anchorTuple.issuerInventorySnapshotRevision(), + anchor.globalCoverageGeneration(), + anchor.controlEpoch(), + anchor.layoutVersion(), + anchor.partitionCount(), + anchor.partitionCapacity(), + anchor.mappingIdentity(), + anchor.layoutDescriptorBytes(), + anchor.layoutDescriptorDigest(), + anchor.exactAnchorBytes(), + anchor.exactAnchorDigest()), + new MemberOperation( + member.memberOperation().operationId(), + member.memberOperation().operationFence(), + member.memberOperation().coverageGeneration()), + new CurrentSource( + stateSource.issuerAuthGeneration(), + sourceCheckpointBytes, + stateSource.checkpointDigest(), + sourceEventBytes, + stateSource.latestIssuerEventDigest(), + incarnationBytes, + CanonicalGameplayIssuerMemberV2Codec.sha256(incarnationBytes)), + proof.physical(), + proof.capacity(), + sha256Hex(readback.sqlCurrentnessDigest())); + } + + private record ReadbackProof(PhysicalReadback physical, Capacity capacity) {} + + private static Map decodeReadback(byte[] readbackBytes) { + Map fields = + CanonicalGameplayIssuerBootstrapCoverageRepository.decodeFieldSet(readbackBytes); + if (fields.isEmpty() || fields.size() > MAX_FIELD_COUNT) { + throw unavailable("Physical issuer readback field count is outside its bound"); + } + return fields; + } + + private static void requireEligibleCandidate( + CanonicalGameplayIssuerBindingLocalProjectionRepository.PreparedPartitionWork work) { + if (!work.targetEntry().bindingPresent() + || !work.targetEntry().countsTowardCapacity() + || !"PROVISIONAL".equals(work.targetEntry().transitionStatus())) { + throw unavailable("Only the original nonterminal binding may receive a local issuer ACK"); + } + } + + private static void requireSameOperation( + Evidence evidence, CanonicalGameplayIssuerBindingLocalOperation operation) { + if (!evidence.operationId().equals(operation.operationId()) + || !evidence.requestId().equals(operation.request().requestId()) + || !evidence.transitionId().equals(operation.request().transitionId()) + || !evidence.reservation().reservationId().equals(operation.reservation().reservationId()) + || !evidence.anchor().exactDigest().equals(operation.anchor().exactAnchorDigest()) + || !Arrays.equals(evidence.memberValueBytes(), operation.exactMemberValueBytes())) { + throw unavailable( + "Retained issuer acknowledgement differs from the exact original operation"); + } + } + + private static void requireSameCurrentSources( + Evidence evidence, + CanonicalGameplayIssuerBindingLocalOperation operation, + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState currentState) { + if (!sameCurrentIssuerStateForOperation(operation, currentState) + || !evidence.anchor().exactDigest().equals(operation.anchor().exactAnchorDigest()) + || !evidence + .currentSource() + .checkpointDigest() + .equals(currentState.accountCheckpoint().checkpointDigest()) + || !Arrays.equals( + evidence.currentSource().checkpointBytes(), + currentState.accountCheckpoint().exactCheckpointBytes()) + || !Objects.equals( + evidence.currentSource().eventDigest(), + currentState.accountCheckpoint().latestIssuerEventDigest()) + || !Arrays.equals( + evidence.currentSource().eventBytes(), + currentState.accountCheckpoint().latestIssuerEventBytes()) + || !Arrays.equals( + evidence.currentSource().incarnationBytes(), + CanonicalGameplayIssuerInstalledAnchor.encodeIncarnation(currentState.incarnation()))) { + throw unavailable( + "Retained issuer acknowledgement is stale for current source or incarnation"); + } + } + + private static void requireReadbackTargetStillMatches( + Evidence evidence, CanonicalGameplayIssuerBindingLocalRedisOwner.Readback readback) { + if (!readback.operationId().equals(evidence.operationId())) { + throw unavailable("Physical issuer readback belongs to a different local operation"); + } + Map fields = decodeReadback(readback.exactReadbackBytes()); + var prior = evidence.physicalReadback(); + var member = CanonicalGameplayIssuerMemberV2Codec.decode(evidence.memberValueBytes()); + byte[] binding = + fields.get(new String(member.owner().bindingRef().bytes(), StandardCharsets.UTF_8)); + byte[] capacity = + fields.get( + CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.reservationField( + evidence.reservation().reservationId())); + if (!Arrays.equals(binding, prior.bindingValueBytes()) + || !Arrays.equals(capacity, prior.capacityValueBytes())) { + throw unavailable("Physical issuer retry differs from the retained target readback"); + } + } + + private void requireCurrentIssuerSource( + CanonicalGameplayIssuerBindingLocalOperation operation, + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState state) { + if (!sameCurrentIssuerStateForOperation(operation, state)) { + throw unavailable( + "Current Account source or issuer incarnation differs from the installed anchor"); + } + } + + private static boolean sameCurrentIssuerStateForOperation( + CanonicalGameplayIssuerBindingLocalOperation operation, + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState state) { + var anchor = operation.anchor(); + var source = state.accountCheckpoint(); + return source.issuerId().equals(anchor.issuerId()) + && source.issuerAuthGeneration().equals(anchor.issuerAuthGeneration()) + && source.checkpointDigest().equals(anchor.sourceCheckpointDigest()) + && Arrays.equals(source.exactCheckpointBytes(), anchor.sourceCheckpointBytes()) + && Objects.equals(source.latestIssuerEventDigest(), anchor.sourceEventDigest()) + && Arrays.equals(source.latestIssuerEventBytes(), anchor.sourceEventBytes()) + && Arrays.equals( + CanonicalGameplayIssuerInstalledAnchor.encodeIncarnation(state.incarnation()), + anchor.incarnationBytes()); + } + + private boolean sameCurrentIssuerState( + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState left, + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState right) { + return left.accountCheckpoint().issuerId().equals(right.accountCheckpoint().issuerId()) + && left.accountCheckpoint() + .issuerAuthGeneration() + .equals(right.accountCheckpoint().issuerAuthGeneration()) + && Arrays.equals( + left.accountCheckpoint().exactCheckpointBytes(), + right.accountCheckpoint().exactCheckpointBytes()) + && left.accountCheckpoint() + .checkpointDigest() + .equals(right.accountCheckpoint().checkpointDigest()) + && Arrays.equals( + left.accountCheckpoint().latestIssuerEventBytes(), + right.accountCheckpoint().latestIssuerEventBytes()) + && Objects.equals( + left.accountCheckpoint().latestIssuerEventDigest(), + right.accountCheckpoint().latestIssuerEventDigest()) + && Arrays.equals( + CanonicalGameplayIssuerInstalledAnchor.encodeIncarnation(left.incarnation()), + CanonicalGameplayIssuerInstalledAnchor.encodeIncarnation(right.incarnation())); + } + + private CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState + readCurrentIssuerState(String boundary) { + try { + requireNoAmbientTransaction(); + var state = currentIssuerStateSource.readFreshCurrentState(); + requireNoAmbientTransaction(); + if (state == null) throw unavailable("Current issuer source returned no state " + boundary); + return state; + } catch (RuntimeException failure) { + if (failure instanceof IllegalStateException state + && state.getMessage() != null + && state.getMessage().contains("Issuer binding-local acknowledgement is unavailable")) { + throw state; + } + throw unavailable("Could not read current issuer source " + boundary, failure); + } + } + + private static BigInteger positive(Record row, String field) { + BigInteger value = number(row, field); + if (value.signum() <= 0) throw unavailable(field + " must be positive"); + return value; + } + + private static BigInteger nonnegative(Record row, String field) { + BigInteger value = number(row, field); + if (value.signum() < 0) throw unavailable(field + " must not be negative"); + return value; + } + + private static BigInteger number(Record row, String field) { + Object value = row.get(field); + if (!(value instanceof Number number)) throw unavailable(field + " is missing or nonnumeric"); + try { + if (number instanceof BigDecimal decimal) return decimal.toBigIntegerExact(); + return BigInteger.valueOf(number.longValue()); + } catch (ArithmeticException malformed) { + throw unavailable(field + " is not an exact integer", malformed); + } + } + + private static UUID uuid(Record row, String field) { + UUID value = row.get(field, UUID.class); + if (value == null || value.equals(new UUID(0L, 0L))) throw unavailable(field + " is missing"); + return value; + } + + private static String text(Record row, String field) { + String value = row.get(field, String.class); + if (value == null || value.isEmpty()) throw unavailable(field + " is missing"); + return value; + } + + private static byte[] bytes(Record row, String field) { + byte[] value = row.get(field, byte[].class); + if (value == null || value.length == 0) throw unavailable(field + " is missing"); + return value.clone(); + } + + private static String sha256Hex(byte[] digestBytes) { + if (digestBytes.length != 32) throw unavailable("SQL currentness digest is not SHA-256"); + return "sha256:" + java.util.HexFormat.of().formatHex(digestBytes); + } + + private static void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw unavailable("Issuer acknowledgement owner cannot join an ambient SQL transaction"); + } + } + + private static IllegalStateException unavailable(String message) { + return new IllegalStateException( + "Issuer binding-local acknowledgement is unavailable: " + message); + } + + private static IllegalStateException unavailable(String message, Throwable cause) { + return new IllegalStateException( + "Issuer binding-local acknowledgement is unavailable: " + message, cause); + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalProjectionRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalProjectionRepository.java index bb3963e250..b6a966b6e8 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalProjectionRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalProjectionRepository.java @@ -80,6 +80,25 @@ PreparedPartitionWork readPreparedPartitionWork( return work; } + /** + * Rebuilds the exact SQL proof inside a caller-owned transaction that already holds the + * inventory-clock lock. The caller must obtain a fresh issuer source before entering SQL and + * re-read it after commit; this method performs no remote work and never holds SQL over Redis. + */ + PreparedPartitionWork readPreparedPartitionWorkInTransaction( + DSLContext transaction, + CanonicalGameplayIssuerBindingLocalOperation target, + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState currentState) { + Objects.requireNonNull(transaction, "transaction"); + Objects.requireNonNull(target, "target"); + requireCurrentSourceMatches(target.anchor(), currentState); + CanonicalGameplayIssuerInstalledAnchor anchor = + CanonicalGameplayIssuerBootstrapCoverageRepository + .readInstalledAnchorForBindingPreparationInTransaction(transaction, currentState); + requireSameAnchor(target.anchor(), anchor); + return prepareInTransaction(transaction, target, anchor); + } + /** Re-reads the durable set and all currentness inputs after the Redis round trip. */ void requireStillCurrent(PreparedPartitionWork expected) { Objects.requireNonNull(expected, "expected"); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwner.java index 6aeec1e0d5..e37bf75b2b 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwner.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwner.java @@ -124,7 +124,7 @@ public Readback projectAndRead(CanonicalGameplayIssuerBindingLocalOperation oper byte[] readbackBytes = readExactPhysicalState(key, work); requireFreshCurrentState(work); projectionRepository.requireStillCurrent(work); - return new Readback(operation, result, readbackBytes); + return new Readback(operation, result, readbackBytes, work.sqlCurrentnessDigest()); } catch (RuntimeException failure) { if (failure instanceof IllegalStateException state && state.getMessage() != null @@ -508,15 +508,22 @@ public static final class Readback { private final CanonicalGameplayIssuerBindingLocalOperation operation; private final long scriptOutcome; private final byte[] exactReadbackBytes; + private final byte[] sqlCurrentnessDigest; private Readback( CanonicalGameplayIssuerBindingLocalOperation operation, long scriptOutcome, - byte[] exactReadbackBytes) { + byte[] exactReadbackBytes, + byte[] sqlCurrentnessDigest) { this.operation = Objects.requireNonNull(operation, "operation"); this.scriptOutcome = scriptOutcome; this.exactReadbackBytes = Objects.requireNonNull(exactReadbackBytes, "exactReadbackBytes").clone(); + this.sqlCurrentnessDigest = + Objects.requireNonNull(sqlCurrentnessDigest, "sqlCurrentnessDigest").clone(); + if (this.sqlCurrentnessDigest.length != 32) { + throw new IllegalArgumentException("SQL issuer currentness digest must be SHA-256"); + } } public CanonicalGameplayIssuerBindingLocalOperation operation() { @@ -534,5 +541,9 @@ public long scriptOutcome() { public byte[] exactReadbackBytes() { return exactReadbackBytes.clone(); } + + byte[] sqlCurrentnessDigest() { + return sqlCurrentnessDigest.clone(); + } } } diff --git a/services/game-session-service/src/main/resources/db/migration/V1039__canonical_issuer_binding_local_acknowledgement.sql b/services/game-session-service/src/main/resources/db/migration/V1039__canonical_issuer_binding_local_acknowledgement.sql new file mode 100644 index 0000000000..b2bf5e58ee --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V1039__canonical_issuer_binding_local_acknowledgement.sql @@ -0,0 +1,244 @@ +-- This receipt is separate from the immutable SQL preparation and physical schema-v2 member. +-- It acknowledges one original binding-local member/reservation readback only; it does not +-- publish issuer-wide coverage, initialize a tenant barrier, or authorize admission. +CREATE TABLE game_session_canonical_issuer_binding_local_ack_gen_counter ( + issuer_id character varying(64) NOT NULL, + last_issued_binding_local_acknowledgement_generation numeric NOT NULL, + counter_version bigint NOT NULL, + updated_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT pk_gs_issuer_binding_local_ack_generation_counter PRIMARY KEY (issuer_id), + CONSTRAINT chk_gs_issuer_binding_local_ack_generation_counter CHECK ( + issuer_id COLLATE "C" = 'firemud-account-service'::character varying COLLATE "C" + AND last_issued_binding_local_acknowledgement_generation >= 0 + AND last_issued_binding_local_acknowledgement_generation = floor(last_issued_binding_local_acknowledgement_generation) + AND length(CAST(last_issued_binding_local_acknowledgement_generation AS varchar)) <= 256 + AND counter_version >= 0 + AND ((counter_version = 0 AND last_issued_binding_local_acknowledgement_generation = 0) + OR (counter_version > 0 AND last_issued_binding_local_acknowledgement_generation > 0))) +); + +CREATE TABLE game_session_canonical_issuer_binding_local_acknowledgement ( + operation_id uuid NOT NULL, + acknowledgement_generation numeric NOT NULL, + issuer_id character varying(64) NOT NULL, + request_id uuid NOT NULL, + transition_id uuid NOT NULL, + binding_ref bytea NOT NULL, + binding_generation numeric NOT NULL, + reservation_id uuid NOT NULL, + reservation_fence uuid NOT NULL, + original_issuer_coverage_operation_id uuid NOT NULL, + original_issuer_coverage_operation_fence numeric NOT NULL, + original_coverage_fence numeric NOT NULL, + original_inventory_snapshot_revision numeric NOT NULL, + original_inventory_revision numeric NOT NULL, + anchor_bootstrap_operation_id uuid NOT NULL, + anchor_issuer_coverage_operation_id uuid NOT NULL, + anchor_operation_fence numeric NOT NULL, + anchor_coverage_fence numeric NOT NULL, + anchor_inventory_snapshot_revision numeric NOT NULL, + anchor_global_coverage_generation numeric NOT NULL, + issuer_control_epoch numeric NOT NULL, + local_member_operation_id uuid NOT NULL, + local_member_operation_fence numeric NOT NULL, + local_member_generation numeric NOT NULL, + physical_partition_id numeric NOT NULL, + physical_field_set_digest character varying(71) NOT NULL, + sql_currentness_digest character varying(71) NOT NULL, + acknowledgement_schema_version smallint NOT NULL, + acknowledgement_bytes bytea NOT NULL, + acknowledgement_digest character varying(71) NOT NULL, + created_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT pk_gs_issuer_binding_local_ack PRIMARY KEY (operation_id), + CONSTRAINT uq_gs_issuer_binding_local_ack_generation UNIQUE (issuer_id, acknowledgement_generation), + CONSTRAINT fk_gs_issuer_binding_local_ack_operation + FOREIGN KEY (operation_id) + REFERENCES game_session_canonical_issuer_binding_local_operation (operation_id), + CONSTRAINT uq_gs_issuer_binding_local_ack_transition UNIQUE (issuer_id, transition_id), + CONSTRAINT uq_gs_issuer_binding_local_ack_reservation UNIQUE (reservation_id), + CONSTRAINT chk_gs_issuer_binding_local_ack CHECK ( + issuer_id COLLATE "C" = 'firemud-account-service'::character varying COLLATE "C" + AND operation_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND acknowledgement_generation > 0 + AND acknowledgement_generation = floor(acknowledgement_generation) + AND length(CAST(acknowledgement_generation AS varchar)) <= 256 + AND request_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND transition_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND request_id <> transition_id + AND octet_length(binding_ref) > 0 + AND binding_generation > 0 + AND reservation_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND reservation_fence <> '00000000-0000-0000-0000-000000000000'::uuid + AND original_issuer_coverage_operation_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND original_issuer_coverage_operation_fence > 0 + AND original_coverage_fence > 0 + AND original_inventory_snapshot_revision > 0 + AND original_inventory_revision > 0 + AND anchor_bootstrap_operation_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND anchor_issuer_coverage_operation_id = anchor_bootstrap_operation_id + AND anchor_operation_fence > 0 + AND anchor_coverage_fence > 0 + AND anchor_operation_fence <> anchor_coverage_fence + AND anchor_inventory_snapshot_revision > 0 + AND anchor_global_coverage_generation > 0 + AND issuer_control_epoch = anchor_operation_fence + AND local_member_operation_id = operation_id + AND local_member_operation_fence > 0 + AND local_member_generation > 0 + AND physical_partition_id >= 0 + AND physical_partition_id = floor(physical_partition_id) + AND physical_field_set_digest ~ '^sha256:[0-9a-f]{64}$' + AND sql_currentness_digest ~ '^sha256:[0-9a-f]{64}$' + AND acknowledgement_schema_version = 1 + AND octet_length(acknowledgement_bytes) BETWEEN 1 AND 1048576 + AND acknowledgement_digest ~ '^sha256:[0-9a-f]{64}$') +); + +-- [jooq ignore start] +CREATE FUNCTION game_session_validate_issuer_binding_local_acknowledgement() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +DECLARE + source_operation game_session_canonical_issuer_binding_local_operation%ROWTYPE; + installed_anchor game_session_canonical_issuer_installed_anchor%ROWTYPE; + generation_counter game_session_canonical_issuer_binding_local_ack_gen_counter%ROWTYPE; +BEGIN + SELECT * INTO source_operation + FROM game_session_canonical_issuer_binding_local_operation + WHERE operation_id = NEW.operation_id + FOR KEY SHARE; + IF NOT FOUND + OR source_operation.issuer_id <> NEW.issuer_id + OR source_operation.request_id <> NEW.request_id + OR source_operation.transition_id <> NEW.transition_id + OR source_operation.binding_ref <> NEW.binding_ref + OR source_operation.binding_generation <> NEW.binding_generation + OR source_operation.reservation_id <> NEW.reservation_id + OR source_operation.reservation_fence <> NEW.reservation_fence + OR source_operation.original_issuer_coverage_operation_id <> NEW.original_issuer_coverage_operation_id + OR source_operation.original_issuer_coverage_operation_fence <> NEW.original_issuer_coverage_operation_fence + OR source_operation.original_coverage_fence <> NEW.original_coverage_fence + OR source_operation.original_inventory_snapshot_revision <> NEW.original_inventory_snapshot_revision + OR source_operation.local_inventory_snapshot_revision <> NEW.original_inventory_revision + OR source_operation.anchor_bootstrap_operation_id <> NEW.anchor_bootstrap_operation_id + OR source_operation.anchor_issuer_coverage_operation_id <> NEW.anchor_issuer_coverage_operation_id + OR source_operation.anchor_operation_fence <> NEW.anchor_operation_fence + OR source_operation.anchor_coverage_fence <> NEW.anchor_coverage_fence + OR source_operation.anchor_issuer_inventory_snapshot_revision <> NEW.anchor_inventory_snapshot_revision + OR source_operation.anchor_control_epoch <> NEW.issuer_control_epoch + OR source_operation.operation_id <> NEW.local_member_operation_id + OR source_operation.operation_fence <> NEW.local_member_operation_fence + OR source_operation.local_member_generation <> NEW.local_member_generation + OR source_operation.partition_id <> NEW.physical_partition_id + OR source_operation.member_status <> 'PENDING_PHYSICAL_PROOF' + OR source_operation.member_schema_version <> 2 THEN + RAISE EXCEPTION 'issuer binding-local acknowledgement differs from its immutable original operation' + USING ERRCODE = 'check_violation'; + END IF; + + SELECT * INTO installed_anchor + FROM game_session_canonical_issuer_installed_anchor + WHERE issuer_id = NEW.issuer_id + FOR KEY SHARE; + IF NOT FOUND + OR installed_anchor.bootstrap_operation_id <> NEW.anchor_bootstrap_operation_id + OR installed_anchor.global_coverage_generation <> NEW.anchor_global_coverage_generation + OR installed_anchor.exact_anchor_bytes <> source_operation.exact_anchor_bytes THEN + RAISE EXCEPTION 'issuer binding-local acknowledgement differs from the immutable installed anchor' + USING ERRCODE = 'check_violation'; + END IF; + + SELECT * INTO generation_counter + FROM game_session_canonical_issuer_binding_local_ack_gen_counter + WHERE issuer_id = NEW.issuer_id + FOR KEY SHARE; + IF NOT FOUND + OR generation_counter.last_issued_binding_local_acknowledgement_generation <> NEW.acknowledgement_generation THEN + RAISE EXCEPTION 'issuer binding-local acknowledgement generation was not issued by its owner counter' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER trg_gs_issuer_binding_local_ack_validate + BEFORE INSERT ON game_session_canonical_issuer_binding_local_acknowledgement + FOR EACH ROW EXECUTE FUNCTION game_session_validate_issuer_binding_local_acknowledgement(); + +CREATE FUNCTION game_session_reject_issuer_binding_local_acknowledgement_change() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'issuer binding-local acknowledgements are immutable' + USING ERRCODE = 'check_violation'; +END; +$$; + +CREATE TRIGGER trg_gs_issuer_binding_local_ack_immutable + BEFORE UPDATE OR DELETE ON game_session_canonical_issuer_binding_local_acknowledgement + FOR EACH ROW EXECUTE FUNCTION game_session_reject_issuer_binding_local_acknowledgement_change(); +CREATE TRIGGER trg_gs_issuer_binding_local_ack_no_truncate + BEFORE TRUNCATE ON game_session_canonical_issuer_binding_local_acknowledgement + FOR EACH STATEMENT EXECUTE FUNCTION game_session_reject_issuer_binding_local_acknowledgement_change(); + +CREATE FUNCTION game_session_reject_issuer_local_ack_gen_counter_change() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'issuer binding-local acknowledgement generation counter cannot be truncated' + USING ERRCODE = 'check_violation'; +END; +$$; + +CREATE FUNCTION game_session_guard_issuer_local_ack_gen_counter() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'issuer binding-local acknowledgement generation counter cannot be deleted' + USING ERRCODE = 'check_violation'; + END IF; + IF NEW.issuer_id IS DISTINCT FROM OLD.issuer_id + OR NEW.counter_version <> OLD.counter_version + 1 + OR NEW.last_issued_binding_local_acknowledgement_generation + <> OLD.last_issued_binding_local_acknowledgement_generation + 1 THEN + RAISE EXCEPTION 'issuer binding-local acknowledgement generation counter must advance its own domain by one' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION game_session_guard_issuer_local_ack_gen_counter_insert() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + IF NEW.counter_version <> 0 + OR NEW.last_issued_binding_local_acknowledgement_generation <> 0 THEN + RAISE EXCEPTION 'issuer binding-local acknowledgement generation counter must start unissued' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER trg_gs_issuer_binding_local_ack_generation_counter_initial + BEFORE INSERT ON game_session_canonical_issuer_binding_local_ack_gen_counter + FOR EACH ROW EXECUTE FUNCTION game_session_guard_issuer_local_ack_gen_counter_insert(); +CREATE TRIGGER trg_gs_issuer_binding_local_ack_generation_counter_guard + BEFORE UPDATE OR DELETE ON game_session_canonical_issuer_binding_local_ack_gen_counter + FOR EACH ROW EXECUTE FUNCTION game_session_guard_issuer_local_ack_gen_counter(); +CREATE TRIGGER trg_gs_issuer_binding_local_ack_generation_counter_no_truncate + BEFORE TRUNCATE ON game_session_canonical_issuer_binding_local_ack_gen_counter + FOR EACH STATEMENT EXECUTE FUNCTION game_session_reject_issuer_local_ack_gen_counter_change(); +-- [jooq ignore stop] + +COMMENT ON TABLE game_session_canonical_issuer_binding_local_acknowledgement IS + 'Immutable versioned exact local issuer binding/reservation readback receipt; not issuer-wide coverage or admission.'; +COMMENT ON TABLE game_session_canonical_issuer_binding_local_ack_gen_counter IS + 'Independent owner-issued per-transition issuer binding-local acknowledgement generation; distinct from local member-operation and global issuer coverage generations.'; diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionAbortCompositionFixture.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionAbortCompositionFixture.java index 7706bdac2e..5479aa1069 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionAbortCompositionFixture.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionAbortCompositionFixture.java @@ -81,6 +81,7 @@ public final class CanonicalGameplayAdmissionAbortCompositionFixture implements initialIssuerState; private final CanonicalGameplayIssuerBindingLocalOperation localOperation; private final CanonicalGameplayIssuerBindingLocalProjectionRepository localProjectionRepository; + private byte[] issuerAcknowledgementBytes; private final RedisClient issuerRedisClient; private final RedisScriptCatalog issuerCatalog; private final Map otherOperations = @@ -406,9 +407,14 @@ public void publish(AccountGameplayAdmissionLeaseEvidence lease) { repository.readProvisionalCasEvidence(transitionId), new CanonicalGameplayAdmissionDecision( transitionId, lease, identity, generation, null, target)); - new CanonicalGameplayIssuerBindingLocalRedisOwner( - issuerRedisClient, issuerCatalog, localProjectionRepository, issuerSource) - .projectAndRead(localOperation); + var physicalReadback = + new CanonicalGameplayIssuerBindingLocalRedisOwner( + issuerRedisClient, issuerCatalog, localProjectionRepository, issuerSource) + .projectAndRead(localOperation); + issuerAcknowledgementBytes = + new CanonicalGameplayIssuerBindingLocalAcknowledgementRepository(dsl, issuerSource) + .acknowledge(physicalReadback) + .exactBytes(); } /** @@ -528,8 +534,20 @@ public void projectIssuerReleaseAndLoseReply( public CanonicalGameplayIssuerBindingLocalReleaseOperation completeIssuerRelease( CanonicalGameplayIssuerBindingLocalReleaseOperation operation, CanonicalGameplayIssuerBindingLocalReleaseRedisOwner.Readback readback) { - return new CanonicalGameplayIssuerBindingLocalReleaseOperationRepository(dsl, issuerSource) - .completeWithReadback(operation, readback); + var completed = + new CanonicalGameplayIssuerBindingLocalReleaseOperationRepository(dsl, issuerSource) + .completeWithReadback(operation, readback); + var historicalAcknowledgement = + new CanonicalGameplayIssuerBindingLocalAcknowledgementRepository(dsl, issuerSource) + .readHistorical(localOperation.operationId()); + if (issuerAcknowledgementBytes == null + || historicalAcknowledgement == null + || !java.util.Arrays.equals( + issuerAcknowledgementBytes, historicalAcknowledgement.exactBytes())) { + throw new IllegalStateException( + "Issuer release did not retain the exact original binding-local acknowledgement"); + } + return completed; } public UUID prepareOtherControllerNew(String seed) { diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java index 14b24ee0b5..860b78d0c8 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java @@ -297,6 +297,13 @@ void registersOrdinaryNewAgainstInstalledAnchorAndReusesExactPendingOperation() var firstCapacityOnly = projectionOwner.projectAndRead(first); assertThat(firstCapacityOnly.operation()).isSameAs(first); assertThat(firstCapacityOnly.scriptOutcome()).isEqualTo(1L); + var acknowledgementRepository = + new CanonicalGameplayIssuerBindingLocalAcknowledgementRepository(dsl, currentState::get); + assertThatThrownBy(() -> acknowledgementRepository.acknowledge(firstCapacityOnly)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("nonterminal binding"); + assertThat(count(dsl, "game_session_canonical_issuer_binding_local_acknowledgement")).isZero(); + assertThat(count(dsl, "game_session_canonical_issuer_binding_local_ack_gen_counter")).isZero(); var firstCapacityFields = CanonicalGameplayIssuerBootstrapCoverageRepository.decodeFieldSet( firstCapacityOnly.exactReadbackBytes()); @@ -453,6 +460,115 @@ void registersOrdinaryNewAgainstInstalledAnchorAndReusesExactPendingOperation() .containsEntry(firstCapacityField, first.exactMemberValueBytes()); assertThat(projectionOwner.projectAndRead(first).scriptOutcome()).isEqualTo(3L); + var issuerAcknowledgement = acknowledgementRepository.acknowledge(firstWithBinding); + assertThat(issuerAcknowledgement.evidence().operationId()).isEqualTo(first.operationId()); + assertThat(issuerAcknowledgement.evidence().issuerBindingLocalAcknowledgementGeneration()) + .isEqualTo(BigInteger.ONE); + assertThat(issuerAcknowledgement.evidence().anchor().globalCoverageGeneration()) + .isEqualTo(initialGlobalCoverageGeneration); + assertThat(issuerAcknowledgement.evidence().reservation().reservationId()) + .isEqualTo(first.reservation().reservationId()); + assertThat(issuerAcknowledgement.evidence().reservation().issuerCoverageOperationFence()) + .isEqualTo(first.reservation().issuerCoverageOperationFence()); + assertThat(issuerAcknowledgement.evidence().anchor().operationFence()) + .isEqualTo(first.anchor().operationFence()); + assertThat(issuerAcknowledgement.evidence().memberOperation().generation()) + .isEqualTo(first.localMemberGeneration()); + assertThat(issuerAcknowledgement.evidence().physicalReadback().bindingValueBytes()) + .containsExactly(first.exactMemberValueBytes()); + assertThat(issuerAcknowledgement.evidence().physicalReadback().capacityValueBytes()) + .containsExactly(first.exactMemberValueBytes()); + assertThat(issuerAcknowledgement.evidence().physicalReadback().countedCapacity()).isEqualTo(2); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT member_status FROM" + + " game_session_canonical_issuer_binding_local_operation WHERE operation_id = ?", + first.operationId()), + "Expected immutable local issuer operation") + .get("member_status", String.class)) + .isEqualTo("PENDING_PHYSICAL_PROOF"); + assertThat(count(dsl, "game_session_canonical_issuer_binding_local_acknowledgement")) + .isEqualTo(1L); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT last_issued_binding_local_acknowledgement_generation FROM" + + " game_session_canonical_issuer_binding_local_ack_gen_counter" + + " WHERE issuer_id = ?", + ISSUER), + "Expected owner-issued local ACK generation counter") + .get("last_issued_binding_local_acknowledgement_generation", BigDecimal.class)) + .isEqualTo(BigDecimal.ONE); + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE game_session_canonical_issuer_binding_local_ack_gen_counter" + + " SET last_issued_binding_local_acknowledgement_generation = 3," + + " counter_version = counter_version + 1 WHERE issuer_id = ?", + ISSUER)) + .hasMessageContaining("must advance its own domain by one"); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT last_issued_binding_local_acknowledgement_generation FROM" + + " game_session_canonical_issuer_binding_local_ack_gen_counter" + + " WHERE issuer_id = ?", + ISSUER), + "Expected counter to refuse a skipped generation") + .get("last_issued_binding_local_acknowledgement_generation", BigDecimal.class)) + .isEqualTo(BigDecimal.ONE); + var restartedAcknowledgementRepository = + new CanonicalGameplayIssuerBindingLocalAcknowledgementRepository(dsl, currentState::get); + var retriedAcknowledgement = + restartedAcknowledgementRepository.acknowledge( + projectionOwner(dsl, currentState::get).projectAndRead(first)); + assertThat(retriedAcknowledgement.exactBytes()) + .containsExactly(issuerAcknowledgement.exactBytes()); + assertThat(retriedAcknowledgement.digest()).isEqualTo(issuerAcknowledgement.digest()); + assertThat(retriedAcknowledgement.evidence().issuerBindingLocalAcknowledgementGeneration()) + .isEqualTo(issuerAcknowledgement.evidence().issuerBindingLocalAcknowledgementGeneration()); + assertThat(restartedAcknowledgementRepository.readHistorical(first.operationId()).exactBytes()) + .containsExactly(issuerAcknowledgement.exactBytes()); + assertThat(count(dsl, "game_session_canonical_issuer_binding_local_acknowledgement")) + .isEqualTo(1L); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT last_issued_binding_local_acknowledgement_generation FROM" + + " game_session_canonical_issuer_binding_local_ack_gen_counter" + + " WHERE issuer_id = ?", + ISSUER), + "Expected replay to retain the owner-issued ACK generation") + .get("last_issued_binding_local_acknowledgement_generation", BigDecimal.class)) + .isEqualTo(BigDecimal.ONE); + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE game_session_canonical_issuer_binding_local_acknowledgement" + + " SET acknowledgement_bytes = ? WHERE operation_id = ?", + issuerAcknowledgement.exactBytes(), + first.operationId())) + .hasMessageContaining("issuer binding-local acknowledgements are immutable"); + assertThatThrownBy( + () -> + dsl.execute( + "DELETE FROM game_session_canonical_issuer_binding_local_acknowledgement" + + " WHERE operation_id = ?", + first.operationId())) + .hasMessageContaining("issuer binding-local acknowledgements are immutable"); + assertThat(count(dsl, "game_session_canonical_issuer_binding_local_acknowledgement")) + .isEqualTo(1L); + currentState.set( + new CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState( + checkpointShape(BigInteger.valueOf(8)), incarnation)); + assertThatThrownBy(() -> restartedAcknowledgementRepository.acknowledge(firstWithBinding)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("differs from the installed anchor"); + assertThat(restartedAcknowledgementRepository.readHistorical(first.operationId()).exactBytes()) + .containsExactly(issuerAcknowledgement.exactBytes()); + currentState.set(initialState); + String beforeCapacityRefusal = localRegistrationImage(dsl); assertThatThrownBy( () -> diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalAcknowledgementCodecTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalAcknowledgementCodecTest.java new file mode 100644 index 0000000000..24a7c6f688 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalAcknowledgementCodecTest.java @@ -0,0 +1,231 @@ +package net.firedevops.firemud.gamesession.repository; + +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.UUID; +import net.firedevops.firemud.gamesession.binding.CanonicalIssuerPartitionReservation; +import org.junit.jupiter.api.Test; + +class CanonicalGameplayIssuerBindingLocalAcknowledgementCodecTest { + private static final ObjectMapper JSON = new ObjectMapper(); + private static final BigInteger LARGE = new BigInteger("9007199254740997"); + + @Test + void roundTripsDistinctOriginalReservationAnchorAndLocalOperationEvidence() throws Exception { + var evidence = fixture(); + byte[] encoded = CanonicalGameplayIssuerBindingLocalAcknowledgementCodec.encode(evidence); + + var decoded = CanonicalGameplayIssuerBindingLocalAcknowledgementCodec.decode(encoded); + ObjectNode root = (ObjectNode) JSON.readTree(encoded); + + assertThat(CanonicalGameplayIssuerBindingLocalAcknowledgementCodec.encode(decoded)) + .containsExactly(encoded); + assertThat(root.path("schemaVersion").intValue()).isEqualTo(1); + assertThat(root.path("scope").textValue()).isEqualTo("ISSUER_BINDING_LOCAL"); + assertThat(root.path("issuerBindingLocalAcknowledgementGeneration").textValue()) + .isEqualTo("83"); + assertThat(root.path("globalIssuerCoverageGeneration").textValue()).isEqualTo("NOT_YET_ISSUED"); + assertThat(root.path("anchor").path("globalCoverageGeneration").textValue()).isEqualTo("5"); + assertThat(root.path("reservation").path("issuerCoverageOperationId").textValue()) + .isNotEqualTo(root.path("anchor").path("issuerCoverageOperationId").textValue()); + assertThat(root.path("reservation").path("coverageFence").textValue()) + .isNotEqualTo(root.path("anchor").path("coverageFence").textValue()); + assertThat(root.path("memberOperation").path("generation").textValue()) + .isNotEqualTo(root.path("globalIssuerCoverageGeneration").textValue()); + } + + @Test + void rejectsUnknownFieldsAndAnAccountOrGlobalCoverageAlias() throws Exception { + byte[] encoded = CanonicalGameplayIssuerBindingLocalAcknowledgementCodec.encode(fixture()); + ObjectNode original = (ObjectNode) JSON.readTree(encoded); + ObjectNode unknown = original.deepCopy(); + unknown.put("accountIndexAcknowledgementSchemaVersion", 2); + ObjectNode globalCoverage = original.deepCopy(); + globalCoverage.put("globalIssuerCoverageGeneration", "17"); + ObjectNode unissuedAcknowledgement = original.deepCopy(); + unissuedAcknowledgement.put("issuerBindingLocalAcknowledgementGeneration", "NOT_YET_ISSUED"); + + assertThatThrownBy( + () -> + CanonicalGameplayIssuerBindingLocalAcknowledgementCodec.decode( + JSON.writeValueAsBytes(unknown))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("missing or unknown fields"); + assertThatThrownBy( + () -> + CanonicalGameplayIssuerBindingLocalAcknowledgementCodec.decode( + JSON.writeValueAsBytes(globalCoverage))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("version or scope"); + assertThatThrownBy( + () -> + CanonicalGameplayIssuerBindingLocalAcknowledgementCodec.decode( + JSON.writeValueAsBytes(unissuedAcknowledgement))) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void rejectsDifferentOriginalReservationProvenanceUnderTheSameBinding() { + var original = fixture(); + var changedReservation = + new CanonicalGameplayIssuerBindingLocalAcknowledgement.Reservation( + original.reservation().reservationId(), + original.reservation().transitionId(), + original.reservation().reservationFence(), + original.reservation().partitionId(), + original.reservation().lifecycle(), + uuid(51), + original.reservation().issuerCoverageOperationFence().add(BigInteger.ONE), + original.reservation().coverageFence().add(BigInteger.ONE), + original.reservation().inventorySnapshotRevision().add(BigInteger.ONE), + original.reservation().inventoryRevision()); + + assertThatThrownBy( + () -> + new CanonicalGameplayIssuerBindingLocalAcknowledgement.Evidence( + original.operationId(), + original.issuerBindingLocalAcknowledgementGeneration(), + original.requestId(), + original.transitionId(), + original.candidateAccountIndexFence(), + original.issuerId(), + original.bindingRef(), + original.bindingGeneration(), + original.memberValueBytes(), + original.memberValueDigest(), + changedReservation, + original.anchor(), + original.memberOperation(), + original.currentSource(), + original.physicalReadback(), + original.capacity(), + original.sqlCurrentnessDigest())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("exact member and proof tuples"); + } + + private static CanonicalGameplayIssuerBindingLocalAcknowledgement.Evidence fixture() { + var sourceMember = CanonicalGameplayIssuerMemberV2ValueCodecTest.fixture(); + var original = sourceMember.reservation(); + var reservation = + new CanonicalIssuerPartitionReservation( + original.reservationId(), + sourceMember.owner(), + sourceMember.bindingGeneration(), + original.transitionId(), + original.partitionId(), + CanonicalIssuerPartitionReservation.Lifecycle.RESERVED, + original.reservationFence(), + original.issuerCoverageOperationId(), + original.issuerCoverageOperationFence(), + original.coverageFence(), + original.inventorySnapshotRevision(), + original.inventoryRevision()); + var member = + new CanonicalGameplayIssuerMemberV2Value( + sourceMember.owner(), + sourceMember.bindingGeneration(), + reservation, + sourceMember.anchor(), + sourceMember.memberOperation(), + sourceMember.anchor().operationFence(), + sourceMember.layoutDescriptor(), + sourceMember.sourceCheckpoint(), + sourceMember.incarnation()); + byte[] memberBytes = CanonicalGameplayIssuerMemberV2Codec.encode(member); + byte[] readbackBytes = "exact-physical-field-set/v1".getBytes(StandardCharsets.UTF_8); + byte[] checkpointBytes = member.sourceCheckpoint().exactCheckpointBytes(); + byte[] eventBytes = member.sourceCheckpoint().latestIssuerEventBytes(); + byte[] incarnationBytes = + CanonicalGameplayIssuerInstalledAnchor.encodeIncarnation(member.incarnation()); + byte[] layoutBytes = member.layoutDescriptor().exactDescriptorBytes(); + byte[] anchorBytes = "installed-anchor/v1".getBytes(StandardCharsets.UTF_8); + BigInteger one = BigInteger.ONE; + BigInteger bound = + member + .layoutDescriptor() + .partitionCount() + .multiply(member.layoutDescriptor().partitionCapacity()); + return new CanonicalGameplayIssuerBindingLocalAcknowledgement.Evidence( + member.memberOperation().operationId(), + BigInteger.valueOf(83), + uuid(41), + member.reservation().transitionId(), + uuid(42), + member.owner().issuerId(), + member.owner().bindingRef().bytes(), + member.bindingGeneration(), + memberBytes, + CanonicalGameplayIssuerMemberV2Codec.sha256(memberBytes), + new CanonicalGameplayIssuerBindingLocalAcknowledgement.Reservation( + reservation.reservationId(), + reservation.transitionId(), + reservation.reservationFence(), + reservation.partitionId(), + reservation.lifecycle().name(), + reservation.issuerCoverageOperationId(), + reservation.issuerCoverageOperationFence(), + reservation.coverageFence(), + reservation.inventorySnapshotRevision(), + reservation.inventoryRevision()), + new CanonicalGameplayIssuerBindingLocalAcknowledgement.Anchor( + member.anchor().issuerCoverageOperationId(), + member.anchor().issuerCoverageOperationId(), + member.anchor().operationFence(), + member.anchor().coverageFence(), + member.anchor().issuerInventorySnapshotRevision(), + BigInteger.valueOf(5), + member.issuerControlEpoch(), + member.layoutDescriptor().layoutVersion(), + member.layoutDescriptor().partitionCount(), + member.layoutDescriptor().partitionCapacity(), + member.layoutDescriptor().mappingIdentity(), + layoutBytes, + member.layoutDescriptor().descriptorDigest(), + anchorBytes, + CanonicalGameplayIssuerMemberV2Codec.sha256(anchorBytes)), + new CanonicalGameplayIssuerBindingLocalAcknowledgement.MemberOperation( + member.memberOperation().operationId(), + member.memberOperation().operationFence(), + member.memberOperation().coverageGeneration()), + new CanonicalGameplayIssuerBindingLocalAcknowledgement.CurrentSource( + member.owner().issuerAuthGeneration(), + checkpointBytes, + member.sourceCheckpoint().checkpointDigest(), + eventBytes, + member.sourceCheckpoint().latestIssuerEventDigest(), + incarnationBytes, + CanonicalGameplayIssuerMemberV2Codec.sha256(incarnationBytes)), + new CanonicalGameplayIssuerBindingLocalAcknowledgement.PhysicalReadback( + memberBytes, + CanonicalGameplayIssuerMemberV2Codec.sha256(memberBytes), + memberBytes, + CanonicalGameplayIssuerMemberV2Codec.sha256(memberBytes), + CanonicalGameplayIssuerMemberV2Codec.sha256(readbackBytes), + 2, + 3, + 1, + 1, + 1), + new CanonicalGameplayIssuerBindingLocalAcknowledgement.Capacity( + reservation.partitionId(), + member.layoutDescriptor().partitionCapacity(), + BigInteger.ZERO, + BigInteger.ZERO, + BigInteger.ZERO, + one, + one, + bound), + CanonicalGameplayIssuerMemberV2Codec.sha256( + "current-sql-cohort/v1".getBytes(StandardCharsets.UTF_8))); + } + + private static UUID uuid(long value) { + return UUID.fromString(String.format("00000000-0000-0000-0000-%012d", value)); + } +} From 0dc7e58d6c9e77c0e759fd62a8a23f22381b7453 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 26 Oct 2026 23:20:18 +1300 Subject: [PATCH 02/26] Define initial issuer barrier under the existing inventory owner --- design/architecture/system-architecture-redis.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/design/architecture/system-architecture-redis.md b/design/architecture/system-architecture-redis.md index e781f0c9ae..5212bc161d 100644 --- a/design/architecture/system-architecture-redis.md +++ b/design/architecture/system-architecture-redis.md @@ -447,6 +447,8 @@ The issuer owner establishes that anchor only from an authorized immutable layou The physical v2 HASH value above is a projection, not the installed anchor or an issuer binding-local acknowledgement. Its anchor tuple and preserved original reservation tuple remain separate even when a bootstrap operation links both to the same frozen cohort. The separate issuer acknowledgement must be explicitly versioned and bind the complete anchor, exact local transition/reservation, member and capacity readbacks, current control/incarnation evidence, and owner-issued per-transition generation. Neither physical-row parsing nor the account `accountIndexAcknowledgement` schema v2 can manufacture that result; the account acknowledgement and its CLOSED barrier receipt establish no issuer anchor or issuer `INSTALLED`/`OPEN` state. The final tenant-local CAS must positively compare the exact issuer barrier `OPEN` state and owner epoch/incarnation with the original candidate and required Account, issuer, and region evidence; global issuer-index and capacity keys never enter tenant-local Lua. +Within the existing Game Session issuer inventory owner, initial tenant-local issuer barriers use a distinct typed live admission-control row. The immutable bootstrap intent, control row and installed anchor retain their original layout provenance; the live barrier epoch is independently owner-allocated and never interpreted as the bootstrap epoch. Installation requires the qualified anchor, exact current Account source, registered target and stable storage incarnation. Every ordinary preparation, pending initializer, issuer acknowledgement, barrier read and final consumer joins current live control in the same inventory, layout-control and admission-control lock order. Under that current authority, the owner persists one immutable initializer and its complete intended `OPEN` tuple before Redis work. Neither a missing key, an installed anchor alone nor Account's `NO_ACTIVE_ACCOUNT_WIDE_FLOW` state authorizes initialization. Pending initializers participate in the same serialized issuer intent/cutoff cohort as binding preparations: a concurrent intent blocks new initializers, captures every existing initializer, installs the required tenant-local cutoff barriers, and reaches declared `INSTALLED` only after its complete cohort qualifies. The initial one-key tenant-slot CAS refuses conflicting, residual, previously `CLOSED`, newer-epoch or reset state; it never reopens or overwrites a cutoff. Exact independent readback and a durable original-initializer receipt precede use, with current control, epoch, source and incarnation revalidated after the remote phase and again for an admitting issuer acknowledgement and final tenant-local CAS. No SQL transaction spans Redis. Lost replies and partial attempts retain the original initializer and stay non-admitting on uncertainty; they create no reset, recovery or activation authority. + ### Recovery and Cutoff Scope Authority The permitted scope is part of the evidence contract, not an operator hint. A region- or tenant-scoped preserved-session parent may enumerate only its binding-local snapshot, repair the region-local and tenant-scoped families it owns, and validate a linked child result. It may not map an issuer layout, perform issuer Redis field or reservation-capacity repair, read back issuer partitions for coverage, publish an issuer-partition acknowledgement, or claim global account-index coverage from its narrow snapshot. An issuer-wide child or standalone issuer operation must use a complete authoritative issuer inventory. A standalone operation carries `parentRecoveryOperationId=NOT_APPLICABLE`, `parentLifecycle=NOT_APPLICABLE`, `parentOperationFence=NOT_APPLICABLE`, and `parentCoverageFence=NOT_APPLICABLE`, then uses its own `issuerCoverageOperationId`, `issuerCoverageOperationFence`, distinct `coverageFence`, later `coverageGeneration`, pinned layout, and all finite partitions. A linked child retains the exact parent tuple through its independent edge but does not nest under the parent maintenance lock; the parent owns that lock and the child owns only its operation and coverage fences. An account-wide operation may cover only the untagged account family from a complete account inventory and its own account coverage evidence; it cannot substitute for issuer coverage. A cluster recovery must rebuild or consume complete per-account and per-issuer coverage for the deployment rather than treating a local region, tenant, or aggregate snapshot as global proof. From dacd20895e2f0d10b2a2327f0fd1650bbe9e0ddb Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 27 Oct 2026 10:34:50 +1300 Subject: [PATCH 03/26] Assemble local NEW barrier and candidate source checkpoint --- ...em-architecture-jwt-and-token-contracts.md | 2 + .../architecture/system-architecture-redis.md | 2 + .../system-architecture-session-behavior.md | 6 +- ...playAccountAdmissionBarrierRepository.java | 25 + ...alGameplayAccountAdmissionFenceIntent.java | 4 +- ...ntInitialBarrierInitializerRepository.java | 895 ++++++++++++ ...nicalGameplayAccountInitialBarrierKey.java | 18 + ...meplayAccountInitialBarrierRedisOwner.java | 564 ++++++++ ...calGameplayAccountInitialBarrierValue.java | 79 ++ ...onicalGameplayAccountInitialOpenProof.java | 85 ++ ...calGameplayBindingInventoryRepository.java | 2 + ...icalGameplayIssuerAdmissionBarrierKey.java | 38 + ...eplayIssuerAdmissionBarrierRedisOwner.java | 539 ++++++++ ...suerAdmissionBarrierRedisOwnerFactory.java | 22 + ...eplayIssuerAdmissionBarrierRepository.java | 981 +++++++++++++ ...alGameplayIssuerAdmissionBarrierValue.java | 558 ++++++++ ...eplayIssuerAdmissionControlRepository.java | 1214 +++++++++++++++++ ...alGameplayIssuerAdmissionControlValue.java | 473 +++++++ ...ssuerBindingLocalProjectionRepository.java | 10 +- ...CanonicalGameplayOriginalNewCandidate.java | 215 +++ ...icalGameplayOriginalNewCandidateCodec.java | 721 ++++++++++ ...lGameplayProtectedIncarnationReceiver.java | 270 +++- .../CanonicalGameplaySessionRedisKeys.java | 22 + ...alGameplayTenantGameplayTagRepository.java | 88 +- ...InitialBarrierRedisScriptContribution.java | 52 + ...missionBarrierRedisScriptContribution.java | 62 + ...anonical_issuer_live_admission_control.sql | 288 ++++ ...ical_initial_account_admission_barrier.sql | 295 ++++ ...account-admission-barrier-initial-open.lua | 57 + ...session-issuer-admission-barrier-close.lua | 133 ++ ...-session-issuer-admission-barrier-open.lua | 106 ++ ...ccount-admission-barrier-initial-open.json | 41 + ...ession-issuer-admission-barrier-close.json | 48 + ...session-issuer-admission-barrier-open.json | 44 + ...ssionBarrierRepositoryIntegrationTest.java | 286 ++++ ...tialBarrierRedisScriptIntegrationTest.java | 225 +++ ...eplayAdmissionAbortCompositionFixture.java | 7 +- ...ssionBarrierRepositoryIntegrationTest.java | 863 ++++++++++++ ...calOperationRepositoryIntegrationTest.java | 6 + ...BindingLocalRedisOwnerIntegrationTest.java | 2 + ...nationReceiverPostgresIntegrationTest.java | 378 ++++- ...ayAccountInitialBarrierRedisOwnerTest.java | 495 +++++++ ...ameplayAccountInitialBarrierValueTest.java | 180 +++ ...nicalGameplayOriginalNewCandidateTest.java | 511 +++++++ 44 files changed, 10866 insertions(+), 46 deletions(-) create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierInitializerRepository.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierKey.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierRedisOwner.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierValue.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialOpenProof.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierKey.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRedisOwner.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRedisOwnerFactory.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepository.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierValue.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionControlRepository.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionControlValue.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCandidate.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCandidateCodec.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayAccountInitialBarrierRedisScriptContribution.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayIssuerAdmissionBarrierRedisScriptContribution.java create mode 100644 services/game-session-service/src/main/resources/db/migration/V1046__canonical_issuer_live_admission_control.sql create mode 100644 services/game-session-service/src/main/resources/db/migration/V1047__canonical_initial_account_admission_barrier.sql create mode 100644 services/game-session-service/src/main/resources/redis/lua/game-session-account-admission-barrier-initial-open.lua create mode 100644 services/game-session-service/src/main/resources/redis/lua/game-session-issuer-admission-barrier-close.lua create mode 100644 services/game-session-service/src/main/resources/redis/lua/game-session-issuer-admission-barrier-open.lua create mode 100644 services/game-session-service/src/main/resources/redis/scripts/game-session-account-admission-barrier-initial-open.json create mode 100644 services/game-session-service/src/main/resources/redis/scripts/game-session-issuer-admission-barrier-close.json create mode 100644 services/game-session-service/src/main/resources/redis/scripts/game-session-issuer-admission-barrier-open.json create mode 100644 services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierRedisScriptIntegrationTest.java create mode 100644 services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepositoryIntegrationTest.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierRedisOwnerTest.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierValueTest.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCandidateTest.java diff --git a/design/architecture/system-architecture-jwt-and-token-contracts.md b/design/architecture/system-architecture-jwt-and-token-contracts.md index 556027a428..888128fb89 100644 --- a/design/architecture/system-architecture-jwt-and-token-contracts.md +++ b/design/architecture/system-architecture-jwt-and-token-contracts.md @@ -382,6 +382,8 @@ Exact route identity and known route-class selection precede claim-shape and aud `tokenGeneration` is distinct from every field in `authorityTuple` and from `issuanceFence`. It binds refresh/replacement ordering for one token lineage; it does not grant scope, replace current authority checks, or serve as restart authority by itself. Game Session uses the durable protected single-use rebind handle in the gameplay binding when a restart or takeover owner no longer has the raw private delegation JWT; Account consumes that handle and returns the next `tokenGeneration` value plus replacement handle under the binding/fence protocol. `membershipVersion` remains separate from `authorityTuple.membershipAuthorityGeneration` and must be checked independently. +For the original public-production `NEW` binding, Account creates one fresh `ORIGINAL_NEW` bound-token lineage anchored to the immutable original binding and lease/transition after the original Account commit. Its first `tokenGeneration` is exactly `1` within that lineage and its signed `jti` is distinct from the unscoped `LOGIN` lineage, row and `jti`; the original signed `LOGIN` evidence remains unchanged. The existing Account issuance and registry owner persists the original issuance identity, complete frozen claims and protected credential/handle result once and links them to the exact original committed receipt. Concurrent requests and exact retries for the same original binding/lease reuse that genesis; they cannot start another lineage, remint, extend expiry or substitute replacement/REBIND. Current profile, source and issuance-fence checks remain independent of token generation and Game Session barrier epochs. The original lease bytes remain immutable, and unavailable protected recovery fails closed. [Session Behavior](./system-architecture-session-behavior.md#canonical-public-production-new-admission) owns publication of the complete authenticated binding and confirmation of its actual admission-time continuity anchor; a preissued handle is not usable before those original admission and currentness predicates are established. This genesis rule does not authorize general rotation, replacement or lineage migration. + For JWT-bearing authorization routes, the issued-token registry has only two structural exceptions: an explicitly public route in the route matrix whose contract requires no JWT, and the exact matrix-declared `gameplay-connect` Gateway handshake with its bounded single-use replay contract. No JWT-bearing route may turn registry absence into authorization. Pending-deletion routes use their separate opaque `pending-deletion-access` credential and dedicated registry contract; that lifecycle credential is not a JWT or a third issued-token-registry exception. The logout endpoints have a separate lifecycle-only reconciliation path: after local signature/profile/time/subject validation, `AuthLogout` may return the stored result only from a durable Account pending/committed intent or tombstone for that exact token, and `AuthLogoutAll` may return the stored result only from durable Account evidence that a prior logout-all superseded the presented authority. These retries create no authorization context and cannot be reused by any other route; a current or ambiguous token without matching durable evidence remains denied. JWT verification model (normative): diff --git a/design/architecture/system-architecture-redis.md b/design/architecture/system-architecture-redis.md index 9803e9a5d1..dcbc4b6a12 100644 --- a/design/architecture/system-architecture-redis.md +++ b/design/architecture/system-architecture-redis.md @@ -301,6 +301,8 @@ Authenticated gameplay session keys capture: The authenticated gameplay payload is one complete canonical contract, not a compatibility family. Every authenticated gameplay binding must carry `schemaVersion=2`; a missing version, `schemaVersion=1`, or any other unsupported version fails closed before the record can be used for refresh, resume, rebind, takeover, admission, backend authorization, or recovery. There is no reduced authenticated payload for a non-resumable binding: terminal or cleanup state does not relax the schema or become retained admission evidence, and fresh `LOGIN`/`PLAY` is required to establish a new binding. Bootstrap/pre-auth context remains unauthenticated and is not an authenticated gameplay payload. +The original-`NEW` provisional artifact has a separate closed, non-admitting type at the same canonical session key. It is not an authenticated session schema and is rejected by authenticated readers, backend authorization and `PLAY`/`LOOK`. Its exact physical preimage is checked by the final tenant-local CAS; no unchecked side candidate or global key may substitute. [Session Behavior](./system-architecture-session-behavior.md#session-and-identity-management) owns the ordering from the original Account commit and complete credential to final admission, including the scope-dependent six- or seven-key set and confirmation of the actual admission-time continuity anchor. + `schemaVersion=2` is the canonical authenticated-session contract and requires the same common fields plus exactly ten authentication-specific fields: `authTokenHash`, `authTokenIssuedAt`, `authTokenExpiresAt`, `tokenGeneration`, `issuanceFence`, `rebindHandle`, `continuityBindingExpiresAt`, the complete `membershipBaseline`, the complete `authorityTuple`, and the complete `outboxCheckpoints` set. Readers, refresh, resume, rebind, admission, recovery, and CAS scripts must reject any authenticated record whose version is not exactly `2` or whose required field is absent, malformed, or unavailable for its declared type. The authentication identity, time, generation, fence, handle, and continuity fields are canonical scalar fields; `membershipBaseline` must instead be one complete same-snapshot object whose nested `membershipBaseline.membershipVersion` is exactly the one-tenant map `{tenantId: version}`, while `authorityTuple` is the complete object and `outboxCheckpoints` is the complete set. A missing baseline member or a multi-tenant, differently keyed, aggregate, scalarized, or otherwise malformed nested map fails closed. `membershipBaseline.membershipAuthorityGeneration` and `authorityTuple.membershipAuthorityGeneration` are both required in their owning objects and are compared independently; a duplicate standalone top-level `membershipAuthorityGeneration` is an invalid extra field and is rejected even when its value matches. The rotation `installationIdentity` is not an additional `schemaVersion=2` authenticated gameplay field. It is candidate-installation metadata carried by the lease-scoped acknowledgement and durable installation-attempt carriers, with the established shape `{rotationOperationId, leaseId, gameplayBindingId, installationFence}`. The durable installation attempt is keyed by the existing `rotationOperationId`; the first session-only CAS and the second fenced session-only CAS must carry and exact-compare that same linkage before the candidate can become admissible. No `installationIdentity` member, including `rotationOperationId`, is retained as an undeclared field in the final admissible gameplay binding. The `INSTALLING` candidate remains non-admissible until the matching acknowledgement and second fenced CAS complete. diff --git a/design/architecture/system-architecture-session-behavior.md b/design/architecture/system-architecture-session-behavior.md index c7e673ea42..0df4a73eec 100644 --- a/design/architecture/system-architecture-session-behavior.md +++ b/design/architecture/system-architecture-session-behavior.md @@ -185,7 +185,7 @@ Target-state Game Session must also maintain bounded authoritative secondary ind Index contract requirements: - In target state, Game Session is the sole writer for all six index families; Account authority and realm-grant state remain the authorization source, not the indexes. -- The shard-local CAS/update flow mutates exactly the gameplay session record plus the four tenant-scoped indexes: character, account-tenant, tenant, and realm-grant. The final binding CAS additionally reads the exact account-admission barrier as a checked key and never writes it; the separate one-key CLOSED installer owns that mutation. All of these keys share `{tenantGameplayTag}`. The initial CAS publishes only the provisional candidate; the final follow-up CAS is the atomic controller boundary for takeover, resume, and tenant/grant-binding decisions inside Redis Cluster, and exact-compares the provisional generation, Account-owned exact-binding admission lease identity, monotonic lease fence, applicable authority cutoff checkpoint, and required follow-up acknowledgements. +- The shard-local CAS/update flow mutates the gameplay session record plus every applicable tenant-scoped index. Public-production and realm-unscoped bindings use character, account-tenant and tenant indexes; a grant-gated binding additionally uses its real Account-owned `grant/v1` realm-grant index. The final binding CAS also reads the exact account-admission and issuer-admission barriers as checked keys and never writes either barrier. The closed key set therefore contains six keys for public-production or realm-unscoped bindings and seven for grant-gated bindings, all sharing `{tenantGameplayTag}`. The owner selects that set from validated realm scope and rejects an inapplicable or missing key; a fabricated grant or sentinel key is not permitted. The initial CAS publishes only the typed non-admitting provisional candidate; the final follow-up CAS is the atomic controller boundary for takeover, resume, and tenant/grant-binding decisions inside Redis Cluster, and exact-compares the provisional generation, Account-owned exact-binding admission lease identity, monotonic lease fence, applicable authority cutoff checkpoint, and required follow-up acknowledgements. - The cross-tenant `session:game:index:account:` and issuer-partition indexes are explicitly excluded from that shard-local CAS because they span tenant hash slots or issuer partitions. The untagged account key is also excluded from every tenant-local Lua invocation. Before the tenant-scoped CAS publishes a new binding, Game Session durably commits deterministic account-index and issuer-index repair obligations keyed to that binding transition. The account obligation contains the expected prior generation, candidate `bindingGeneration`, unique transition identity, desired add/remove, and `accountIndexFence`; the issuer obligation also carries its exact reservation identity. The shard-local CAS may publish only a provisional binding with each applicable `accountIndexState=REPAIR_REQUIRED` and `issuerIndexState=REPAIR_REQUIRED`; it is not admissible for gameplay, resume, or takeover. Game Session then performs each separate idempotent single-key index/capacity compare-and-set, reads back the exact generation/fence-qualified member and reservation state, and durably acknowledges each matching account/issuer obligation. The region-lease bridge is another ordered, separately acknowledged follow-up using the validated binding generation and region epoch. Only after all required account, issuer, and region acknowledgements does the final follow-up shard-local CAS exact-compare the provisional generation, set the applicable states to `ACKNOWLEDGED`, and admit the binding at the controller linearization point. This ordered protocol closes the cross-slot and region-bridge crash windows without claiming a cross-store transaction. - An issuer-index write or removal atomically compares the complete expected physical v2 value, including its anchor tuple, the independently preserved original reservation coverage tuple, and local member-operation and control/incarnation evidence, before changing the hash field. The operation also compares the exact original reservation owner, transition, partition/layout, lifecycle, reservation fence and revision; the original reservation tuple is not reconstructed from or required to equal the anchor tuple. For bootstrap, the owner must prove that the original reservation belongs to the frozen complete cohort and is linked to the exact bootstrap operation and fences. An identical already-applied value is an idempotent success, while a newer or conflicting value is a repair conflict. At the start of an issuer cutoff or recovery, Game Session captures the active layout pointer's version, partition count, and capacity while establishing the operation and coverage fences, then reads exactly that pinned finite partition range and maps every binding through the canonical mapping helper; it does not reread the pointer and mix layouts during the operation. If the pointer no longer matches before acknowledgement, the current operation fails closed or enters the explicit layout-transition workflow, which accounts for the complete pinned old layout and separately built new layout before cutover; neither workflow evaluates a mixed partition set. The operation validates every returned value and reservation, then fences or terminates the referenced bindings through their ordinary binding CAS. Missing Redis responses, unreadable partitions, unresolved reservations or repair obligations, or conflicting field values are unavailable or ambiguous coverage, never an empty result. Recovery rebuilds each partition from the complete durable active-binding and reservation inventory using the same expected-value compare-and-set, canonical mapping, and capacity rules and clears the repair obligation only after every required partition, reservation, and binding acknowledgement is proven. - An issuer-partition acknowledgement is a durable evidence object, not an aggregate flag. For preserved region/tenant recovery it must carry the child-owned `issuerCoverageOperationId` and child lifecycle, the child `issuerCoverageOperationFence`, distinct issuer-wide `coverageFence`, `coverageGeneration`, issuer-wide `inventorySnapshotRevision`, pinned `issuerIndexLayoutVersion`, pinned partition count and capacity, `partitionId`, the exact `issuer/` cutoff checkpoint (`issuerAuthGeneration`, `issuanceFence`, and complete applicable `outboxCheckpoints`), every reservation identity with its owner, transition, lifecycle, fence, and inventory revision, and the capacity tuple `{partitionId, reservationCount, partitionCapacity, aggregateReservationCount, aggregateCapacity}`. The independent parent edge and the parent's consumption record carry the exact linked `parentRecoveryOperationId`, both current lifecycles, parent `operationFence`, distinct `parentCoverageFence`, resolved issuer/scope, and link revision; the child request/digest, transition, partition and reservation readback, acknowledgement, and immutable child result are parent-independent. `coverageGeneration=NOT_YET_ISSUED` remains the pre-coverage value and becomes concrete only after complete finite coverage is proven. For a standalone issuer-wide operation, the operation identity is its own issuer coverage operation identity and still carries its own maintenance fence and coverage fence; all parent fields and account-wide fields are the exact `NOT_APPLICABLE` marker plus `NO_ACTIVE_ACCOUNT_WIDE_FLOW`. The acknowledgement is valid only when all of that evidence comes from the same complete issuer-wide snapshot and operation attempt, with exact readback of the partition and reservation state. Cross-snapshot, cross-attempt, narrow-scope, stale-layout, changed-cutoff, mixed-partition, missing-reservation, or partial-capacity evidence is rejected; no acknowledgement may be assembled from separately read responses or used to authorize a different operation or layout. @@ -207,6 +207,8 @@ Every `GameplayBindingInventory` row selected for an account-index operation rec The tenant-qualified repair protocol is mandatory and the untagged account key is never included in tenant-local Lua or session-only CAS. Before the tenant-local session CAS can publish an active or provisional binding, Game Session commits a PostgreSQL repair obligation containing the expected prior generation, candidate `bindingGeneration`, unique transition identity, desired account-index add/remove, and `accountIndexFence`. The shard-local CAS may publish the candidate only when the expected prior generation and current session owner/fence still match; it records `accountIndexState=REPAIR_REQUIRED`, so the candidate is provisional and non-admissible. The separate account-key operation carries the same transition identity and fence, adds or retains the generation-qualified candidate before removing an old member, and refuses a removal when the authoritative binding or durable obligation has a newer generation/fence. A stale add may remain as an extra projection for repair, but a stale remove must never hide a newer binding. Game Session acknowledges only an exact `accountIndexAcknowledgement` matching the schema below and the fenced add/remove outcome, then uses a follow-up tenant-local CAS to set `accountIndexState=ACKNOWLEDGED` only when the same candidate generation/fence and the acknowledgement's operation/snapshot carrier are still current and matching. A missing, stale, conflicting, cross-tenant, or unavailable member leaves the binding non-admissible and the account scope fenced. +An original `NEW` candidate before Account finalization is a distinct typed, non-admitting lease-bound artifact at the canonical session key, not an incomplete authenticated `schemaVersion=2` session. Its exact positive physical readback may support the original provisional decision and Account finalization, but every authenticated reader and `PLAY`/`LOOK` path rejects it. After the original Account commit, Account supplies the complete bound credential and protected opaque rebind handle from the unchanged original binding, membership baseline and checkpoints. Only the final checked tenant-local CAS replaces the exact candidate with the complete authenticated session and establishes `admissionAt` and the immutable continuity expiry. The preissued handle does not claim those future times; its original issuance record confirms them only from the authenticated original Game Session admission result, and missing confirmation recovers that same result without reminting or extending authority. + The exact account-index acknowledgement schema is: ```text @@ -247,6 +249,8 @@ Account-control acquisition and per-tenant barrier installation are a separate a The account-qualified barrier key is `session:game:account-admission:{tenantGameplayTag}::`. Its persistent hash has exactly nine fields: `schema=gs_account_admission_barrier/v1`, `accountId`, `tenantId`, `playableStateNamespaceId`, `tenantGameplayTag`, `ownerOperationId`, `ownerFenceEpoch`, `incarnationDigest`, and `state`. Epochs are canonical decimal strings compared without floating-point conversion. A `CLOSED` acquisition uses a positive epoch; the positively established initial no-active control epoch may be zero, so the first acquisition may close a prior `OPEN` epoch `0` at epoch `1`. Zero never stands for a missing control row. A missing key may be created `CLOSED` only under the current original intent. An older well-formed barrier may advance only under a newer epoch and a different owner operation; equal epoch permits only exact same-operation, same-incarnation `CLOSED` replay. Malformed, expiring, foreign-scope, equal-conflicting, or newer barriers are refused without mutation. This key shares the tenant gameplay slot with the final session CAS; the global account index is never a member of that Lua invocation. A `CLOSED` write or a key-builder result grants no opening or admission authority. +An INITIAL-only `OPEN` install requires a positively present SQL `NO_ACTIVE_ACCOUNT_WIDE_FLOW` source and uses its exact nonnegative control epoch, including zero when established by that owner. SQL control is not Account identity, membership, token or storage-incarnation authority. The existing inventory-clock-to-Account-control serialization retains one original initializer for the exact account, tenant and playable-state namespace target, complete source tuple and protected incarnation. Pending initializers are part of the next acquisition's frozen cohort and target derivation; the racing initializer is included or refused when the intent wins. Before any create attempt, SQL durably records that dispatch may have occurred. Only the original never-installed target may be created `OPEN`, followed by independent exact physical readback, protected observations and guarded SQL completion against current control. Retry of an existing original `OPEN` is read-only; missing storage after possible dispatch or completed installation is reset or uncertainty, never permission to recreate. A previously `CLOSED` target cannot reopen under this arm, and a newer cutoff wins. No SQL transaction spans Redis or protected-source calls. The final session CAS still requires both exact current `OPEN` barriers, original Account commit and all account, issuer and region acknowledgements. + The stable `incarnationDigest` is SHA-256 over strict canonical JSON for the protected attestor binding, accepted canonical attestation digest, complete `targetDeploymentEvidence/v1` tuple (including deployment, Redis build, Lua registry, boot/startup and storage/AOF generations), and separately observed ACL and Redis-configuration digests. Fresh current-observation nonces, observation times, operation context, and signing-key identifiers do not change that stable storage binding. Each signed bounded current observation must bind the fresh receiver nonce and time window to the original account operation/fence, frozen cohort and exact tenant/namespace target, and must match the fixed trusted deployment expectation. The operational accepted-attestation/current-proof source is not supplied by the local controlled-signature fixture, so that fixture proves verifier mechanics only, not production custody or reset continuity. A retained barrier with the same operation and epoch but a changed stable incarnation is a conflict even after a fresh protected observation; it cannot be rewritten in place by an exact retry. Game Session’s account-wide fenced recovery owner must resolve replacement under the [canonical reset and recovery boundary](./system-architecture-redis-reset-and-recovery.md#canonical-reset-sequence-boundary), preserving the original intent and historical evidence while the affected target stays closed and unresolved. The local CLOSED installer does not supply that recovery; see the [implementation gap](../project-management/implementation-tracking/player-access-and-session.md#canonical-new-admission-components). diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountAdmissionBarrierRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountAdmissionBarrierRepository.java index 805d6cf439..00e8e8da2f 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountAdmissionBarrierRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountAdmissionBarrierRepository.java @@ -627,6 +627,27 @@ private static List capt + " ON i.binding_ref = t.candidate_binding_ref" + " WHERE o.account_id = ? ORDER BY o.operation_id", accountId); + appendRows( + rows, + transaction, + CanonicalGameplayAccountAdmissionFenceIntent.CohortKind.INITIALIZER, + "SELECT i.original_request_id::text AS source_key, t.tenant_id," + + " t.playable_state_namespace_id, to_jsonb(i)::text AS source_record_json" + + " FROM game_session_canonical_initial_account_barrier_initializer i" + + " JOIN game_session_canonical_initial_account_barrier_target t" + + " ON t.initializer_id = i.initializer_id" + + " AND t.original_request_id = i.original_request_id" + + " WHERE i.account_id = ? ORDER BY i.original_request_id", + accountId); + appendRows( + rows, + transaction, + CanonicalGameplayAccountAdmissionFenceIntent.CohortKind.INITIAL_TARGET, + "SELECT t.initializer_id::text || ':' || t.target_ordinal::text AS source_key," + + " t.tenant_id, t.playable_state_namespace_id, to_jsonb(t)::text AS source_record_json" + + " FROM game_session_canonical_initial_account_barrier_target t" + + " WHERE t.account_id = ? ORDER BY t.initializer_id, t.target_ordinal", + accountId); return List.copyOf(rows); } @@ -693,6 +714,9 @@ private static void appendRows( + " LEFT JOIN game_session_canonical_gameplay_binding_inventory i" + " ON i.binding_ref = t.candidate_binding_ref" + " WHERE o.account_id = ?" + + " UNION ALL SELECT t.tenant_id, t.playable_state_namespace_id" + + " FROM game_session_canonical_initial_account_barrier_target t" + + " WHERE t.account_id = ?" + ") account_scopes" + " ORDER BY tenant_id, playable_state_namespace_id", accountId, @@ -701,6 +725,7 @@ private static void appendRows( accountId, accountId, accountId, + accountId, accountId); var targets = new ArrayList(); for (Record row : rows) { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountAdmissionFenceIntent.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountAdmissionFenceIntent.java index 8d805921c8..e3a0286ce1 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountAdmissionFenceIntent.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountAdmissionFenceIntent.java @@ -22,7 +22,9 @@ public enum CohortKind { ISSUER_OBLIGATION, REGION_OBLIGATION, MEMBER_REPAIR_CONTROL, - MEMBER_REPAIR_OPERATION + MEMBER_REPAIR_OPERATION, + INITIALIZER, + INITIAL_TARGET } private final UUID operationId; diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierInitializerRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierInitializerRepository.java new file mode 100644 index 0000000000..278456cd22 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierInitializerRepository.java @@ -0,0 +1,895 @@ +package net.firedevops.firemud.gamesession.repository; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.Clock; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.gamesession.dto.CanonicalGameplayLoginResult; +import net.firedevops.firemud.gamesession.dto.InitialGameplayLoginAttemptCoordinates; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.impl.DSL; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.databind.json.JsonMapper; + +/** + * Unregistered SQL owner for a single original-attempt INITIAL account barrier target. + * + *

This owner serializes with account-wide acquisition through inventory-clock then existing + * account-control locks. It never inserts missing account control and never changes Account token, + * admission-lease, or finalization authority. + */ +final class CanonicalGameplayAccountInitialBarrierInitializerRepository { + private static final String CONTROL = "game_session_canonical_account_coverage_control"; + private static final String INVENTORY_CLOCK = "game_session_canonical_binding_inventory_clock"; + private static final String ORIGINAL = "game_session_initial_gameplay_login_journal"; + private static final String INITIALIZER = + "game_session_canonical_initial_account_barrier_initializer"; + private static final String TARGET = "game_session_canonical_initial_account_barrier_target"; + private static final String NO_ACTIVE = "NO_ACTIVE_ACCOUNT_WIDE_FLOW"; + private static final JsonMapper JSON = JsonMapper.builder().build(); + + private final DSLContext dsl; + private final Clock clock; + + CanonicalGameplayAccountInitialBarrierInitializerRepository(DSLContext dsl) { + this(dsl, Clock.systemUTC()); + } + + CanonicalGameplayAccountInitialBarrierInitializerRepository(DSLContext dsl, Clock clock) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + this.clock = Objects.requireNonNull(clock, "clock"); + } + + /** + * Captures one exact initial target under the same inventory-clock then account-control order + * used by account-wide acquisition. The Account account id is taken from the authenticated result. + */ + InitializerSnapshot beginOrRead( + InitialGameplayLoginAttemptCoordinates original, + CanonicalGameplayLoginResult accountLogin, + UUID tenantId, + UUID playableStateNamespaceId) { + Objects.requireNonNull(original, "original attempt"); + Objects.requireNonNull(accountLogin, "authenticated Account LOGIN result"); + requireNonNil(tenantId, "tenantId"); + requireNonNil(playableStateNamespaceId, "playableStateNamespaceId"); + requireNoAmbientTransaction(); + CanonicalGameplayLoginResult.NonSecretEvidence accountEvidence = accountLogin.evidence(); + requireOriginalEvidence(original, accountEvidence); + String accountEvidenceDigest = digestAccountEvidence(accountEvidence); + + return dsl.transactionResult( + configuration -> { + DSLContext transaction = DSL.using(configuration); + BigInteger inventoryRevision = lockInventoryRevision(transaction); + Record control = lockExistingControl(transaction, accountEvidence.accountId()); + AccountControlSource source = readNoActiveControl(control, accountEvidence.accountId()); + if (inventoryRevision.signum() <= 0) { + throw conflict("Initial account barrier requires positive canonical inventory revision"); + } + requireExactOriginalLogin(transaction, original, accountEvidence); + + Record prior = readInitializer(transaction, original.requestId(), true); + if (prior != null) { + InitializerSnapshot snapshot = toSnapshot(prior); + requireSameOriginalTarget( + snapshot, + original, + accountEvidence.accountId(), + tenantId, + playableStateNamespaceId, + accountEvidenceDigest); + requireSameCurrentSource(snapshot, source); + return snapshot; + } + + UUID initializerId = randomNonNilUuid(); + while (initializerId.equals(original.requestId()) + || initializerId.equals(original.callerContextId()) + || initializerId.equals(accountEvidence.accountId())) { + initializerId = randomNonNilUuid(); + } + transaction.execute( + "INSERT INTO " + + INITIALIZER + + " (initializer_id, original_request_id, original_caller_context_id," + + " original_attempt_fence, account_id, account_login_evidence_digest," + + " source_control_state, source_control_epoch, inventory_snapshot_revision," + + " source_control_digest) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + initializerId, + original.requestId(), + original.callerContextId(), + original.expectedAttemptFence(), + accountEvidence.accountId(), + accountEvidenceDigest, + NO_ACTIVE, + new BigDecimal(source.epoch()), + new BigDecimal(inventoryRevision), + source.digest()); + transaction.execute( + "INSERT INTO " + + TARGET + + " (initializer_id, original_request_id, account_id, target_ordinal, tenant_id," + + " playable_state_namespace_id, target_state)" + + " VALUES (?, ?, ?, 0, ?, ?, 'NEVER_DISPATCHED')", + initializerId, + original.requestId(), + accountEvidence.accountId(), + tenantId, + playableStateNamespaceId); + Record created = readInitializer(transaction, original.requestId(), true); + if (created == null) throw conflict("Initial account barrier target readback is missing"); + InitializerSnapshot snapshot = toSnapshot(created); + requireSameOriginalTarget( + snapshot, + original, + accountEvidence.accountId(), + tenantId, + playableStateNamespaceId, + accountEvidenceDigest); + requireSameCurrentSource(snapshot, source); + return snapshot; + }); + } + + /** Reads the exact live owner context for protected INITIAL incarnation observation. */ + InitialObservationContext readCurrentObservationContext(UUID originalRequestId) { + requireNonNil(originalRequestId, "originalRequestId"); + requireNoAmbientTransaction(); + return dsl.transactionResult( + configuration -> { + DSLContext transaction = DSL.using(configuration); + transaction.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY"); + Record row = readInitializer(transaction, originalRequestId, false); + if (row == null) throw conflict("Exact original INITIAL account target is missing"); + InitializerSnapshot snapshot = toSnapshot(row); + AccountControlSource current = readCurrentNoActiveControl(transaction, snapshot.accountId()); + requireSameCurrentSource(snapshot, current); + requireOriginalJournalStillCurrent(transaction, snapshot); + return InitialObservationContext.from(snapshot); + }); + } + + InitializerSnapshot readCurrent(UUID originalRequestId) { + requireNonNil(originalRequestId, "originalRequestId"); + requireNoAmbientTransaction(); + return dsl.transactionResult( + configuration -> { + DSLContext transaction = DSL.using(configuration); + transaction.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY"); + InitializerSnapshot snapshot = readRequiredCurrent(transaction, originalRequestId, false); + AccountControlSource current = readCurrentNoActiveControl(transaction, snapshot.accountId()); + requireSameCurrentSource(snapshot, current); + requireOriginalJournalStillCurrent(transaction, snapshot); + return snapshot; + }); + } + + /** + * Commits the one-time remote-attempt state and its qualified pre-dispatch source before Redis is + * called. No subsequent path can receive another create permission. + */ + InitializerSnapshot recordDispatchPossible( + UUID originalRequestId, + CanonicalGameplayProtectedIncarnationReceiver.VerifiedIncarnation beforeIncarnation) { + requireNonNil(originalRequestId, "originalRequestId"); + Objects.requireNonNull(beforeIncarnation, "beforeIncarnation"); + requireNoAmbientTransaction(); + return dsl.transactionResult( + configuration -> { + DSLContext transaction = DSL.using(configuration); + lockInventoryRevision(transaction); + Record locator = readInitializer(transaction, originalRequestId, false); + if (locator == null) throw conflict("Exact original INITIAL account target is missing"); + InitializerSnapshot located = toSnapshot(locator); + Record control = lockExistingControl(transaction, located.accountId()); + AccountControlSource source = readNoActiveControl(control, located.accountId()); + InitializerSnapshot current = readRequiredCurrent(transaction, originalRequestId, true); + requireSameCurrentSource(current, source); + requireOriginalJournalStillCurrent(transaction, current); + requireInitialObservationMatches(current, beforeIncarnation); + if (current.state() != State.NEVER_DISPATCHED) { + throw conflict("INITIAL remote attempt was already possible and cannot be reissued"); + } + int updated = + transaction.execute( + "UPDATE " + + TARGET + + " SET target_state = 'DISPATCH_POSSIBLE'," + + " before_accepted_attestation_digest = ?, before_incarnation_digest = ?," + + " before_source_payload_digest = ?," + + " before_observation_issued_at_epoch_millis = ?," + + " before_observation_observed_at_epoch_millis = ?," + + " before_observation_expires_at_epoch_millis = ?" + + " WHERE initializer_id = ? AND target_ordinal = 0" + + " AND target_state = 'NEVER_DISPATCHED'", + beforeIncarnation.acceptedAttestationDigest(), + beforeIncarnation.incarnationDigest(), + beforeIncarnation.payloadDigest(), + beforeIncarnation.issuedAtEpochMillis(), + beforeIncarnation.observedAtEpochMillis(), + beforeIncarnation.expiresAtEpochMillis(), + current.initializerId()); + requireOne(updated, "INITIAL one-time remote dispatch claim was lost"); + InitializerSnapshot saved = readRequiredCurrent(transaction, originalRequestId, true); + if (saved.state() != State.DISPATCH_POSSIBLE + || !saved.beforeIncarnationDigest().equals(beforeIncarnation.incarnationDigest()) + || !saved.beforeSourcePayloadDigest().equals(beforeIncarnation.payloadDigest())) { + throw conflict("INITIAL remote dispatch state did not read back exactly"); + } + requireSameCurrentSource(saved, source); + return saved; + }); + } + + /** + * Accepts exact physical OPEN readback only while the positively read source control still has + * its captured NO_ACTIVE control epoch. This receipt is current SQL evidence, not a later + * admission decision. + */ + InitializerSnapshot acceptOpenReadback( + UUID originalRequestId, + CanonicalGameplayAccountInitialBarrierRedisOwner.Readback readback) { + requireNonNil(originalRequestId, "originalRequestId"); + Objects.requireNonNull(readback, "readback"); + requireNoAmbientTransaction(); + if (!originalRequestId.equals(readback.originalRequestId())) { + throw conflict("INITIAL readback belongs to a different original request"); + } + requireReadback(readback); + long now = clock.millis(); + if (now <= 0 + || now < readback.beforeIncarnation().issuedAtEpochMillis() + || now >= readback.beforeIncarnation().expiresAtEpochMillis() + || now < readback.afterIncarnation().issuedAtEpochMillis() + || now >= readback.afterIncarnation().expiresAtEpochMillis()) { + throw conflict("INITIAL protected incarnation observation expired before SQL completion"); + } + String fieldsDigest = digestFields(readback.value().fields()); + + return dsl.transactionResult( + configuration -> { + DSLContext transaction = DSL.using(configuration); + lockInventoryRevision(transaction); + Record locator = readInitializer(transaction, originalRequestId, false); + if (locator == null) throw conflict("Exact original INITIAL account target is missing"); + InitializerSnapshot located = toSnapshot(locator); + Record control = lockExistingControl(transaction, located.accountId()); + AccountControlSource source = readNoActiveControl(control, located.accountId()); + InitializerSnapshot current = readRequiredCurrent(transaction, originalRequestId, true); + requireSameCurrentSource(current, source); + requireOriginalJournalStillCurrent(transaction, current); + requireSameReadbackContext(current, readback); + if (current.state() == State.OPEN_INSTALLED) { + if (!fieldsDigest.equals(current.installedFieldsDigest())) { + throw conflict("An installed INITIAL OPEN value cannot be replaced"); + } + return current; + } + if (current.state() != State.DISPATCH_POSSIBLE) { + throw conflict("INITIAL OPEN readback has no persisted possible-dispatch state"); + } + int updated = + transaction.execute( + "UPDATE " + + TARGET + + " SET target_state = 'OPEN_INSTALLED', installed_fields_digest = ?," + + " completed_at = CURRENT_TIMESTAMP" + + " WHERE initializer_id = ? AND target_ordinal = 0" + + " AND target_state = 'DISPATCH_POSSIBLE'" + + " AND before_incarnation_digest = ?" + + " AND before_accepted_attestation_digest = ?", + fieldsDigest, + current.initializerId(), + readback.beforeIncarnation().incarnationDigest(), + readback.beforeIncarnation().acceptedAttestationDigest()); + requireOne(updated, "INITIAL OPEN completion lost its exact original SQL target"); + InitializerSnapshot saved = readRequiredCurrent(transaction, originalRequestId, true); + if (saved.state() != State.OPEN_INSTALLED + || !fieldsDigest.equals(saved.installedFieldsDigest())) { + throw conflict("INITIAL OPEN completion readback differs from its exact SQL postimage"); + } + requireSameCurrentSource(saved, source); + return saved; + }); + } + + void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw conflict("INITIAL account barrier phases require no ambient SQL transaction"); + } + try { + dsl.connectionResult( + connection -> { + if (!connection.getAutoCommit()) { + throw conflict("INITIAL account barrier phases cannot join a jOOQ transaction"); + } + return Boolean.TRUE; + }); + } catch (RuntimeException failure) { + if (failure instanceof CanonicalGameplayBindingInventoryConflictException) throw failure; + throw conflict("INITIAL account barrier SQL connection state is unavailable"); + } + } + + private static void requireReadback(CanonicalGameplayAccountInitialBarrierRedisOwner.Readback readback) { + CanonicalGameplayProtectedIncarnationReceiver.VerifiedIncarnation before = + readback.beforeIncarnation(); + CanonicalGameplayProtectedIncarnationReceiver.VerifiedIncarnation after = + readback.afterIncarnation(); + if (!readback.value().fields().equals(readback.barrierFields()) + || !CanonicalGameplayAccountInitialBarrierValue.FIELDS.equals( + readback.barrierFields().keySet()) + || !"OPEN".equals(readback.barrierFields().get("state")) + || !readback.beforeIncarnation() + .sourceControlEpoch() + .equals(readback.barrierFields().get("ownerFenceEpoch")) + || !readback.afterIncarnation() + .sourceControlEpoch() + .equals(readback.barrierFields().get("ownerFenceEpoch")) + || !before.incarnationDigest().equals(after.incarnationDigest()) + || !before.acceptedAttestationDigest().equals(after.acceptedAttestationDigest()) + || after.issuedAtEpochMillis() < before.issuedAtEpochMillis() + || after.observedAtEpochMillis() < before.observedAtEpochMillis()) { + throw conflict("Physical INITIAL OPEN readback or protected source tuple is not exact"); + } + } + + private static void requireSameReadbackContext( + InitializerSnapshot current, + CanonicalGameplayAccountInitialBarrierRedisOwner.Readback readback) { + requireInitialObservationMatches(current, readback.beforeIncarnation()); + requireInitialObservationMatches(current, readback.afterIncarnation()); + if (!current.initializerId().equals(readback.initializerId()) + || !current.originalRequestId().equals(readback.originalRequestId()) + || !current.accountId().equals(readback.accountId()) + || !current.tenantId().equals(readback.tenantId()) + || !current.playableStateNamespaceId().equals(readback.playableStateNamespaceId()) + || !current.accountLoginEvidenceDigest().equals(readback.accountLoginEvidenceDigest()) + || !current.sourceControlDigest().equals(readback.sourceControlDigest()) + || !current.inventorySnapshotRevision().equals(readback.inventorySnapshotRevision()) + || !readback.key() + .equals( + CanonicalGameplayAccountInitialBarrierKey.forTarget( + readback.assignment(), current.initializerId(), current.originalRequestId()))) { + throw conflict("Physical INITIAL OPEN readback differs from the original SQL initializer"); + } + Map fields = readback.barrierFields(); + if (!current.initializerId().toString().equals(fields.get("ownerOperationId")) + || !current.accountId().toString().equals(fields.get("accountId")) + || !current.sourceControlEpoch().toString().equals(fields.get("ownerFenceEpoch")) + || !current.tenantId().toString().equals(fields.get("tenantId")) + || !current.playableStateNamespaceId() + .toString() + .equals(fields.get("playableStateNamespaceId")) + || !readback.assignment().tenantGameplayTag().equals(fields.get("tenantGameplayTag"))) { + throw conflict("Physical INITIAL OPEN fields differ from the exact original target"); + } + } + + private static void requireInitialObservationMatches( + InitializerSnapshot snapshot, + CanonicalGameplayProtectedIncarnationReceiver.VerifiedIncarnation observation) { + if (observation.ownerKind() + != CanonicalGameplayProtectedIncarnationReceiver.OwnerKind.INITIAL_ACCOUNT_BARRIER + || !snapshot.initializerId().equals(observation.operationId()) + || !snapshot.originalRequestId().equals(observation.requestId()) + || !snapshot.originalCallerContextId().equals(observation.originalCallerContextId()) + || snapshot.originalAttemptFence() != observation.originalAttemptFence() + || !snapshot.accountId().equals(observation.accountId()) + || !snapshot.tenantId().equals(observation.tenantId()) + || !snapshot.playableStateNamespaceId().equals(observation.playableStateNamespaceId()) + || !NO_ACTIVE.equals(observation.sourceControlState()) + || !snapshot.sourceControlEpoch().toString().equals(observation.sourceControlEpoch()) + || !snapshot.inventorySnapshotRevision().toString() + .equals(observation.inventorySnapshotRevision()) + || !snapshot.accountLoginEvidenceDigest().equals(observation.accountLoginEvidenceDigest()) + || !snapshot.sourceControlDigest().equals(observation.sourceControlDigest()) + || !snapshot.targetDigest().equals(observation.barrierTargetDigest())) { + throw conflict("Protected INITIAL observation differs from original SQL source context"); + } + } + + private static void requireOriginalEvidence( + InitialGameplayLoginAttemptCoordinates original, + CanonicalGameplayLoginResult.NonSecretEvidence evidence) { + if (evidence == null + || !original.requestId().equals(evidence.requestId()) + || !original.callerContextId().equals(evidence.callerContextId()) + || original.expectedAttemptFence() <= 0L + || !net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile.PROFILE + .equals(evidence.tokenProfile()) + || evidence.accountId() == null + || evidence.tokenJti() == null + || evidence.tokenSha256() == null + || !evidence.tokenSha256().matches("[0-9a-f]{64}") + || !positiveDecimal(evidence.tokenGeneration()) + || !positiveDecimal(evidence.issuanceFence())) { + throw conflict("Authenticated Account LOGIN result differs from the exact original attempt"); + } + } + + private static void requireExactOriginalLogin( + DSLContext transaction, + InitialGameplayLoginAttemptCoordinates original, + CanonicalGameplayLoginResult.NonSecretEvidence evidence) { + Record row = + transaction.fetchOne( + "SELECT caller_context_id, expected_attempt_fence, abandoned, verified_token_jti," + + " verified_token_sha256, verified_token_generation, verified_issuance_fence" + + " FROM " + + ORIGINAL + + " WHERE request_id = ? FOR UPDATE", + original.requestId()); + if (row == null + || !original.callerContextId().equals(row.get("caller_context_id", UUID.class)) + || !Long.valueOf(original.expectedAttemptFence()) + .equals(row.get("expected_attempt_fence", Long.class)) + || !Boolean.FALSE.equals(row.get("abandoned", Boolean.class)) + || !evidence.tokenJti().equals(row.get("verified_token_jti", UUID.class)) + || !evidence.tokenSha256().equals(row.get("verified_token_sha256", String.class)) + || !Long.valueOf(Long.parseLong(evidence.tokenGeneration())) + .equals(row.get("verified_token_generation", Long.class)) + || !Long.valueOf(Long.parseLong(evidence.issuanceFence())) + .equals(row.get("verified_issuance_fence", Long.class))) { + throw conflict("Original Account COMMITTED evidence is not retained by the LOGIN journal"); + } + } + + private static void requireOriginalJournalStillCurrent( + DSLContext transaction, InitializerSnapshot snapshot) { + Record row = + transaction.fetchOne( + "SELECT caller_context_id, expected_attempt_fence, abandoned" + + " FROM " + + ORIGINAL + + " WHERE request_id = ?", + snapshot.originalRequestId()); + if (row == null + || !snapshot.originalCallerContextId().equals(row.get("caller_context_id", UUID.class)) + || !Long.valueOf(snapshot.originalAttemptFence()) + .equals(row.get("expected_attempt_fence", Long.class)) + || !Boolean.FALSE.equals(row.get("abandoned", Boolean.class))) { + throw conflict("Original INITIAL LOGIN was abandoned or its coordinates changed"); + } + } + + private static void requireSameOriginalTarget( + InitializerSnapshot snapshot, + InitialGameplayLoginAttemptCoordinates original, + UUID accountId, + UUID tenantId, + UUID namespaceId, + String accountEvidenceDigest) { + if (!snapshot.originalRequestId().equals(original.requestId()) + || !snapshot.originalCallerContextId().equals(original.callerContextId()) + || snapshot.originalAttemptFence() != original.expectedAttemptFence() + || !snapshot.accountId().equals(accountId) + || !snapshot.tenantId().equals(tenantId) + || !snapshot.playableStateNamespaceId().equals(namespaceId) + || !snapshot.accountLoginEvidenceDigest().equals(accountEvidenceDigest)) { + throw conflict("INITIAL original request was reused for a different Account or target"); + } + } + + private static void requireSameCurrentSource( + InitializerSnapshot snapshot, AccountControlSource current) { + if (!NO_ACTIVE.equals(snapshot.sourceControlState()) + || snapshot.sourceControlEpoch().signum() < 0 + || !snapshot.sourceControlEpoch().equals(current.epoch()) + || !snapshot.sourceControlDigest().equals(current.digest()) + || !snapshot.accountId().equals(current.accountId())) { + throw conflict("INITIAL source-control tuple is no longer the exact positive NO_ACTIVE row"); + } + } + + private static InitialObservationContext context(InitializerSnapshot snapshot) { + return InitialObservationContext.from(snapshot); + } + + private static BigInteger lockInventoryRevision(DSLContext transaction) { + Record row = + transaction.fetchOne( + "SELECT inventory_revision FROM " + INVENTORY_CLOCK + " WHERE singleton_id = 1 FOR UPDATE"); + if (row == null) throw conflict("Canonical binding inventory clock is missing"); + BigInteger revision = readBigInteger(row, "inventory_revision"); + if (revision.signum() <= 0) throw conflict("Initial account barrier inventory revision is not positive"); + return revision; + } + + private static Record lockExistingControl(DSLContext transaction, UUID accountId) { + Record row = + transaction.fetchOne( + "SELECT * FROM " + CONTROL + " WHERE account_id = ? FOR UPDATE", accountId); + if (row == null) throw conflict("Account coverage control row is missing; absence is not source"); + return row; + } + + private static AccountControlSource readCurrentNoActiveControl( + DSLContext transaction, UUID accountId) { + Record row = transaction.fetchOne("SELECT * FROM " + CONTROL + " WHERE account_id = ?", accountId); + if (row == null) throw conflict("Account coverage control row is missing; absence is not source"); + return readNoActiveControl(row, accountId); + } + + private static AccountControlSource readNoActiveControl(Record row, UUID accountId) { + if (!accountId.equals(row.get("account_id", UUID.class)) + || !NO_ACTIVE.equals(row.get("state", String.class)) + || row.get("current_operation_id", UUID.class) != null + || row.get("current_fence_intent_id", UUID.class) != null + || row.get("current_operation_fence") != null + || row.get("account_admission_fence", UUID.class) != null + || row.get("historical_account_admission_fence", UUID.class) != null + || row.get("coverage_fence", UUID.class) != null + || row.get("inventory_snapshot_revision") != null + || row.get("coverage_generation") != null) { + throw conflict("INITIAL source requires the complete SQL NO_ACTIVE account-control arm"); + } + BigInteger epoch = readBigInteger(row, "last_operation_fence"); + if (epoch.signum() < 0 || epoch.toString().length() > 256) { + throw conflict( + "INITIAL source requires a bounded nonnegative positive-row account-control epoch"); + } + return new AccountControlSource(accountId, NO_ACTIVE, epoch, digestControl(row)); + } + + private static String digestControl(Record row) { + Map fields = new LinkedHashMap<>(); + fields.put("accountId", row.get("account_id", UUID.class).toString()); + fields.put("state", row.get("state", String.class)); + fields.put("lastOperationFence", readBigInteger(row, "last_operation_fence").toString()); + fields.put("currentOperationId", uuidText(row, "current_operation_id")); + fields.put("currentFenceIntentId", uuidText(row, "current_fence_intent_id")); + fields.put("currentOperationFence", nullableInteger(row, "current_operation_fence")); + fields.put("accountAdmissionFence", uuidText(row, "account_admission_fence")); + fields.put("historicalAccountAdmissionFence", uuidText(row, "historical_account_admission_fence")); + fields.put("coverageFence", uuidText(row, "coverage_fence")); + fields.put("inventorySnapshotRevision", nullableInteger(row, "inventory_snapshot_revision")); + fields.put("coverageGeneration", nullableInteger(row, "coverage_generation")); + try { + return digest(net.firedevops.firemud.common.json.Rfc8785CanonicalJson.canonicalizeUtf8( + JSON.writeValueAsString(fields))); + } catch (Exception invalid) { + throw conflict("Account control source digest could not be computed"); + } + } + + private static String digestAccountEvidence(CanonicalGameplayLoginResult.NonSecretEvidence e) { + Map fields = new LinkedHashMap<>(); + fields.put("accountId", e.accountId().toString()); + fields.put("requestId", e.requestId().toString()); + fields.put("callerContextId", e.callerContextId().toString()); + fields.put("tokenJti", e.tokenJti().toString()); + fields.put("tokenSha256", e.tokenSha256()); + fields.put("tokenProfile", e.tokenProfile()); + fields.put("issuedAtEpochSecond", e.issuedAtEpochSecond()); + fields.put("notBeforeEpochSecond", e.notBeforeEpochSecond()); + fields.put("expiresAtEpochSecond", e.expiresAtEpochSecond()); + fields.put("tokenGeneration", e.tokenGeneration()); + fields.put("issuanceFence", e.issuanceFence()); + fields.put("authorityTupleCanonicalJson", e.authorityTupleCanonicalJson().toStringUtf8()); + fields.put("outboxCheckpointsCanonicalJson", e.outboxCheckpointsCanonicalJson().toStringUtf8()); + fields.put( + "outboxSourceEventEvidenceCanonicalJson", + e.outboxSourceEventEvidenceCanonicalJson().toStringUtf8()); + try { + return digest(net.firedevops.firemud.common.json.Rfc8785CanonicalJson.canonicalizeUtf8( + JSON.writeValueAsString(fields))); + } catch (Exception invalid) { + throw conflict("Authenticated Account response evidence digest could not be computed"); + } + } + + private static String digestTarget(InitializerSnapshot snapshot) { + Map fields = new LinkedHashMap<>(); + fields.put("initializerId", snapshot.initializerId().toString()); + fields.put("originalRequestId", snapshot.originalRequestId().toString()); + fields.put("originalCallerContextId", snapshot.originalCallerContextId().toString()); + fields.put("originalAttemptFence", snapshot.originalAttemptFence()); + fields.put("accountId", snapshot.accountId().toString()); + fields.put("tenantId", snapshot.tenantId().toString()); + fields.put("playableStateNamespaceId", snapshot.playableStateNamespaceId().toString()); + fields.put("accountLoginEvidenceDigest", snapshot.accountLoginEvidenceDigest()); + fields.put("sourceControlState", snapshot.sourceControlState()); + fields.put("sourceControlEpoch", snapshot.sourceControlEpoch().toString()); + fields.put("sourceControlDigest", snapshot.sourceControlDigest()); + fields.put("inventorySnapshotRevision", snapshot.inventorySnapshotRevision().toString()); + return digestUnchecked(fields); + } + + private static String digestFields(Map fields) { + return digestUnchecked(new java.util.TreeMap<>(fields)); + } + + private static String digestUnchecked(Object fields) { + try { + return digest(net.firedevops.firemud.common.json.Rfc8785CanonicalJson.canonicalizeUtf8( + JSON.writeValueAsString(fields))); + } catch (Exception invalid) { + throw conflict("Canonical INITIAL source digest could not be computed"); + } + } + + private static String digest(byte[] bytes) { + try { + return "sha256:" + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 is unavailable", impossible); + } + } + + private static String uuidText(Record row, String name) { + UUID value = row.get(name, UUID.class); + return value == null ? null : value.toString(); + } + + private static String nullableInteger(Record row, String name) { + BigDecimal value = row.get(name, BigDecimal.class); + return value == null ? null : value.toBigIntegerExact().toString(); + } + + private static Record readInitializer(DSLContext transaction, UUID requestId, boolean forUpdate) { + return transaction.fetchOne( + "SELECT i.initializer_id, i.original_request_id, i.original_caller_context_id," + + " i.original_attempt_fence, i.account_id, i.account_login_evidence_digest," + + " i.source_control_state, i.source_control_epoch, i.inventory_snapshot_revision," + + " i.source_control_digest, t.tenant_id, t.playable_state_namespace_id," + + " t.target_state, t.before_accepted_attestation_digest, t.before_incarnation_digest," + + " t.before_source_payload_digest, t.before_observation_issued_at_epoch_millis," + + " t.before_observation_observed_at_epoch_millis," + + " t.before_observation_expires_at_epoch_millis, t.installed_fields_digest" + + " FROM " + + INITIALIZER + + " i JOIN " + + TARGET + + " t ON t.initializer_id = i.initializer_id AND t.original_request_id = i.original_request_id" + + " WHERE i.original_request_id = ?" + + (forUpdate ? " FOR UPDATE OF i, t" : ""), + requestId); + } + + private static InitializerSnapshot readRequiredCurrent( + DSLContext transaction, UUID requestId, boolean forUpdate) { + Record row = readInitializer(transaction, requestId, forUpdate); + if (row == null) throw conflict("Exact original INITIAL account target is missing"); + return toSnapshot(row); + } + + private static InitializerSnapshot toSnapshot(Record row) { + UUID requestId = row.get("original_request_id", UUID.class); + UUID callerContextId = row.get("original_caller_context_id", UUID.class); + UUID accountId = row.get("account_id", UUID.class); + UUID tenantId = row.get("tenant_id", UUID.class); + UUID namespaceId = row.get("playable_state_namespace_id", UUID.class); + BigInteger controlEpoch = readBigInteger(row, "source_control_epoch"); + BigInteger inventoryRevision = readBigInteger(row, "inventory_snapshot_revision"); + State state; + try { + state = State.valueOf(row.get("target_state", String.class)); + } catch (RuntimeException malformed) { + throw conflict("Initial account barrier target state is malformed"); + } + InitializerSnapshot snapshot = + new InitializerSnapshot( + row.get("initializer_id", UUID.class), + requestId, + callerContextId, + row.get("original_attempt_fence", Long.class), + accountId, + tenantId, + namespaceId, + row.get("account_login_evidence_digest", String.class), + row.get("source_control_state", String.class), + controlEpoch, + inventoryRevision, + row.get("source_control_digest", String.class), + state, + row.get("before_accepted_attestation_digest", String.class), + row.get("before_incarnation_digest", String.class), + row.get("before_source_payload_digest", String.class), + nullableLong(row, "before_observation_issued_at_epoch_millis"), + nullableLong(row, "before_observation_observed_at_epoch_millis"), + nullableLong(row, "before_observation_expires_at_epoch_millis"), + row.get("installed_fields_digest", String.class)); + if (snapshot.initializerId() == null + || snapshot.originalRequestId() == null + || snapshot.originalCallerContextId() == null + || snapshot.originalAttemptFence() <= 0L + || snapshot.accountId() == null + || snapshot.tenantId() == null + || snapshot.playableStateNamespaceId() == null + || !NO_ACTIVE.equals(snapshot.sourceControlState()) + || controlEpoch.signum() < 0 + || controlEpoch.toString().length() > 256 + || inventoryRevision.signum() <= 0 + || !isDigest(snapshot.accountLoginEvidenceDigest()) + || !isDigest(snapshot.sourceControlDigest())) { + throw conflict("Persisted INITIAL account barrier identity or source is malformed"); + } + return snapshot.withTargetDigest(digestTarget(snapshot)); + } + + private static long nullableLong(Record row, String name) { + Long value = row.get(name, Long.class); + return value == null ? 0L : value; + } + + private static BigInteger readBigInteger(Record row, String name) { + BigDecimal value = row.get(name, BigDecimal.class); + if (value == null) throw conflict("Persisted INITIAL account field is missing: " + name); + try { + return value.toBigIntegerExact(); + } catch (ArithmeticException malformed) { + throw conflict("Persisted INITIAL account field is not integral: " + name); + } + } + + private static boolean positiveDecimal(String value) { + return value != null && value.matches("[1-9][0-9]{0,38}"); + } + + private static boolean isDigest(String value) { + return value != null && value.matches("sha256:[0-9a-f]{64}"); + } + + private static UUID randomNonNilUuid() { + UUID value = UUID.randomUUID(); + if (value.equals(new UUID(0L, 0L))) throw conflict("UUID source returned nil identity"); + return value; + } + + private static void requireNonNil(UUID value, String name) { + Objects.requireNonNull(value, name); + if (value.equals(new UUID(0L, 0L))) throw new IllegalArgumentException(name + " must not be nil"); + } + + private static void requireOne(int actual, String message) { + if (actual != 1) throw conflict(message); + } + + private static CanonicalGameplayBindingInventoryConflictException conflict(String message) { + return new CanonicalGameplayBindingInventoryConflictException(message); + } + + enum State { + NEVER_DISPATCHED, + DISPATCH_POSSIBLE, + OPEN_INSTALLED + } + + record InitialObservationContext( + UUID initializerId, + UUID originalRequestId, + UUID originalCallerContextId, + long originalAttemptFence, + UUID accountId, + UUID tenantId, + UUID playableStateNamespaceId, + String sourceControlState, + BigInteger sourceControlEpoch, + BigInteger inventorySnapshotRevision, + String accountLoginEvidenceDigest, + String sourceControlDigest, + String targetDigest) { + private static InitialObservationContext from(InitializerSnapshot snapshot) { + return new InitialObservationContext( + snapshot.initializerId(), + snapshot.originalRequestId(), + snapshot.originalCallerContextId(), + snapshot.originalAttemptFence(), + snapshot.accountId(), + snapshot.tenantId(), + snapshot.playableStateNamespaceId(), + snapshot.sourceControlState(), + snapshot.sourceControlEpoch(), + snapshot.inventorySnapshotRevision(), + snapshot.accountLoginEvidenceDigest(), + snapshot.sourceControlDigest(), + snapshot.targetDigest()); + } + } + + record InitializerSnapshot( + UUID initializerId, + UUID originalRequestId, + UUID originalCallerContextId, + long originalAttemptFence, + UUID accountId, + UUID tenantId, + UUID playableStateNamespaceId, + String accountLoginEvidenceDigest, + String sourceControlState, + BigInteger sourceControlEpoch, + BigInteger inventorySnapshotRevision, + String sourceControlDigest, + State state, + String beforeAcceptedAttestationDigest, + String beforeIncarnationDigest, + String beforeSourcePayloadDigest, + long beforeIssuedAtEpochMillis, + long beforeObservedAtEpochMillis, + long beforeExpiresAtEpochMillis, + String installedFieldsDigest, + String targetDigest) { + private InitializerSnapshot( + UUID initializerId, + UUID originalRequestId, + UUID originalCallerContextId, + long originalAttemptFence, + UUID accountId, + UUID tenantId, + UUID playableStateNamespaceId, + String accountLoginEvidenceDigest, + String sourceControlState, + BigInteger sourceControlEpoch, + BigInteger inventorySnapshotRevision, + String sourceControlDigest, + State state, + String beforeAcceptedAttestationDigest, + String beforeIncarnationDigest, + String beforeSourcePayloadDigest, + long beforeIssuedAtEpochMillis, + long beforeObservedAtEpochMillis, + long beforeExpiresAtEpochMillis, + String installedFieldsDigest) { + this( + initializerId, + originalRequestId, + originalCallerContextId, + originalAttemptFence, + accountId, + tenantId, + playableStateNamespaceId, + accountLoginEvidenceDigest, + sourceControlState, + sourceControlEpoch, + inventorySnapshotRevision, + sourceControlDigest, + state, + beforeAcceptedAttestationDigest, + beforeIncarnationDigest, + beforeSourcePayloadDigest, + beforeIssuedAtEpochMillis, + beforeObservedAtEpochMillis, + beforeExpiresAtEpochMillis, + installedFieldsDigest, + null); + } + + InitializerSnapshot withTargetDigest(String value) { + return new InitializerSnapshot( + initializerId, + originalRequestId, + originalCallerContextId, + originalAttemptFence, + accountId, + tenantId, + playableStateNamespaceId, + accountLoginEvidenceDigest, + sourceControlState, + sourceControlEpoch, + inventorySnapshotRevision, + sourceControlDigest, + state, + beforeAcceptedAttestationDigest, + beforeIncarnationDigest, + beforeSourcePayloadDigest, + beforeIssuedAtEpochMillis, + beforeObservedAtEpochMillis, + beforeExpiresAtEpochMillis, + installedFieldsDigest, + value); + } + } + + private record AccountControlSource( + UUID accountId, String state, BigInteger epoch, String digest) {} +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierKey.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierKey.java new file mode 100644 index 0000000000..46a0014dfc --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierKey.java @@ -0,0 +1,18 @@ +package net.firedevops.firemud.gamesession.repository; + +import java.util.Objects; +import java.util.UUID; + +/** Key for the original-attempt INITIAL OPEN operation on one tenant gameplay slot. */ +final class CanonicalGameplayAccountInitialBarrierKey { + private CanonicalGameplayAccountInitialBarrierKey() {} + + static String forTarget( + CanonicalGameplayTenantGameplayTagRepository.Assignment assignment, + UUID initializerId, + UUID originalRequestId) { + Objects.requireNonNull(assignment, "persisted initial target assignment"); + return CanonicalGameplaySessionRedisKeys.initialAccountAdmissionBarrier( + assignment, initializerId, originalRequestId); + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierRedisOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierRedisOwner.java new file mode 100644 index 0000000000..ede8711830 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierRedisOwner.java @@ -0,0 +1,564 @@ +package net.firedevops.firemud.gamesession.repository; + +import io.lettuce.core.RedisFuture; +import io.lettuce.core.ScriptOutputType; +import io.lettuce.core.api.StatefulRedisConnection; +import io.lettuce.core.api.async.RedisAsyncCommands; +import io.lettuce.core.codec.ByteArrayCodec; +import java.io.IOException; +import java.io.InputStream; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.util.HashMap; +import java.util.HexFormat; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor; +import net.firedevops.firemud.gamesession.dto.CanonicalGameplayLoginResult; +import net.firedevops.firemud.gamesession.dto.InitialGameplayLoginAttemptCoordinates; +import net.firedevops.firemud.gamesession.service.CanonicalGameplayAccountInitialBarrierRedisScriptContribution; + +/** Explicit manual owner for a create-once INITIAL OPEN barrier and exact current readback. */ +final class CanonicalGameplayAccountInitialBarrierRedisOwner { + private static final String PRINCIPAL = "gamesession_coord_app"; + private static final String KEY_PREFIX = "session:game:account-admission:"; + private static final int MAX_SCRIPT_BYTES = 32 * 1024; + private static final long COMMAND_TIMEOUT_MILLIS = 5_000; + private static final List FIELDS = + List.of( + "schema", + "accountId", + "tenantId", + "playableStateNamespaceId", + "tenantGameplayTag", + "ownerOperationId", + "ownerFenceEpoch", + "incarnationDigest", + "state"); + private static final List SCRIPT_ARGUMENTS = + List.of( + new RedisScriptDescriptor.ArgumentSpec("schema"), + new RedisScriptDescriptor.ArgumentSpec("accountId"), + new RedisScriptDescriptor.ArgumentSpec("tenantId"), + new RedisScriptDescriptor.ArgumentSpec("playableStateNamespaceId"), + new RedisScriptDescriptor.ArgumentSpec("tenantGameplayTag"), + new RedisScriptDescriptor.ArgumentSpec("initializerId"), + new RedisScriptDescriptor.ArgumentSpec("ownerFenceEpoch"), + new RedisScriptDescriptor.ArgumentSpec("incarnationDigest"), + new RedisScriptDescriptor.ArgumentSpec("state")); + private static final List SCRIPT_OUTCOMES = + List.of( + outcome( + "OPEN_CREATED", + RedisScriptDescriptor.OutcomeCategory.SUCCESS, + RedisScriptDescriptor.MutationEffect.MUTATING), + outcome( + "TARGET_ALREADY_PRESENT", + RedisScriptDescriptor.OutcomeCategory.STALE, + RedisScriptDescriptor.MutationEffect.NON_MUTATING), + outcome( + "TYPE_TTL_OR_FIELDS_REFUSED", + RedisScriptDescriptor.OutcomeCategory.VALIDATION_FAILURE, + RedisScriptDescriptor.MutationEffect.NON_MUTATING), + outcome( + "INVALID_ARGUMENTS", + RedisScriptDescriptor.OutcomeCategory.VALIDATION_FAILURE, + RedisScriptDescriptor.MutationEffect.NON_MUTATING)); + + private final io.lettuce.core.RedisClient redisClient; + private final RedisScriptCatalog catalog; + private final CanonicalGameplayAccountInitialBarrierInitializerRepository repository; + private final CanonicalGameplayTenantGameplayTagRepository tenantTags; + private final CanonicalGameplayProtectedIncarnationReceiver incarnationReceiver; + + CanonicalGameplayAccountInitialBarrierRedisOwner( + io.lettuce.core.RedisClient redisClient, + RedisScriptCatalog catalog, + CanonicalGameplayAccountInitialBarrierInitializerRepository repository, + CanonicalGameplayTenantGameplayTagRepository tenantTags, + CanonicalGameplayProtectedIncarnationReceiver incarnationReceiver) { + this.redisClient = Objects.requireNonNull(redisClient, "Configured Redis client is required"); + this.catalog = Objects.requireNonNull(catalog, "Manual Redis script catalog is required"); + this.repository = Objects.requireNonNull(repository, "Exact SQL initializer is required"); + this.tenantTags = Objects.requireNonNull(tenantTags, "Persisted target resolver is required"); + this.incarnationReceiver = + Objects.requireNonNull(incarnationReceiver, "Protected observation verifier is required"); + } + + /** + * Starts one original-attempt target or performs read-only same-original verification. The SQL + * DISPATCH_POSSIBLE state commits before the only Redis write call; every later path is read-only. + */ + CanonicalGameplayAccountInitialOpenProof initializeOnce( + InitialGameplayLoginAttemptCoordinates original, + CanonicalGameplayLoginResult accountLogin, + UUID tenantId, + UUID playableStateNamespaceId) { + Objects.requireNonNull(original, "original attempt"); + Objects.requireNonNull(accountLogin, "authenticated Account LOGIN result"); + CanonicalGameplayAccountInitialBarrierInitializerRepository.InitializerSnapshot snapshot; + try { + requireNoAmbientTransaction(); + snapshot = repository.beginOrRead(original, accountLogin, tenantId, playableStateNamespaceId); + } catch (RuntimeException unavailable) { + return refused(CanonicalGameplayAccountInitialOpenProof.Reason.SOURCE_CONTROL_UNAVAILABLE); + } + if (snapshot.state() + != CanonicalGameplayAccountInitialBarrierInitializerRepository.State.NEVER_DISPATCHED) { + return verifyCurrentOpen(snapshot.originalRequestId()); + } + + try { + CanonicalGameplayTenantGameplayTagRepository.Assignment assignment = + requireInitialAssignment(snapshot.originalRequestId(), snapshot); + CanonicalGameplayProtectedIncarnationReceiver.VerifiedIncarnation before = + incarnationReceiver.observeForInitialAccountBarrier(snapshot.originalRequestId()); + requireObservation(snapshot, before); + repository.recordDispatchPossible(snapshot.originalRequestId(), before); + // The state transition above is durable before this one and only possible remote attempt. + tryCreateOnce(snapshot, assignment, before); + } catch (RuntimeException possibleDispatchOrSourceFailure) { + // Never create a replacement initializer or repeat a possibly dispatched write. A positive + // exact readback can still finish the original receipt; absence remains explicit uncertainty. + } + return verifyCurrentOpen(snapshot.originalRequestId()); + } + + /** Typed read-only current-OPEN proof or refusal; it cannot authorize final admission. */ + CanonicalGameplayAccountInitialOpenProof verifyCurrentOpen(UUID originalRequestId) { + if (originalRequestId == null) { + return refused(CanonicalGameplayAccountInitialOpenProof.Reason.ORIGINAL_ATTEMPT_MISMATCH); + } + CanonicalGameplayAccountInitialBarrierInitializerRepository.InitializerSnapshot snapshot; + try { + requireNoAmbientTransaction(); + snapshot = repository.readCurrent(originalRequestId); + } catch (RuntimeException unavailable) { + return refused(CanonicalGameplayAccountInitialOpenProof.Reason.SOURCE_CONTROL_UNAVAILABLE); + } + if (snapshot.state() + == CanonicalGameplayAccountInitialBarrierInitializerRepository.State.NEVER_DISPATCHED) { + return refused(CanonicalGameplayAccountInitialOpenProof.Reason.TARGET_NEVER_DISPATCHED); + } + if (snapshot.state() + == CanonicalGameplayAccountInitialBarrierInitializerRepository.State.DISPATCH_POSSIBLE + && snapshot.beforeIncarnationDigest() == null) { + return refused(CanonicalGameplayAccountInitialOpenProof.Reason.REMOTE_OUTCOME_UNCERTAIN); + } + + try { + CanonicalGameplayTenantGameplayTagRepository.Assignment assignment = + requireInitialAssignment(originalRequestId, snapshot); + CanonicalGameplayProtectedIncarnationReceiver.VerifiedIncarnation before = + incarnationReceiver.observeForInitialAccountBarrier(originalRequestId); + requireObservation(snapshot, before); + if (!before.incarnationDigest().equals(snapshot.beforeIncarnationDigest()) + || !before.acceptedAttestationDigest().equals(snapshot.beforeAcceptedAttestationDigest())) { + return refused(CanonicalGameplayAccountInitialOpenProof.Reason.PROTECTED_OBSERVATION_UNAVAILABLE); + } + CanonicalGameplayAccountInitialBarrierValue value = + CanonicalGameplayAccountInitialBarrierValue.open( + snapshot.accountId(), + snapshot.tenantId(), + snapshot.playableStateNamespaceId(), + assignment.tenantGameplayTag(), + snapshot.initializerId(), + snapshot.sourceControlEpoch(), + snapshot.beforeIncarnationDigest()); + String key = + CanonicalGameplayAccountInitialBarrierKey.forTarget( + assignment, snapshot.initializerId(), originalRequestId); + Map physical = readExactPhysicalState(key, value); + CanonicalGameplayProtectedIncarnationReceiver.VerifiedIncarnation after = + incarnationReceiver.observeForInitialAccountBarrier(originalRequestId); + requireObservation(snapshot, after); + if (!before.incarnationDigest().equals(after.incarnationDigest()) + || !before.acceptedAttestationDigest().equals(after.acceptedAttestationDigest()) + || after.issuedAtEpochMillis() < before.issuedAtEpochMillis() + || after.observedAtEpochMillis() < before.observedAtEpochMillis()) { + return refused(CanonicalGameplayAccountInitialOpenProof.Reason.PROTECTED_OBSERVATION_UNAVAILABLE); + } + + Readback readback = + new Readback( + snapshot, + assignment, + key, + value, + physical, + before, + after, + 0L); + if (snapshot.state() + == CanonicalGameplayAccountInitialBarrierInitializerRepository.State.OPEN_INSTALLED) { + var current = repository.readCurrent(originalRequestId); + if (current.state() + != CanonicalGameplayAccountInitialBarrierInitializerRepository.State.OPEN_INSTALLED) { + return refused(CanonicalGameplayAccountInitialOpenProof.Reason.CURRENT_CONTROL_CHANGED); + } + return currentProof(current, key, value.fields(), after); + } + var accepted = repository.acceptOpenReadback(originalRequestId, readback); + if (accepted.state() + != CanonicalGameplayAccountInitialBarrierInitializerRepository.State.OPEN_INSTALLED) { + return refused(CanonicalGameplayAccountInitialOpenProof.Reason.REMOTE_OUTCOME_UNCERTAIN); + } + return currentProof(accepted, key, value.fields(), after); + } catch (RuntimeException unavailable) { + return refused(classifyRefusal(snapshot)); + } + } + + private void tryCreateOnce( + CanonicalGameplayAccountInitialBarrierInitializerRepository.InitializerSnapshot snapshot, + CanonicalGameplayTenantGameplayTagRepository.Assignment assignment, + CanonicalGameplayProtectedIncarnationReceiver.VerifiedIncarnation before) { + requireNoAmbientTransaction(); + RedisScriptDescriptor descriptor = requireDescriptor(); + byte[] script = scriptSource(descriptor); + CanonicalGameplayAccountInitialBarrierValue value = + CanonicalGameplayAccountInitialBarrierValue.open( + snapshot.accountId(), + snapshot.tenantId(), + snapshot.playableStateNamespaceId(), + assignment.tenantGameplayTag(), + snapshot.initializerId(), + snapshot.sourceControlEpoch(), + before.incarnationDigest()); + String key = + CanonicalGameplayAccountInitialBarrierKey.forTarget( + assignment, snapshot.initializerId(), snapshot.originalRequestId()); + long outcome = + writeOneKey( + script, + key, + ascii(CanonicalGameplayAccountInitialBarrierValue.SCHEMA), + ascii(snapshot.accountId().toString()), + ascii(snapshot.tenantId().toString()), + ascii(snapshot.playableStateNamespaceId().toString()), + ascii(assignment.tenantGameplayTag()), + ascii(snapshot.initializerId().toString()), + ascii(snapshot.sourceControlEpoch().toString()), + ascii(before.incarnationDigest()), + ascii(CanonicalGameplayAccountInitialBarrierValue.OPEN)); + if (outcome < 0 || outcome > 1) throw unavailable(); + } + + private CanonicalGameplayTenantGameplayTagRepository.Assignment requireInitialAssignment( + UUID originalRequestId, + CanonicalGameplayAccountInitialBarrierInitializerRepository.InitializerSnapshot snapshot) { + CanonicalGameplayTenantGameplayTagRepository.Assignment assignment = + tenantTags.assignmentForInitialBarrierTarget(originalRequestId); + if (!assignment.isInitialBarrierTarget() + || !snapshot.initializerId().equals(assignment.initialBarrierInitializerId()) + || !snapshot.originalRequestId().equals(assignment.initialBarrierOriginalRequestId()) + || !snapshot.accountId().equals(assignment.accountId()) + || !snapshot.tenantId().equals(assignment.tenantId()) + || !snapshot.playableStateNamespaceId().equals(assignment.playableStateNamespaceId())) { + throw unavailable(); + } + return assignment; + } + + private static void requireObservation( + CanonicalGameplayAccountInitialBarrierInitializerRepository.InitializerSnapshot snapshot, + CanonicalGameplayProtectedIncarnationReceiver.VerifiedIncarnation observation) { + if (observation.ownerKind() + != CanonicalGameplayProtectedIncarnationReceiver.OwnerKind.INITIAL_ACCOUNT_BARRIER + || !snapshot.initializerId().equals(observation.operationId()) + || !snapshot.originalRequestId().equals(observation.requestId()) + || !snapshot.originalCallerContextId().equals(observation.originalCallerContextId()) + || snapshot.originalAttemptFence() != observation.originalAttemptFence() + || !snapshot.accountId().equals(observation.accountId()) + || !snapshot.tenantId().equals(observation.tenantId()) + || !snapshot.playableStateNamespaceId().equals(observation.playableStateNamespaceId()) + || !"NO_ACTIVE_ACCOUNT_WIDE_FLOW".equals(observation.sourceControlState()) + || !snapshot.sourceControlEpoch().toString().equals(observation.sourceControlEpoch()) + || !snapshot.inventorySnapshotRevision().toString() + .equals(observation.inventorySnapshotRevision()) + || !snapshot.accountLoginEvidenceDigest().equals(observation.accountLoginEvidenceDigest()) + || !snapshot.sourceControlDigest().equals(observation.sourceControlDigest()) + || !snapshot.targetDigest().equals(observation.barrierTargetDigest())) { + throw unavailable(); + } + } + + private Map readExactPhysicalState( + String key, CanonicalGameplayAccountInitialBarrierValue expected) { + requireNoAmbientTransaction(); + byte[] keyBytes = ascii(key); + try (StatefulRedisConnection connection = + redisClient.connect(ByteArrayCodec.INSTANCE)) { + RedisAsyncCommands commands = requireCommands(connection); + requirePrincipal(await(commands.aclWhoami())); + if (!"hash".equals(await(commands.type(keyBytes))) + || !Long.valueOf(-1L).equals(await(commands.pttl(keyBytes)))) throw unavailable(); + Long length = await(commands.hlen(keyBytes)); + if (length == null || length != FIELDS.size()) throw unavailable(); + Map raw = await(commands.hgetall(keyBytes)); + if (raw == null || raw.size() != FIELDS.size()) throw unavailable(); + Map actual = new HashMap<>(); + for (Map.Entry entry : raw.entrySet()) { + String field = asciiString(entry.getKey()); + String value = asciiString(Objects.requireNonNull(entry.getValue())); + if (!FIELDS.contains(field) || actual.putIfAbsent(field, value) != null) throw unavailable(); + } + if (!expected.fields().equals(actual)) throw unavailable(); + return Map.copyOf(actual); + } catch (RuntimeException failure) { + throw unavailable(failure); + } + } + + private long writeOneKey(byte[] script, String key, byte[]... arguments) { + requireNoAmbientTransaction(); + try (StatefulRedisConnection connection = + redisClient.connect(ByteArrayCodec.INSTANCE)) { + RedisAsyncCommands commands = requireCommands(connection); + requirePrincipal(await(commands.aclWhoami())); + String sha = await(commands.scriptLoad(script)); + if (!digest("SHA-1", script).equals(sha)) throw unavailable(); + Long reply = + await(commands.evalsha(sha, ScriptOutputType.INTEGER, new byte[][] {ascii(key)}, arguments)); + if (reply == null) throw unavailable(); + return reply; + } catch (RuntimeException failure) { + throw unavailable(failure); + } + } + + private RedisScriptDescriptor requireDescriptor() { + String scriptId = CanonicalGameplayAccountInitialBarrierRedisScriptContribution.SCRIPT_ID; + String resourcePath = + CanonicalGameplayAccountInitialBarrierRedisScriptContribution.RESOURCE_PATH; + try { + RedisScriptDescriptor descriptor = catalog.require(scriptId); + if (!scriptId.equals(descriptor.scriptId()) + || !resourcePath.equals(descriptor.resourcePath()) + || !"game-session-service".equals(descriptor.owner()) + || !PRINCIPAL.equals(descriptor.principal()) + || descriptor.role() != RedisScriptDescriptor.RedisRole.COORDINATION + || !List.of( + new RedisScriptDescriptor.KeySpec( + "accountAdmissionBarrier", + KEY_PREFIX, + RedisScriptDescriptor.HashTagDeclaration.REQUIRED)) + .equals(descriptor.keys()) + || !SCRIPT_ARGUMENTS.equals(descriptor.arguments()) + || descriptor.category() != RedisScriptDescriptor.ScriptCategory.SESSION_CAS + || !SCRIPT_OUTCOMES.equals(descriptor.outcomes()) + || descriptor.resetSensitivity() != RedisScriptDescriptor.ResetSensitivity.CLUSTER + || descriptor.lossClass() + != RedisScriptDescriptor.LossClass.EMPTY_REDIS_COLD_START_OR_RESET + || descriptor.compatibilityLevel() + != RedisScriptDescriptor.CompatibilityLevel.REQUIRES_CLUSTER_RESET + || !descriptor + .supportedCoexistence() + .equals(List.of(new RedisScriptDescriptor.SupportedCoexistence("v1", "none"))) + || descriptor.legacyPayloadShape() != null) throw unavailable(); + return descriptor; + } catch (RuntimeException failure) { + throw unavailable(failure); + } + } + + private static byte[] scriptSource(RedisScriptDescriptor descriptor) { + try (InputStream input = + CanonicalGameplayAccountInitialBarrierRedisOwner.class + .getClassLoader() + .getResourceAsStream(descriptor.resourcePath())) { + if (input == null) throw unavailable(); + byte[] bytes = input.readNBytes(MAX_SCRIPT_BYTES + 1); + if (bytes.length == 0 + || bytes.length > MAX_SCRIPT_BYTES + || !descriptor.sha256().equals(digest("SHA-256", bytes))) throw unavailable(); + return bytes; + } catch (IOException | RuntimeException failure) { + throw unavailable(failure); + } + } + + private static CanonicalGameplayAccountInitialOpenProof currentProof( + CanonicalGameplayAccountInitialBarrierInitializerRepository.InitializerSnapshot snapshot, + String key, + Map fields, + CanonicalGameplayProtectedIncarnationReceiver.VerifiedIncarnation currentObservation) { + return new CanonicalGameplayAccountInitialOpenProof.CurrentOpen( + snapshot.initializerId(), + snapshot.originalRequestId(), + snapshot.originalCallerContextId(), + snapshot.originalAttemptFence(), + snapshot.accountId(), + snapshot.tenantId(), + snapshot.playableStateNamespaceId(), + key, + snapshot.sourceControlEpoch(), + snapshot.inventorySnapshotRevision(), + snapshot.accountLoginEvidenceDigest(), + snapshot.sourceControlDigest(), + snapshot.beforeIncarnationDigest(), + currentObservation.issuedAtEpochMillis(), + currentObservation.expiresAtEpochMillis(), + fields); + } + + private static CanonicalGameplayAccountInitialOpenProof refused( + CanonicalGameplayAccountInitialOpenProof.Reason reason) { + return new CanonicalGameplayAccountInitialOpenProof.Refused(reason); + } + + private static CanonicalGameplayAccountInitialOpenProof.Reason classifyRefusal( + CanonicalGameplayAccountInitialBarrierInitializerRepository.InitializerSnapshot snapshot) { + return snapshot.state() + == CanonicalGameplayAccountInitialBarrierInitializerRepository.State.DISPATCH_POSSIBLE + ? CanonicalGameplayAccountInitialOpenProof.Reason.REMOTE_OUTCOME_UNCERTAIN + : CanonicalGameplayAccountInitialOpenProof.Reason.PHYSICAL_VALUE_MISSING_OR_CONFLICTING; + } + + private static RedisAsyncCommands requireCommands( + StatefulRedisConnection connection) { + if (connection == null || !connection.isOpen()) throw unavailable(); + RedisAsyncCommands commands = connection.async(); + if (commands == null) throw unavailable(); + return commands; + } + + private static void requirePrincipal(String principal) { + if (!PRINCIPAL.equals(principal)) throw unavailable(); + } + + private static byte[] ascii(String value) { + Objects.requireNonNull(value, "ASCII value"); + for (int index = 0; index < value.length(); index++) { + if (value.charAt(index) > 0x7f) throw unavailable(); + } + return value.getBytes(StandardCharsets.US_ASCII); + } + + private static String asciiString(byte[] value) { + Objects.requireNonNull(value, "Redis field"); + for (byte character : value) if ((character & 0x80) != 0) throw unavailable(); + return new String(value, StandardCharsets.US_ASCII); + } + + private static String digest(String algorithm, byte[] bytes) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance(algorithm).digest(bytes)); + } catch (Exception failure) { + throw unavailable(failure); + } + } + + private static T await(RedisFuture future) { + if (future == null) throw unavailable(); + try { + return future.get(COMMAND_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw unavailable(interrupted); + } catch (ExecutionException | TimeoutException failure) { + throw unavailable(failure); + } + } + + private void requireNoAmbientTransaction() { + repository.requireNoAmbientTransaction(); + } + + private static RedisScriptDescriptor.OutcomeSpec outcome( + String code, + RedisScriptDescriptor.OutcomeCategory category, + RedisScriptDescriptor.MutationEffect effect) { + return new RedisScriptDescriptor.OutcomeSpec(code, category, effect); + } + + private static IllegalStateException unavailable() { + return new IllegalStateException("INITIAL account barrier is unavailable"); + } + + private static IllegalStateException unavailable(Throwable cause) { + return new IllegalStateException("INITIAL account barrier is unavailable", cause); + } + + record Readback( + UUID initializerId, + UUID originalRequestId, + UUID accountId, + UUID tenantId, + UUID playableStateNamespaceId, + String accountLoginEvidenceDigest, + String sourceControlDigest, + BigInteger inventorySnapshotRevision, + String key, + CanonicalGameplayTenantGameplayTagRepository.Assignment assignment, + CanonicalGameplayAccountInitialBarrierValue value, + Map barrierFields, + CanonicalGameplayProtectedIncarnationReceiver.VerifiedIncarnation beforeIncarnation, + CanonicalGameplayProtectedIncarnationReceiver.VerifiedIncarnation afterIncarnation, + long scriptOutcome) { + Readback( + CanonicalGameplayAccountInitialBarrierInitializerRepository.InitializerSnapshot snapshot, + CanonicalGameplayTenantGameplayTagRepository.Assignment assignment, + String key, + CanonicalGameplayAccountInitialBarrierValue value, + Map barrierFields, + CanonicalGameplayProtectedIncarnationReceiver.VerifiedIncarnation beforeIncarnation, + CanonicalGameplayProtectedIncarnationReceiver.VerifiedIncarnation afterIncarnation, + long scriptOutcome) { + this( + snapshot.initializerId(), + snapshot.originalRequestId(), + snapshot.accountId(), + snapshot.tenantId(), + snapshot.playableStateNamespaceId(), + snapshot.accountLoginEvidenceDigest(), + snapshot.sourceControlDigest(), + snapshot.inventorySnapshotRevision(), + key, + assignment, + value, + barrierFields, + beforeIncarnation, + afterIncarnation, + scriptOutcome); + } + + Readback { + Objects.requireNonNull(initializerId, "initializerId"); + Objects.requireNonNull(originalRequestId, "originalRequestId"); + Objects.requireNonNull(accountId, "accountId"); + Objects.requireNonNull(tenantId, "tenantId"); + Objects.requireNonNull(playableStateNamespaceId, "playableStateNamespaceId"); + Objects.requireNonNull(accountLoginEvidenceDigest, "accountLoginEvidenceDigest"); + Objects.requireNonNull(sourceControlDigest, "sourceControlDigest"); + Objects.requireNonNull(inventorySnapshotRevision, "inventorySnapshotRevision"); + Objects.requireNonNull(key, "key"); + Objects.requireNonNull(assignment, "assignment"); + Objects.requireNonNull(value, "value"); + barrierFields = Map.copyOf(Objects.requireNonNull(barrierFields, "barrierFields")); + Objects.requireNonNull(beforeIncarnation, "beforeIncarnation"); + Objects.requireNonNull(afterIncarnation, "afterIncarnation"); + if (scriptOutcome < 0 + || scriptOutcome > 1 + || !CanonicalGameplayAccountInitialBarrierValue.FIELDS.equals(barrierFields.keySet()) + || !value.fields().equals(barrierFields) + || !CanonicalGameplayAccountInitialBarrierKey.forTarget( + assignment, initializerId, originalRequestId) + .equals(key) + || !initializerId.equals(assignment.initialBarrierInitializerId()) + || !originalRequestId.equals(assignment.initialBarrierOriginalRequestId()) + || !accountId.equals(assignment.accountId()) + || !tenantId.equals(assignment.tenantId()) + || !playableStateNamespaceId.equals(assignment.playableStateNamespaceId())) { + throw unavailable(); + } + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierValue.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierValue.java new file mode 100644 index 0000000000..67ecd3714a --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierValue.java @@ -0,0 +1,79 @@ +package net.firedevops.firemud.gamesession.repository; + +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.math.BigInteger; +import java.util.UUID; + +/** Exact nine-field physical INITIAL OPEN value; it carries no later Account or issuer authority. */ +final class CanonicalGameplayAccountInitialBarrierValue { + static final String SCHEMA = "gs_account_admission_barrier/v1"; + static final String OPEN = "OPEN"; + static final Set FIELDS = + Set.of( + "schema", + "accountId", + "tenantId", + "playableStateNamespaceId", + "tenantGameplayTag", + "ownerOperationId", + "ownerFenceEpoch", + "incarnationDigest", + "state"); + + private final Map fields; + + private CanonicalGameplayAccountInitialBarrierValue(Map fields) { + if (!FIELDS.equals(fields.keySet())) { + throw new IllegalArgumentException("INITIAL barrier fields are not exact"); + } + this.fields = Map.copyOf(fields); + } + + static CanonicalGameplayAccountInitialBarrierValue open( + UUID accountId, + UUID tenantId, + UUID namespaceId, + String tenantGameplayTag, + UUID initializerId, + BigInteger ownerFenceEpoch, + String incarnationDigest) { + requireNonNil(accountId, "account id"); + requireNonNil(tenantId, "tenant id"); + requireNonNil(namespaceId, "namespace id"); + requireNonNil(initializerId, "initializer id"); + if (tenantGameplayTag == null + || !tenantGameplayTag.matches("g[1-9][0-9]{0,9}-[0-9a-f]{32}") + || ownerFenceEpoch == null + || ownerFenceEpoch.signum() < 0 + || ownerFenceEpoch.toString().length() > 256 + || incarnationDigest == null + || !incarnationDigest.matches("sha256:[0-9a-f]{64}")) { + throw new IllegalArgumentException("INITIAL barrier target or incarnation is invalid"); + } + Map fields = new LinkedHashMap<>(); + fields.put("schema", SCHEMA); + fields.put("accountId", accountId.toString()); + fields.put("tenantId", tenantId.toString()); + fields.put("playableStateNamespaceId", namespaceId.toString()); + fields.put("tenantGameplayTag", tenantGameplayTag); + fields.put("ownerOperationId", initializerId.toString()); + fields.put("ownerFenceEpoch", ownerFenceEpoch.toString()); + fields.put("incarnationDigest", incarnationDigest); + fields.put("state", OPEN); + return new CanonicalGameplayAccountInitialBarrierValue(fields); + } + + Map fields() { + return fields; + } + + private static void requireNonNil(UUID value, String name) { + Objects.requireNonNull(value, name); + if (value.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException(name + " must not be nil"); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialOpenProof.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialOpenProof.java new file mode 100644 index 0000000000..3a7f270eeb --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialOpenProof.java @@ -0,0 +1,85 @@ +package net.firedevops.firemud.gamesession.repository; + +import java.math.BigInteger; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; + +/** Owner-issued current OPEN proof, or a typed refusal that cannot be used as admission evidence. */ +sealed interface CanonicalGameplayAccountInitialOpenProof + permits CanonicalGameplayAccountInitialOpenProof.CurrentOpen, + CanonicalGameplayAccountInitialOpenProof.Refused { + record CurrentOpen( + UUID initializerId, + UUID originalRequestId, + UUID originalCallerContextId, + long originalAttemptFence, + UUID accountId, + UUID tenantId, + UUID playableStateNamespaceId, + String key, + BigInteger sourceControlEpoch, + BigInteger inventorySnapshotRevision, + String accountLoginEvidenceDigest, + String sourceControlDigest, + String incarnationDigest, + long issuedAtEpochMillis, + long expiresAtEpochMillis, + Map exactFields) + implements CanonicalGameplayAccountInitialOpenProof { + CurrentOpen { + Objects.requireNonNull(initializerId, "initializerId"); + Objects.requireNonNull(originalRequestId, "originalRequestId"); + Objects.requireNonNull(originalCallerContextId, "originalCallerContextId"); + Objects.requireNonNull(accountId, "accountId"); + Objects.requireNonNull(tenantId, "tenantId"); + Objects.requireNonNull(playableStateNamespaceId, "playableStateNamespaceId"); + Objects.requireNonNull(key, "key"); + Objects.requireNonNull(sourceControlEpoch, "sourceControlEpoch"); + Objects.requireNonNull(inventorySnapshotRevision, "inventorySnapshotRevision"); + requireDigest(accountLoginEvidenceDigest, "accountLoginEvidenceDigest"); + requireDigest(sourceControlDigest, "sourceControlDigest"); + requireDigest(incarnationDigest, "incarnationDigest"); + exactFields = Map.copyOf(Objects.requireNonNull(exactFields, "exactFields")); + if (originalAttemptFence <= 0L + || sourceControlEpoch.signum() < 0 + || sourceControlEpoch.toString().length() > 256 + || inventorySnapshotRevision.signum() <= 0 + || issuedAtEpochMillis <= 0 + || expiresAtEpochMillis <= issuedAtEpochMillis + || !CanonicalGameplayAccountInitialBarrierValue.FIELDS.equals(exactFields.keySet()) + || !"OPEN".equals(exactFields.get("state")) + || !sourceControlEpoch.toString().equals(exactFields.get("ownerFenceEpoch")) + || !initializerId.toString().equals(exactFields.get("ownerOperationId")) + || !accountId.toString().equals(exactFields.get("accountId")) + || !tenantId.toString().equals(exactFields.get("tenantId")) + || !playableStateNamespaceId.toString() + .equals(exactFields.get("playableStateNamespaceId")) + || !incarnationDigest.equals(exactFields.get("incarnationDigest"))) { + throw new IllegalArgumentException("Current INITIAL OPEN proof is malformed"); + } + } + } + + record Refused(Reason reason) implements CanonicalGameplayAccountInitialOpenProof { + Refused { + Objects.requireNonNull(reason, "reason"); + } + } + + enum Reason { + ORIGINAL_ATTEMPT_MISMATCH, + SOURCE_CONTROL_UNAVAILABLE, + TARGET_NEVER_DISPATCHED, + REMOTE_OUTCOME_UNCERTAIN, + PHYSICAL_VALUE_MISSING_OR_CONFLICTING, + PROTECTED_OBSERVATION_UNAVAILABLE, + CURRENT_CONTROL_CHANGED + } + + private static void requireDigest(String value, String name) { + if (value == null || !value.matches("sha256:[0-9a-f]{64}")) { + throw new IllegalArgumentException(name + " must be canonical SHA-256"); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepository.java index cfcefb1751..f762ffb42d 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepository.java @@ -105,6 +105,8 @@ CanonicalGameplayBindingTransitionSnapshot prepareAfterInstalledIssuerAnchor( CanonicalGameplayIssuerBootstrapCoverageRepository .readInstalledAnchorForBindingPreparationInTransaction( transaction, currentIssuerState); + CanonicalGameplayIssuerAdmissionControlRepository.requireOpenInTransaction( + transaction, actualAnchor, currentIssuerState); InstalledAnchorPreparationContext context = new InstalledAnchorPreparationContext(revision, actualAnchor, currentIssuerState); CanonicalGameplayBindingTransitionRequest request = diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierKey.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierKey.java new file mode 100644 index 0000000000..afbf82071a --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierKey.java @@ -0,0 +1,38 @@ +package net.firedevops.firemud.gamesession.repository; + +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.gamesession.repository.CanonicalGameplayTenantGameplayTagRepository.Assignment; + +/** Builds the one tenant-slot issuer barrier key from persisted tenant placement evidence. */ +final class CanonicalGameplayIssuerAdmissionBarrierKey { + private CanonicalGameplayIssuerAdmissionBarrierKey() {} + + static String forTarget(String issuerId, Assignment assignment) { + Objects.requireNonNull(assignment, "assignment"); + return forTarget( + issuerId, + assignment.tenantId(), + assignment.playableStateNamespaceId(), + assignment.tenantGameplayTag()); + } + + static String forTarget(String issuerId, UUID tenantId, UUID namespaceId, String tag) { + Objects.requireNonNull(tenantId, "tenantId"); + Objects.requireNonNull(namespaceId, "playableStateNamespaceId"); + Objects.requireNonNull(tag, "tenantGameplayTag"); + if (!net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile.ISSUER + .equals(issuerId) + || !tag.matches("g[1-9][0-9]{0,9}-[0-9a-f]{32}")) { + throw new IllegalArgumentException("Issuer barrier key requires exact Account issuer placement"); + } + return "session:game:issuer-admission:{" + + tag + + "}:" + + issuerId + + ":" + + tenantId + + ":" + + namespaceId; + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRedisOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRedisOwner.java new file mode 100644 index 0000000000..248c302bb0 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRedisOwner.java @@ -0,0 +1,539 @@ +package net.firedevops.firemud.gamesession.repository; + +import io.lettuce.core.RedisFuture; +import io.lettuce.core.ScriptOutputType; +import io.lettuce.core.api.StatefulRedisConnection; +import io.lettuce.core.api.async.RedisAsyncCommands; +import io.lettuce.core.codec.ByteArrayCodec; +import java.io.IOException; +import java.io.InputStream; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HexFormat; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor; +import net.firedevops.firemud.gamesession.service.CanonicalGameplayIssuerAdmissionBarrierRedisScriptContribution; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Explicit manual owner for exact one-key issuer tenant barrier projection and readback. */ +final class CanonicalGameplayIssuerAdmissionBarrierRedisOwner { + private static final String PRINCIPAL = "gamesession_coord_app"; + private static final String KEY_PREFIX = "session:game:issuer-admission:"; + private static final int MAX_SCRIPT_BYTES = 32 * 1024; + private static final long COMMAND_TIMEOUT_MILLIS = 5_000; + private static final List FIELDS = + List.of( + "schema", + "issuerId", + "tenantId", + "playableStateNamespaceId", + "tenantGameplayTag", + "state", + "admissionEpoch", + "ownerOperationId", + "initializerOperationId", + "initializerEpoch", + "initializerDigest", + "payloadDigest", + "payload"); + + private final io.lettuce.core.RedisClient redisClient; + private final RedisScriptCatalog catalog; + private final ProjectionRepository repository; + private final CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerStateSource + currentStateSource; + + CanonicalGameplayIssuerAdmissionBarrierRedisOwner( + io.lettuce.core.RedisClient redisClient, + RedisScriptCatalog catalog, + ProjectionRepository repository, + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerStateSource + currentStateSource) { + this.redisClient = Objects.requireNonNull(redisClient, "Configured Redis client is required"); + this.catalog = Objects.requireNonNull(catalog, "Manual Redis script catalog is required"); + this.repository = Objects.requireNonNull(repository, "Actual SQL projection repository is required"); + this.currentStateSource = + Objects.requireNonNull(currentStateSource, "Fresh issuer source is required"); + } + + /** Writes and independently reads back one exact original initializer's OPEN payload. */ + Readback initializeAndRead(UUID operationId) { + Objects.requireNonNull(operationId, "operationId"); + try { + requireNoAmbientTransaction(); + PreparedInitializer prepared = repository.readPreparedInitializer(operationId); + requireCurrentState(prepared.value().initializer()); + repository.requireStillCurrent(prepared); + String createMode = prepared.consumeCreatePermit() ? "CREATE_ONCE" : "REPLAY_ONLY"; + RedisScriptDescriptor descriptor = requireDescriptor( + CanonicalGameplayIssuerAdmissionBarrierRedisScriptContribution.OPEN_SCRIPT_ID, + CanonicalGameplayIssuerAdmissionBarrierRedisScriptContribution.OPEN_RESOURCE_PATH, + OPEN_ARGUMENTS, + OPEN_OUTCOMES); + byte[] script = scriptSource(descriptor); + CanonicalGameplayIssuerAdmissionBarrierValue value = prepared.value(); + byte[] payload = value.exactBytes(); + long result = + writeOneKey( + script, + prepared.key(), + ascii(value.issuerId()), + ascii(value.tenantId().toString()), + ascii(value.playableStateNamespaceId().toString()), + ascii(value.tenantGameplayTag()), + ascii(value.ownerOperationId().toString()), + ascii(value.admissionEpoch().toString()), + ascii(value.initializer().exactDigest()), + ascii(value.exactDigest()), + payload, + ascii(value.state().name()), + ascii(createMode)); + if (result < 1 || result > 2) throw unavailable(); + byte[] observed = readExactPhysicalState(prepared.key(), value); + requireCurrentState(value.initializer()); + repository.requireStillCurrent(prepared); + Readback readback = new Readback(value, result, observed); + repository.recordOpenReadback(prepared, readback); + return readback; + } catch (RuntimeException failure) { + if (isUnavailable(failure)) throw failure; + throw unavailable(failure); + } + } + + /** Closes one exact captured cutoff target and independently reads back its CLOSED payload. */ + Readback closeAndRead(UUID operationId, UUID tenantId, UUID namespaceId) { + Objects.requireNonNull(operationId, "operationId"); + Objects.requireNonNull(tenantId, "tenantId"); + Objects.requireNonNull(namespaceId, "namespaceId"); + try { + requireNoAmbientTransaction(); + PreparedCutoffTarget prepared = + repository.readPreparedCutoffTarget(operationId, tenantId, namespaceId); + repository.requireStillCurrent(prepared); + RedisScriptDescriptor descriptor = requireDescriptor( + CanonicalGameplayIssuerAdmissionBarrierRedisScriptContribution.CLOSE_SCRIPT_ID, + CanonicalGameplayIssuerAdmissionBarrierRedisScriptContribution.CLOSE_RESOURCE_PATH, + CLOSE_ARGUMENTS, + CLOSE_OUTCOMES); + byte[] script = scriptSource(descriptor); + CanonicalGameplayIssuerAdmissionBarrierValue closed = prepared.closedValue(); + CanonicalGameplayIssuerAdmissionBarrierValue.Initializer initializer = closed.initializer(); + CanonicalGameplayIssuerAdmissionBarrierValue expectedOpen = prepared.expectedOpenValue(); + byte[] payload = closed.exactBytes(); + long result = + writeOneKey( + script, + prepared.key(), + ascii(closed.issuerId()), + ascii(closed.tenantId().toString()), + ascii(closed.playableStateNamespaceId().toString()), + ascii(closed.tenantGameplayTag()), + ascii(closed.ownerOperationId().toString()), + ascii(closed.admissionEpoch().toString()), + ascii(closed.exactDigest()), + payload, + ascii(initializer == null ? "none" : initializer.operationId().toString()), + ascii(initializer == null ? "0" : initializer.admissionEpoch().toString()), + ascii(initializer == null ? "none" : initializer.exactDigest()), + ascii(expectedOpen == null ? "none" : expectedOpen.exactDigest()), + expectedOpen == null ? new byte[0] : expectedOpen.exactBytes(), + ascii(closed.state().name())); + if (result < 1 || result > 3) throw unavailable(); + byte[] observed = readExactPhysicalState(prepared.key(), closed); + repository.requireStillCurrent(prepared); + Readback readback = new Readback(closed, result, observed); + repository.recordClosedReadback(prepared, readback); + return readback; + } catch (RuntimeException failure) { + if (isUnavailable(failure)) throw failure; + throw unavailable(failure); + } + } + + private void requireCurrentState( + CanonicalGameplayIssuerAdmissionBarrierValue.Initializer initializer) { + requireNoAmbientTransaction(); + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState current; + try { + current = currentStateSource.readFreshCurrentState(); + } catch (RuntimeException failure) { + throw unavailable(failure); + } + if (current == null || !initializer.matchesCurrentIssuerState(current)) throw unavailable(); + } + + private byte[] readExactPhysicalState( + String key, CanonicalGameplayIssuerAdmissionBarrierValue expected) { + requireNoAmbientTransaction(); + byte[] keyBytes = ascii(key); + try (StatefulRedisConnection connection = + redisClient.connect(ByteArrayCodec.INSTANCE)) { + RedisAsyncCommands commands = requireCommands(connection); + requirePrincipal(await(commands.aclWhoami())); + if (!"hash".equals(await(commands.type(keyBytes))) + || !Long.valueOf(-1L).equals(await(commands.pttl(keyBytes)))) throw unavailable(); + Long length = await(commands.hlen(keyBytes)); + if (length == null || length != FIELDS.size()) throw unavailable(); + Map raw = await(commands.hgetall(keyBytes)); + if (raw == null || raw.size() != FIELDS.size()) throw unavailable(); + Map actual = new HashMap<>(); + for (Map.Entry entry : raw.entrySet()) { + String field = asciiString(entry.getKey()); + if (!FIELDS.contains(field) + || actual.putIfAbsent(field, Objects.requireNonNull(entry.getValue()).clone()) != null) { + throw unavailable(); + } + } + Map wanted = physicalFields(expected); + if (actual.size() != wanted.size()) throw unavailable(); + for (Map.Entry entry : wanted.entrySet()) { + if (!Arrays.equals(actual.get(entry.getKey()), entry.getValue())) throw unavailable(); + } + byte[] payload = actual.get("payload"); + CanonicalGameplayIssuerAdmissionBarrierValue decoded = + CanonicalGameplayIssuerAdmissionBarrierValue.decode(payload); + if (!Arrays.equals(decoded.exactBytes(), expected.exactBytes()) + || !decoded.exactDigest().equals(expected.exactDigest())) throw unavailable(); + return payload.clone(); + } catch (RuntimeException failure) { + throw unavailable(failure); + } + } + + private long writeOneKey(byte[] script, String key, byte[]... arguments) { + requireNoAmbientTransaction(); + try (StatefulRedisConnection connection = + redisClient.connect(ByteArrayCodec.INSTANCE)) { + RedisAsyncCommands commands = requireCommands(connection); + requirePrincipal(await(commands.aclWhoami())); + String sha = await(commands.scriptLoad(script)); + if (!digest("SHA-1", script).equals(sha)) throw unavailable(); + Long reply = + await( + commands.evalsha( + sha, + ScriptOutputType.INTEGER, + new byte[][] {ascii(key)}, + arguments)); + if (reply == null) throw unavailable(); + return reply; + } catch (RuntimeException failure) { + throw unavailable(failure); + } + } + + private RedisScriptDescriptor requireDescriptor( + String scriptId, + String resourcePath, + List arguments, + List outcomes) { + try { + RedisScriptDescriptor descriptor = catalog.require(scriptId); + if (!scriptId.equals(descriptor.scriptId()) + || !resourcePath.equals(descriptor.resourcePath()) + || !"game-session-service".equals(descriptor.owner()) + || !PRINCIPAL.equals(descriptor.principal()) + || descriptor.role() != RedisScriptDescriptor.RedisRole.COORDINATION + || !List.of( + new RedisScriptDescriptor.KeySpec( + "issuerAdmissionBarrier", + KEY_PREFIX, + RedisScriptDescriptor.HashTagDeclaration.REQUIRED)) + .equals(descriptor.keys()) + || !arguments.equals(descriptor.arguments()) + || descriptor.category() != RedisScriptDescriptor.ScriptCategory.SESSION_CAS + || !outcomes.equals(descriptor.outcomes()) + || descriptor.resetSensitivity() != RedisScriptDescriptor.ResetSensitivity.CLUSTER + || descriptor.lossClass() + != RedisScriptDescriptor.LossClass.EMPTY_REDIS_COLD_START_OR_RESET + || descriptor.compatibilityLevel() + != RedisScriptDescriptor.CompatibilityLevel.REQUIRES_CLUSTER_RESET + || !descriptor + .supportedCoexistence() + .equals(List.of(new RedisScriptDescriptor.SupportedCoexistence("v1", "none"))) + || descriptor.legacyPayloadShape() != null) throw unavailable(); + return descriptor; + } catch (RuntimeException failure) { + throw unavailable(failure); + } + } + + private static byte[] scriptSource(RedisScriptDescriptor descriptor) { + try (InputStream input = + CanonicalGameplayIssuerAdmissionBarrierRedisOwner.class + .getClassLoader() + .getResourceAsStream(descriptor.resourcePath())) { + if (input == null) throw unavailable(); + byte[] bytes = input.readNBytes(MAX_SCRIPT_BYTES + 1); + if (bytes.length == 0 + || bytes.length > MAX_SCRIPT_BYTES + || !descriptor.sha256().equals(digest("SHA-256", bytes))) throw unavailable(); + return bytes; + } catch (IOException | RuntimeException failure) { + throw unavailable(failure); + } + } + + private static Map physicalFields( + CanonicalGameplayIssuerAdmissionBarrierValue value) { + var initializer = value.initializer(); + Map fields = new HashMap<>(); + fields.put("schema", ascii(CanonicalGameplayIssuerAdmissionBarrierValue.SCHEMA)); + fields.put("issuerId", ascii(value.issuerId())); + fields.put("tenantId", ascii(value.tenantId().toString())); + fields.put("playableStateNamespaceId", ascii(value.playableStateNamespaceId().toString())); + fields.put("tenantGameplayTag", ascii(value.tenantGameplayTag())); + fields.put("state", ascii(value.state().name())); + fields.put("admissionEpoch", ascii(value.admissionEpoch().toString())); + fields.put("ownerOperationId", ascii(value.ownerOperationId().toString())); + fields.put("initializerOperationId", ascii(initializer == null ? "none" : initializer.operationId().toString())); + fields.put("initializerEpoch", ascii(initializer == null ? "0" : initializer.admissionEpoch().toString())); + fields.put("initializerDigest", ascii(initializer == null ? "none" : initializer.exactDigest())); + fields.put("payloadDigest", ascii(value.exactDigest())); + fields.put("payload", value.exactBytes()); + return fields; + } + + private static RedisAsyncCommands requireCommands( + StatefulRedisConnection connection) { + if (connection == null || !connection.isOpen()) throw unavailable(); + RedisAsyncCommands commands = connection.async(); + if (commands == null) throw unavailable(); + return commands; + } + + private static void requirePrincipal(String principal) { + if (!PRINCIPAL.equals(principal)) throw unavailable(); + } + + private static byte[] ascii(String value) { + Objects.requireNonNull(value, "ASCII value"); + for (int index = 0; index < value.length(); index++) { + if (value.charAt(index) > 0x7f) throw unavailable(); + } + return value.getBytes(StandardCharsets.US_ASCII); + } + + private static String asciiString(byte[] value) { + Objects.requireNonNull(value, "Redis field"); + for (byte character : value) if ((character & 0x80) != 0) throw unavailable(); + return new String(value, StandardCharsets.US_ASCII); + } + + private static String digest(String algorithm, byte[] bytes) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance(algorithm).digest(bytes)); + } catch (Exception failure) { + throw unavailable(failure); + } + } + + private static T await(RedisFuture future) { + if (future == null) throw unavailable(); + try { + return future.get(COMMAND_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw unavailable(interrupted); + } catch (ExecutionException | TimeoutException failure) { + throw unavailable(failure); + } + } + + private static void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive()) throw unavailable(); + } + + private static boolean isUnavailable(RuntimeException failure) { + return failure instanceof IllegalStateException + && failure.getMessage() != null + && failure.getMessage().contains("Issuer tenant admission barrier is unavailable"); + } + + private static IllegalStateException unavailable() { + return new IllegalStateException("Issuer tenant admission barrier is unavailable"); + } + + private static IllegalStateException unavailable(Throwable cause) { + return new IllegalStateException("Issuer tenant admission barrier is unavailable", cause); + } + + private static final List OPEN_ARGUMENTS = + List.of( + new RedisScriptDescriptor.ArgumentSpec("issuerId"), + new RedisScriptDescriptor.ArgumentSpec("tenantId"), + new RedisScriptDescriptor.ArgumentSpec("playableStateNamespaceId"), + new RedisScriptDescriptor.ArgumentSpec("tenantGameplayTag"), + new RedisScriptDescriptor.ArgumentSpec("initializerOperationId"), + new RedisScriptDescriptor.ArgumentSpec("admissionBarrierEpoch"), + new RedisScriptDescriptor.ArgumentSpec("initializerTupleDigest"), + new RedisScriptDescriptor.ArgumentSpec("exactBarrierPayloadDigest"), + new RedisScriptDescriptor.ArgumentSpec("exactBarrierPayload"), + new RedisScriptDescriptor.ArgumentSpec("state"), + new RedisScriptDescriptor.ArgumentSpec("createMode")); + private static final List OPEN_OUTCOMES = + List.of( + outcome("OPEN_CREATED", RedisScriptDescriptor.OutcomeCategory.SUCCESS, + RedisScriptDescriptor.MutationEffect.MUTATING), + outcome("OPEN_REPLAY", RedisScriptDescriptor.OutcomeCategory.REPLAY, + RedisScriptDescriptor.MutationEffect.NON_MUTATING), + outcome("TYPE_TTL_OR_FIELDSET_REFUSED", RedisScriptDescriptor.OutcomeCategory.VALIDATION_FAILURE, + RedisScriptDescriptor.MutationEffect.NON_MUTATING), + outcome("INVALID_ARGUMENTS_OR_TARGET", RedisScriptDescriptor.OutcomeCategory.VALIDATION_FAILURE, + RedisScriptDescriptor.MutationEffect.NON_MUTATING), + outcome("CLOSED_OR_CONFLICTING_STATE", RedisScriptDescriptor.OutcomeCategory.STALE, + RedisScriptDescriptor.MutationEffect.NON_MUTATING)); + private static final List CLOSE_ARGUMENTS = + List.of( + new RedisScriptDescriptor.ArgumentSpec("issuerId"), + new RedisScriptDescriptor.ArgumentSpec("tenantId"), + new RedisScriptDescriptor.ArgumentSpec("playableStateNamespaceId"), + new RedisScriptDescriptor.ArgumentSpec("tenantGameplayTag"), + new RedisScriptDescriptor.ArgumentSpec("cutoffOperationId"), + new RedisScriptDescriptor.ArgumentSpec("cutoffAdmissionBarrierEpoch"), + new RedisScriptDescriptor.ArgumentSpec("exactClosedPayloadDigest"), + new RedisScriptDescriptor.ArgumentSpec("exactClosedPayload"), + new RedisScriptDescriptor.ArgumentSpec("capturedInitializerOperationIdOrNone"), + new RedisScriptDescriptor.ArgumentSpec("capturedInitializerAdmissionBarrierEpochOrZero"), + new RedisScriptDescriptor.ArgumentSpec("capturedInitializerTupleDigestOrNone"), + new RedisScriptDescriptor.ArgumentSpec("expectedOriginalOpenPayloadDigestOrNone"), + new RedisScriptDescriptor.ArgumentSpec("expectedOriginalOpenPayloadOrEmpty"), + new RedisScriptDescriptor.ArgumentSpec("state")); + private static final List CLOSE_OUTCOMES = + List.of( + outcome("CLOSED_CREATED", RedisScriptDescriptor.OutcomeCategory.SUCCESS, + RedisScriptDescriptor.MutationEffect.MUTATING), + outcome("CLOSED_REPLAY", RedisScriptDescriptor.OutcomeCategory.REPLAY, + RedisScriptDescriptor.MutationEffect.NON_MUTATING), + outcome("CAPTURED_OPEN_CLOSED", RedisScriptDescriptor.OutcomeCategory.SUCCESS, + RedisScriptDescriptor.MutationEffect.MUTATING), + outcome("TYPE_TTL_OR_FIELDSET_REFUSED", RedisScriptDescriptor.OutcomeCategory.VALIDATION_FAILURE, + RedisScriptDescriptor.MutationEffect.NON_MUTATING), + outcome("INVALID_ARGUMENTS_OR_TARGET", RedisScriptDescriptor.OutcomeCategory.VALIDATION_FAILURE, + RedisScriptDescriptor.MutationEffect.NON_MUTATING), + outcome("NEWER_CLOSED_OR_UNEXPECTED_STATE", RedisScriptDescriptor.OutcomeCategory.STALE, + RedisScriptDescriptor.MutationEffect.NON_MUTATING)); + + private static RedisScriptDescriptor.OutcomeSpec outcome( + String code, + RedisScriptDescriptor.OutcomeCategory category, + RedisScriptDescriptor.MutationEffect effect) { + return new RedisScriptDescriptor.OutcomeSpec(code, category, effect); + } + + interface ProjectionRepository { + PreparedInitializer readPreparedInitializer(UUID operationId); + + PreparedCutoffTarget readPreparedCutoffTarget( + UUID cutoffOperationId, UUID tenantId, UUID namespaceId); + + void requireStillCurrent(PreparedInitializer prepared); + + void requireStillCurrent(PreparedCutoffTarget prepared); + + void recordOpenReadback(PreparedInitializer prepared, Readback readback); + + void recordClosedReadback(PreparedCutoffTarget prepared, Readback readback); + } + + static final class PreparedInitializer { + private final CanonicalGameplayIssuerAdmissionBarrierValue value; + private final CanonicalGameplayTenantGameplayTagRepository.Assignment assignment; + private final UUID requestOperationId; + private final String key; + private final java.util.concurrent.atomic.AtomicBoolean createPermit; + + PreparedInitializer( + CanonicalGameplayIssuerAdmissionBarrierValue value, + CanonicalGameplayTenantGameplayTagRepository.Assignment assignment, + UUID requestOperationId, + String key, + boolean createPermit) { + this.value = Objects.requireNonNull(value, "value"); + this.assignment = assignment; + this.requestOperationId = Objects.requireNonNull(requestOperationId, "requestOperationId"); + this.key = Objects.requireNonNull(key, "key"); + this.createPermit = new java.util.concurrent.atomic.AtomicBoolean(createPermit); + if (value.state() != CanonicalGameplayIssuerAdmissionBarrierValue.State.OPEN + || !CanonicalGameplayIssuerAdmissionBarrierKey.forTarget( + value.issuerId(), + value.tenantId(), + value.playableStateNamespaceId(), + value.tenantGameplayTag()) + .equals(key)) throw unavailable(); + if (assignment == null) { + if (!requestOperationId.equals(value.initializer().operationId())) throw unavailable(); + } else if (!assignment.isBindingTransition() + || !assignment.tenantId().equals(value.tenantId()) + || !assignment.playableStateNamespaceId().equals(value.playableStateNamespaceId()) + || !assignment.tenantGameplayTag().equals(value.tenantGameplayTag())) { + throw unavailable(); + } + } + + CanonicalGameplayIssuerAdmissionBarrierValue value() { return value; } + CanonicalGameplayTenantGameplayTagRepository.Assignment assignment() { return assignment; } + UUID requestOperationId() { return requestOperationId; } + String key() { return key; } + + /** Consumes the SQL owner's first-attempt authority before any Redis command is attempted. */ + boolean consumeCreatePermit() { + return createPermit.getAndSet(false); + } + } + + record PreparedCutoffTarget( + CanonicalGameplayIssuerAdmissionBarrierValue closedValue, + CanonicalGameplayIssuerAdmissionBarrierValue expectedOpenValue, + String key) { + PreparedCutoffTarget { + Objects.requireNonNull(closedValue, "closedValue"); + Objects.requireNonNull(key, "key"); + if (closedValue.state() != CanonicalGameplayIssuerAdmissionBarrierValue.State.CLOSED + || (expectedOpenValue != null + && (expectedOpenValue.state() != CanonicalGameplayIssuerAdmissionBarrierValue.State.OPEN + || closedValue.initializer() == null + || !Arrays.equals( + closedValue.initializer().exactBytes(), + expectedOpenValue.initializer().exactBytes()))) + || !CanonicalGameplayIssuerAdmissionBarrierKey.forTarget( + closedValue.issuerId(), + closedValue.tenantId(), + closedValue.playableStateNamespaceId(), + closedValue.tenantGameplayTag()) + .equals(key)) throw unavailable(); + } + } + + static final class Readback { + private final CanonicalGameplayIssuerAdmissionBarrierValue value; + private final long scriptOutcome; + private final byte[] exactPhysicalPayload; + + private Readback( + CanonicalGameplayIssuerAdmissionBarrierValue value, + long scriptOutcome, + byte[] exactPhysicalPayload) { + this.value = Objects.requireNonNull(value, "value"); + if (scriptOutcome < 1 || scriptOutcome > 3) throw unavailable(); + this.scriptOutcome = scriptOutcome; + this.exactPhysicalPayload = Objects.requireNonNull(exactPhysicalPayload).clone(); + if (!Arrays.equals(value.exactBytes(), this.exactPhysicalPayload)) throw unavailable(); + } + + CanonicalGameplayIssuerAdmissionBarrierValue value() { return value; } + long scriptOutcome() { return scriptOutcome; } + byte[] exactPhysicalPayload() { return exactPhysicalPayload.clone(); } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRedisOwnerFactory.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRedisOwnerFactory.java new file mode 100644 index 0000000000..edc2ee96b2 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRedisOwnerFactory.java @@ -0,0 +1,22 @@ +package net.firedevops.firemud.gamesession.repository; + +import io.lettuce.core.RedisClient; +import java.util.Objects; +import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; + +/** Explicit manual factory; it does not register a runtime or ServiceLoader provider. */ +final class CanonicalGameplayIssuerAdmissionBarrierRedisOwnerFactory { + private CanonicalGameplayIssuerAdmissionBarrierRedisOwnerFactory() {} + + static CanonicalGameplayIssuerAdmissionBarrierRedisOwner create( + RedisClient redisClient, + RedisScriptCatalog catalog, + CanonicalGameplayIssuerAdmissionBarrierRedisOwner.ProjectionRepository repository, + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerStateSource currentStateSource) { + return new CanonicalGameplayIssuerAdmissionBarrierRedisOwner( + Objects.requireNonNull(redisClient, "redisClient"), + Objects.requireNonNull(catalog, "catalog"), + Objects.requireNonNull(repository, "repository"), + Objects.requireNonNull(currentStateSource, "currentStateSource")); + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepository.java new file mode 100644 index 0000000000..9202005e73 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepository.java @@ -0,0 +1,981 @@ +package net.firedevops.firemud.gamesession.repository; + +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.impl.DSL; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** SQL projection owner for immutable tenant OPEN initializers and issuer-wide CLOSED cutoffs. */ +final class CanonicalGameplayIssuerAdmissionBarrierRepository + implements CanonicalGameplayIssuerAdmissionBarrierRedisOwner.ProjectionRepository { + private static final String ISSUER = GameSessionAccountDelegationProfile.ISSUER; + private static final String CONTROL = "game_session_canonical_issuer_admission_control"; + private static final String INITIALIZER = "game_session_canonical_issuer_admission_initializer"; + private static final String INITIALIZER_RECEIPT = + "game_session_canonical_issuer_admission_initializer_receipt"; + private static final String CUTOFF_TARGET = + "game_session_canonical_issuer_admission_cutoff_target"; + private static final String LOCAL_OPERATION = + "game_session_canonical_issuer_binding_local_operation"; + private static final String TENANT_TAG = "game_session_canonical_tenant_gameplay_tag"; + + private final DSLContext dsl; + private final CanonicalGameplayTenantGameplayTagRepository tenantTags; + private final CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerStateSource + currentStateSource; + + CanonicalGameplayIssuerAdmissionBarrierRepository( + DSLContext dsl, + CanonicalGameplayTenantGameplayTagRepository tenantTags, + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerStateSource + currentStateSource) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + this.tenantTags = Objects.requireNonNull(tenantTags, "tenantTags"); + this.currentStateSource = Objects.requireNonNull(currentStateSource, "currentStateSource"); + } + + /** Persists the original complete OPEN payload before the Redis owner is allowed to write it. */ + @Override + public CanonicalGameplayIssuerAdmissionBarrierRedisOwner.PreparedInitializer + readPreparedInitializer(UUID operationId) { + requireNonNil(operationId, "operationId"); + requireNoAmbientTransaction(); + Record originalOperationInitializer = + dsl.fetchOne( + "SELECT operation_id FROM " + INITIALIZER + + " WHERE operation_id = ? AND issuer_id = ?", + operationId, + ISSUER); + CanonicalGameplayTenantGameplayTagRepository.Assignment requestAssignment = + originalOperationInitializer == null + ? tenantTags.assignmentForTransition(transitionForLocalOperation(operationId)) + : null; + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState before = + readCurrentState(); + PreparedInitializerSource source = + dsl.transactionResult( + configuration -> { + DSLContext transaction = DSL.using(configuration); + CanonicalGameplayBindingInventoryRepository.lockInventoryRevision(transaction); + if (requestAssignment != null) { + requireCurrentTagMapping( + transaction, + requestAssignment.tenantId(), + requestAssignment.tenantGameplayTag()); + } + CanonicalGameplayIssuerInstalledAnchor anchor = + CanonicalGameplayIssuerBootstrapCoverageRepository + .readInstalledAnchorForBindingPreparationInTransaction(transaction, before); + CanonicalGameplayIssuerAdmissionControlValue control = + CanonicalGameplayIssuerAdmissionControlRepository.requireOpenInTransaction( + transaction, anchor, before); + Record byOperation = + transaction.fetchOne( + "SELECT * FROM " + INITIALIZER + + " WHERE operation_id = ? AND issuer_id = ? FOR UPDATE", + operationId, + ISSUER); + if (byOperation != null) { + CanonicalGameplayIssuerAdmissionBarrierValue frozen = + readFrozenInitializer( + transaction, byOperation, null, anchor, control, before); + if (requestAssignment != null) { + requireSameTargetAssignment(requestAssignment, frozen.initializer()); + } + return new PreparedInitializerSource(frozen, null); + } + if (requestAssignment == null) { + throw conflict("The exact original tenant initializer disappeared"); + } + + CurrentRequestTarget requestTarget = + requireCurrentRequestTarget( + transaction, operationId, requestAssignment, before); + Record targetInitializer = + transaction.fetchOne( + "SELECT * FROM " + INITIALIZER + + " WHERE issuer_id = ? AND tenant_id = ?" + + " AND playable_state_namespace_id = ? AND live_barrier_epoch = ?" + + " FOR UPDATE", + ISSUER, + requestAssignment.tenantId(), + requestAssignment.playableStateNamespaceId(), + control.liveBarrierEpoch()); + if (targetInitializer != null) { + CanonicalGameplayIssuerAdmissionBarrierValue frozen = + readFrozenInitializer( + transaction, targetInitializer, requestAssignment, anchor, control, before); + return new PreparedInitializerSource(frozen, requestAssignment); + } + + CanonicalGameplayAdmissionBarrierTuple tuple = + buildOriginalInitializer( + transaction, + operationId, + requestTarget, + requestAssignment, + anchor, + control, + before); + CanonicalGameplayIssuerAdmissionBarrierValue original = + CanonicalGameplayIssuerAdmissionBarrierValue.open(tuple.initializer()); + persistOriginalInitializer(transaction, original); + return new PreparedInitializerSource(original, requestAssignment); + }); + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState current = + readCurrentState(); + CanonicalGameplayIssuerAdmissionBarrierValue value = source.value(); + if (!value.initializer().matchesCurrentIssuerState(current)) { + throw conflict("Original OPEN initializer no longer matches current Account issuer source"); + } + boolean createPermit = + claimFirstCreatePermit(value.initializer().operationId(), value, current); + CanonicalGameplayIssuerAdmissionBarrierRedisOwner.PreparedInitializer prepared = + prepared(value, source.requestAssignment(), operationId, createPermit); + requireStillCurrent(prepared); + return prepared; + } + + /** Starts the one issuer-wide live cutoff after resolving the complete durable target set. */ + CanonicalGameplayIssuerAdmissionControlValue beginCutoff(UUID operationId, UUID requestId) { + requireNonNil(operationId, "operationId"); + requireNonNil(requestId, "requestId"); + requireNoAmbientTransaction(); + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState before = + readCurrentState(); + CanonicalGameplayIssuerInstalledAnchor anchor = readInstalledAnchor(before); + CanonicalGameplayIssuerAdmissionControlValue pending = + new CanonicalGameplayIssuerAdmissionControlRepository(dsl) + .beginCutoff(operationId, requestId, anchor, before); + if (!pending.matchesCurrentIssuerState(readCurrentState())) { + throw conflict("Current issuer source or stable incarnation moved during cutoff capture"); + } + return pending; + } + + /** Completes the durable cutoff only after every frozen target has a CLOSED readback. */ + CanonicalGameplayIssuerAdmissionControlValue completeCutoff(UUID operationId) { + requireNonNil(operationId, "operationId"); + requireNoAmbientTransaction(); + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState before = + readCurrentState(); + CanonicalGameplayIssuerInstalledAnchor anchor = readInstalledAnchor(before); + CanonicalGameplayIssuerAdmissionControlValue installed = + new CanonicalGameplayIssuerAdmissionControlRepository(dsl) + .completeCutoff(operationId, anchor, before); + if (!installed.matchesCurrentIssuerState(readCurrentState())) { + throw conflict("Current issuer source or stable incarnation moved during cutoff completion"); + } + return installed; + } + + List + readPreparedCutoffTargets(UUID cutoffOperationId) { + requireNonNil(cutoffOperationId, "cutoffOperationId"); + List targets = + dsl.fetch( + "SELECT tenant_id, playable_state_namespace_id FROM " + CUTOFF_TARGET + + " WHERE operation_id = ? AND issuer_id = ? ORDER BY target_ordinal", + cutoffOperationId, + ISSUER); + List prepared = + new ArrayList<>(); + for (Record target : targets) { + prepared.add( + readPreparedCutoffTarget( + cutoffOperationId, + requiredUuid(target, "tenant_id"), + requiredUuid(target, "playable_state_namespace_id"))); + } + return List.copyOf(prepared); + } + + @Override + public CanonicalGameplayIssuerAdmissionBarrierRedisOwner.PreparedCutoffTarget + readPreparedCutoffTarget(UUID cutoffOperationId, UUID tenantId, UUID namespaceId) { + requireNonNil(cutoffOperationId, "cutoffOperationId"); + requireNonNil(tenantId, "tenantId"); + requireNonNil(namespaceId, "namespaceId"); + requireNoAmbientTransaction(); + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState current = + readCurrentState(); + return dsl.transactionResult( + configuration -> { + DSLContext transaction = DSL.using(configuration); + CanonicalGameplayBindingInventoryRepository.lockInventoryRevision(transaction); + CanonicalGameplayIssuerInstalledAnchor anchor = + CanonicalGameplayIssuerBootstrapCoverageRepository + .readInstalledAnchorForBindingPreparationInTransaction(transaction, current); + CanonicalGameplayIssuerAdmissionControlValue control = + readCurrentControl(transaction, anchor, current); + if (!cutoffOperationId.equals(control.currentOperationId()) + || control.state() + != CanonicalGameplayIssuerAdmissionControlValue.State.CUTOFF_PENDING) { + throw conflict("The exact current issuer cutoff is not pending"); + } + new CanonicalGameplayIssuerAdmissionControlRepository(dsl) + .verifyCurrentCutoffTarget(transaction, control, tenantId, namespaceId, null); + Record target = + transaction.fetchOne( + "SELECT * FROM " + CUTOFF_TARGET + + " WHERE operation_id = ? AND issuer_id = ? AND tenant_id = ?" + + " AND playable_state_namespace_id = ? FOR UPDATE", + cutoffOperationId, + ISSUER, + tenantId, + namespaceId); + if (target == null + || !tenantId.equals(requiredUuid(target, "tenant_id")) + || !namespaceId.equals(requiredUuid(target, "playable_state_namespace_id"))) { + throw conflict("The exact durable cutoff target is unavailable"); + } + String tenantTag = requireText(target, "tenant_gameplay_tag"); + requireCurrentTagMapping(transaction, tenantId, tenantTag); + CanonicalGameplayIssuerAdmissionBarrierValue closed = + CanonicalGameplayIssuerAdmissionBarrierValue.decode( + requireBytes(target, "closed_payload_bytes")); + byte[] capturedOpen = target.get("captured_open_payload_bytes", byte[].class); + CanonicalGameplayIssuerAdmissionBarrierValue expectedOpen = + capturedOpen == null + ? null + : CanonicalGameplayIssuerAdmissionBarrierValue.decode(capturedOpen); + if (!closed.exactDigest().equals(target.get("closed_payload_digest", String.class))) { + throw conflict("Persisted issuer cutoff target digest is invalid"); + } + return new CanonicalGameplayIssuerAdmissionBarrierRedisOwner.PreparedCutoffTarget( + closed, + expectedOpen, + CanonicalGameplayIssuerAdmissionBarrierKey.forTarget( + ISSUER, tenantId, namespaceId, tenantTag)); + }); + } + + @Override + public void requireStillCurrent( + CanonicalGameplayIssuerAdmissionBarrierRedisOwner.PreparedInitializer prepared) { + Objects.requireNonNull(prepared, "prepared"); + requireNoAmbientTransaction(); + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState current = + readCurrentState(); + CanonicalGameplayIssuerAdmissionBarrierValue.Initializer initializer = + prepared.value().initializer(); + if (!initializer.matchesCurrentIssuerState(current)) { + throw conflict("Original OPEN initializer no longer matches current Account issuer source"); + } + CanonicalGameplayTenantGameplayTagRepository.Assignment assignment = + prepared.assignment() == null + ? null + : tenantTags.assignmentForTransition(prepared.assignment().transitionId()); + if (assignment != null) requireSameAssignment(prepared.assignment(), assignment); + dsl.transactionResult( + configuration -> { + DSLContext transaction = DSL.using(configuration); + CanonicalGameplayBindingInventoryRepository.lockInventoryRevision(transaction); + CanonicalGameplayIssuerInstalledAnchor anchor = + CanonicalGameplayIssuerBootstrapCoverageRepository + .readInstalledAnchorForBindingPreparationInTransaction(transaction, current); + CanonicalGameplayIssuerAdmissionControlValue control = + CanonicalGameplayIssuerAdmissionControlRepository.requireOpenInTransaction( + transaction, anchor, current); + if (!control.liveBarrierEpoch().equals(initializer.admissionEpoch()) + || !control.currentOperationId().equals(anchor.bootstrapOperationId())) { + throw conflict("Original initializer no longer belongs to current OPEN live control"); + } + if (assignment != null) { + requireCurrentTagMapping( + transaction, assignment.tenantId(), assignment.tenantGameplayTag()); + requireCurrentRequestTarget( + transaction, prepared.requestOperationId(), assignment, current); + } + Record saved = + transaction.fetchOne( + "SELECT * FROM " + INITIALIZER + + " WHERE operation_id = ? AND issuer_id = ? FOR UPDATE", + initializer.operationId(), + ISSUER); + readFrozenInitializer( + transaction, saved, prepared.assignment(), anchor, control, current); + return null; + }); + } + + @Override + public void requireStillCurrent( + CanonicalGameplayIssuerAdmissionBarrierRedisOwner.PreparedCutoffTarget prepared) { + Objects.requireNonNull(prepared, "prepared"); + requireNoAmbientTransaction(); + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState current = + readCurrentState(); + CanonicalGameplayIssuerAdmissionBarrierValue closed = prepared.closedValue(); + dsl.transactionResult( + configuration -> { + DSLContext transaction = DSL.using(configuration); + CanonicalGameplayBindingInventoryRepository.lockInventoryRevision(transaction); + CanonicalGameplayIssuerInstalledAnchor anchor = + CanonicalGameplayIssuerBootstrapCoverageRepository + .readInstalledAnchorForBindingPreparationInTransaction(transaction, current); + CanonicalGameplayIssuerAdmissionControlValue value = + readCurrentControl(transaction, anchor, current); + if (!closed.ownerOperationId().equals(value.currentOperationId()) + || value.state() != CanonicalGameplayIssuerAdmissionControlValue.State.CUTOFF_PENDING + || !closed.admissionEpoch().equals(value.liveBarrierEpoch())) { + throw conflict("Prepared CLOSED target no longer belongs to current pending cutoff"); + } + new CanonicalGameplayIssuerAdmissionControlRepository(dsl) + .verifyCurrentCutoffTarget( + transaction, + value, + closed.tenantId(), + closed.playableStateNamespaceId(), + closed.exactBytes()); + requireCurrentTagMapping( + transaction, closed.tenantId(), closed.tenantGameplayTag()); + return null; + }); + } + + @Override + public void recordOpenReadback( + CanonicalGameplayIssuerAdmissionBarrierRedisOwner.PreparedInitializer prepared, + CanonicalGameplayIssuerAdmissionBarrierRedisOwner.Readback readback) { + Objects.requireNonNull(prepared, "prepared"); + Objects.requireNonNull(readback, "readback"); + requireStillCurrent(prepared); + CanonicalGameplayIssuerAdmissionBarrierValue value = prepared.value(); + if (!Arrays.equals(value.exactBytes(), readback.exactPhysicalPayload()) + || !Arrays.equals(value.exactBytes(), readback.value().exactBytes()) + || readback.scriptOutcome() < 1 + || readback.scriptOutcome() > 2) { + throw conflict("OPEN readback does not match the exact original initializer"); + } + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState current = + readCurrentState(); + dsl.transactionResult( + configuration -> { + DSLContext transaction = DSL.using(configuration); + CanonicalGameplayBindingInventoryRepository.lockInventoryRevision(transaction); + CanonicalGameplayIssuerInstalledAnchor anchor = + CanonicalGameplayIssuerBootstrapCoverageRepository + .readInstalledAnchorForBindingPreparationInTransaction(transaction, current); + CanonicalGameplayIssuerAdmissionControlRepository.requireOpenInTransaction( + transaction, anchor, current); + Record initializer = + transaction.fetchOne( + "SELECT * FROM " + INITIALIZER + + " WHERE operation_id = ? AND issuer_id = ? FOR UPDATE", + value.initializer().operationId(), + ISSUER); + requirePersistedInitializer(initializer, value); + String initializationState = initializer.get("initialization_state", String.class); + if (!List.of("INITIALIZING", "OPEN_CONFIRMED").contains(initializationState)) { + throw conflict("OPEN readback has no durable first-attempt initializer state"); + } + transaction.execute( + "INSERT INTO " + INITIALIZER_RECEIPT + + " (operation_id, issuer_id, exact_open_payload_bytes," + + " exact_open_payload_digest, script_outcome) VALUES (?, ?, ?, ?, ?)" + + " ON CONFLICT (operation_id) DO NOTHING", + value.initializer().operationId(), + ISSUER, + value.exactBytes(), + value.exactDigest(), + (short) readback.scriptOutcome()); + Record receipt = + transaction.fetchOne( + "SELECT * FROM " + INITIALIZER_RECEIPT + + " WHERE operation_id = ? AND issuer_id = ? FOR UPDATE", + value.initializer().operationId(), + ISSUER); + if (receipt == null + || !Arrays.equals(requireBytes(receipt, "exact_open_payload_bytes"), value.exactBytes()) + || !value.exactDigest().equals(receipt.get("exact_open_payload_digest", String.class)) + || !List.of((short) 1, (short) 2).contains(receipt.get("script_outcome", Short.class))) { + throw conflict("Original OPEN readback receipt conflicts with durable initializer bytes"); + } + if ("INITIALIZING".equals(initializationState)) { + int confirmed = + transaction.execute( + "UPDATE " + INITIALIZER + + " SET initialization_state = 'OPEN_CONFIRMED'" + + " WHERE operation_id = ? AND issuer_id = ?" + + " AND initialization_state = 'INITIALIZING'", + value.initializer().operationId(), + ISSUER); + if (confirmed != 1) { + throw conflict("Original OPEN receipt could not confirm its initializer state"); + } + } + return null; + }); + } + + @Override + public void recordClosedReadback( + CanonicalGameplayIssuerAdmissionBarrierRedisOwner.PreparedCutoffTarget prepared, + CanonicalGameplayIssuerAdmissionBarrierRedisOwner.Readback readback) { + Objects.requireNonNull(prepared, "prepared"); + Objects.requireNonNull(readback, "readback"); + requireStillCurrent(prepared); + CanonicalGameplayIssuerAdmissionBarrierValue value = prepared.closedValue(); + if (!Arrays.equals(value.exactBytes(), readback.exactPhysicalPayload()) + || !Arrays.equals(value.exactBytes(), readback.value().exactBytes())) { + throw conflict("CLOSED readback differs from the exact cutoff target"); + } + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState current = + readCurrentState(); + dsl.transactionResult( + configuration -> { + DSLContext transaction = DSL.using(configuration); + CanonicalGameplayBindingInventoryRepository.lockInventoryRevision(transaction); + CanonicalGameplayIssuerInstalledAnchor anchor = + CanonicalGameplayIssuerBootstrapCoverageRepository + .readInstalledAnchorForBindingPreparationInTransaction(transaction, current); + CanonicalGameplayIssuerAdmissionControlValue control = + readCurrentControl(transaction, anchor, current); + if (!value.ownerOperationId().equals(control.currentOperationId()) + || control.state() != CanonicalGameplayIssuerAdmissionControlValue.State.CUTOFF_PENDING) { + throw conflict("CLOSED readback is not owned by the current pending cutoff"); + } + new CanonicalGameplayIssuerAdmissionControlRepository(dsl) + .verifyCurrentCutoffTarget( + transaction, + control, + value.tenantId(), + value.playableStateNamespaceId(), + value.exactBytes()); + requireCurrentTagMapping( + transaction, value.tenantId(), value.tenantGameplayTag()); + Record target = + transaction.fetchOne( + "SELECT * FROM " + CUTOFF_TARGET + + " WHERE operation_id = ? AND issuer_id = ? AND tenant_id = ?" + + " AND playable_state_namespace_id = ? FOR UPDATE", + value.ownerOperationId(), + ISSUER, + value.tenantId(), + value.playableStateNamespaceId()); + if (target == null + || !Arrays.equals(requireBytes(target, "closed_payload_bytes"), value.exactBytes()) + || !value.exactDigest().equals(target.get("closed_payload_digest", String.class))) { + throw conflict("CLOSED readback target changed before durable acknowledgement"); + } + String state = target.get("target_state", String.class); + if ("REQUIRED".equals(state)) { + int updated = + transaction.execute( + "UPDATE " + CUTOFF_TARGET + + " SET exact_closed_readback_bytes = ?, exact_closed_readback_digest = ? ," + + " script_outcome = ?, target_state = 'CLOSED'" + + " WHERE operation_id = ? AND target_ordinal = ? AND target_state = 'REQUIRED'", + value.exactBytes(), + value.exactDigest(), + (short) readback.scriptOutcome(), + value.ownerOperationId(), + target.get("target_ordinal", Long.class)); + if (updated != 1) throw conflict("CLOSED target changed during receipt persistence"); + } else if (!"CLOSED".equals(state) + || !Arrays.equals(requireBytes(target, "exact_closed_readback_bytes"), value.exactBytes()) + || !value.exactDigest().equals(target.get("exact_closed_readback_digest", String.class)) + || !List.of((short) 1, (short) 2, (short) 3) + .contains(target.get("script_outcome", Short.class))) { + throw conflict("CLOSED retry conflicts with its immutable durable readback"); + } + return null; + }); + } + + private CurrentRequestTarget requireCurrentRequestTarget( + DSLContext transaction, + UUID operationId, + CanonicalGameplayTenantGameplayTagRepository.Assignment assignment, + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState current) { + Record row = + transaction.fetchOne( + "SELECT op.operation_id, op.transition_id, op.binding_ref, op.member_value_bytes," + + " op.member_value_digest, op.member_status, op.issuer_id," + + " t.status AS transition_status, t.tenant_id AS transition_tenant_id," + + " t.playable_state_namespace_id AS transition_namespace_id," + + " t.admission_lease_id, t.admission_target_tenant_id," + + " t.admission_target_playable_state_namespace_id," + + " t.admission_target_owner_proof_outcome, t.admission_target_positive_durable_abort," + + " i.account_id, i.tenant_id, i.playable_state_namespace_id, i.lifecycle," + + " i.binding_ref AS inventory_binding_ref, r.reservation_id" + + " FROM " + LOCAL_OPERATION + " op" + + " JOIN game_session_canonical_binding_transition t ON t.transition_id = op.transition_id" + + " JOIN game_session_canonical_gameplay_binding_inventory i" + + " ON i.binding_ref = op.binding_ref AND i.transition_id = op.transition_id" + + " JOIN game_session_canonical_issuer_partition_reservation r" + + " ON r.reservation_id = op.reservation_id AND r.transition_id = op.transition_id" + + " WHERE op.operation_id = ? AND op.issuer_id = ?" + + " FOR UPDATE OF op, t, i, r", + operationId, + ISSUER); + if (row == null) throw conflict("The exact original issuer local operation is unavailable"); + UUID transitionId = requiredUuid(row, "transition_id"); + UUID tenantId = requiredUuid(row, "transition_tenant_id"); + UUID namespaceId = requiredUuid(row, "transition_namespace_id"); + if (!transitionId.equals(assignment.transitionId()) + || !tenantId.equals(assignment.tenantId()) + || !namespaceId.equals(assignment.playableStateNamespaceId()) + || !tenantId.equals(requiredUuid(row, "tenant_id")) + || !namespaceId.equals(requiredUuid(row, "playable_state_namespace_id")) + || !requiredUuid(row, "account_id").equals(assignment.accountId()) + || !List.of("PROVISIONAL", "COMMITTED").contains(row.get("transition_status", String.class)) + || !List.of("PROVISIONAL", "ACTIVE").contains(row.get("lifecycle", String.class)) + || row.get("admission_lease_id", UUID.class) == null + || !tenantId.equals(row.get("admission_target_tenant_id", UUID.class)) + || !namespaceId.equals(row.get("admission_target_playable_state_namespace_id", UUID.class)) + || !"COMMITTED".equals(row.get("admission_target_owner_proof_outcome", String.class)) + || !Boolean.FALSE.equals(row.get("admission_target_positive_durable_abort", Boolean.class))) { + throw conflict("Current issuer NEW request is not the exact registered tenant target"); + } + byte[] memberBytes = requireBytes(row, "member_value_bytes"); + if (!CanonicalGameplayIssuerMemberV2Codec.sha256(memberBytes) + .equals(row.get("member_value_digest", String.class)) + || !"PENDING_PHYSICAL_PROOF".equals(row.get("member_status", String.class))) { + throw conflict("Current local issuer operation has malformed pending member evidence"); + } + CanonicalGameplayIssuerMemberV2Value member = + CanonicalGameplayIssuerMemberV2Codec.decode(memberBytes); + byte[] bindingRef = requireBytes(row, "binding_ref"); + if (!Arrays.equals(bindingRef, requireBytes(row, "inventory_binding_ref")) + || !member.owner().tenantId().equals(tenantId) + || !member.owner().playableStateNamespaceId().equals(namespaceId) + || !member.owner().accountId().equals(assignment.accountId()) + || !Arrays.equals(member.owner().bindingRef().bytes(), bindingRef) + || !member.sourceCheckpoint().issuerId().equals(ISSUER) + || !member.sourceCheckpoint().issuerAuthGeneration() + .equals(current.accountCheckpoint().issuerAuthGeneration()) + || !Arrays.equals( + member.sourceCheckpoint().exactCheckpointBytes(), + current.accountCheckpoint().exactCheckpointBytes()) + || !Objects.equals( + member.sourceCheckpoint().latestIssuerEventDigest(), + current.accountCheckpoint().latestIssuerEventDigest()) + || !Arrays.equals( + CanonicalGameplayIssuerInstalledAnchor.encodeIncarnation(member.incarnation()), + CanonicalGameplayIssuerInstalledAnchor.encodeIncarnation(current.incarnation()))) { + throw conflict("Current local operation differs from the Account or incarnation source"); + } + + return new CurrentRequestTarget( + transitionId, tenantId, namespaceId, assignment.accountId(), bindingRef); + } + + private CanonicalGameplayAdmissionBarrierTuple buildOriginalInitializer( + DSLContext transaction, + UUID operationId, + CurrentRequestTarget expected, + CanonicalGameplayTenantGameplayTagRepository.Assignment assignment, + CanonicalGameplayIssuerInstalledAnchor anchor, + CanonicalGameplayIssuerAdmissionControlValue control, + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState current) { + Record row = + transaction.fetchOne( + "SELECT op.transition_id, op.binding_ref, to_jsonb(t)::text AS registered_target_json," + + " to_jsonb(r)::text AS reservation_json" + + " FROM " + LOCAL_OPERATION + " op" + + " JOIN game_session_canonical_binding_transition t ON t.transition_id = op.transition_id" + + " JOIN game_session_canonical_gameplay_binding_inventory i" + + " ON i.binding_ref = op.binding_ref AND i.transition_id = op.transition_id" + + " JOIN game_session_canonical_issuer_partition_reservation r" + + " ON r.reservation_id = op.reservation_id AND r.transition_id = op.transition_id" + + " WHERE op.operation_id = ? AND op.issuer_id = ?" + + " FOR UPDATE OF op, t, i, r", + operationId, + ISSUER); + if (row == null + || !expected.transitionId().equals(requiredUuid(row, "transition_id")) + || !Arrays.equals(expected.bindingRef(), requireBytes(row, "binding_ref"))) { + throw conflict("Current issuer NEW target changed before its original initializer was captured"); + } + byte[] reservationBytes = + requireText(row, "reservation_json").getBytes(StandardCharsets.UTF_8); + byte[] targetBytes = + requireText(row, "registered_target_json").getBytes(StandardCharsets.UTF_8); + CanonicalGameplayIssuerAdmissionBarrierValue.Initializer initializer = + new CanonicalGameplayIssuerAdmissionBarrierValue.Initializer( + ISSUER, + expected.tenantId(), + expected.namespaceId(), + assignment.tenantGameplayTag(), + operationId, + control.liveBarrierEpoch(), + expected.transitionId(), + expected.accountId(), + expected.bindingRef(), + reservationBytes, + CanonicalGameplayIssuerAdmissionBarrierValue.sha256(reservationBytes), + anchor.exactAnchorBytes(), + anchor.exactAnchorDigest(), + current.accountCheckpoint().issuerAuthGeneration(), + current.accountCheckpoint().exactCheckpointBytes(), + current.accountCheckpoint().checkpointDigest(), + current.accountCheckpoint().latestIssuerEventBytes(), + current.accountCheckpoint().latestIssuerEventDigest(), + CanonicalGameplayIssuerInstalledAnchor.encodeIncarnation(current.incarnation()), + CanonicalGameplayIssuerMemberV2Codec.sha256( + CanonicalGameplayIssuerInstalledAnchor.encodeIncarnation(current.incarnation())), + targetBytes, + CanonicalGameplayIssuerAdmissionBarrierValue.sha256(targetBytes)); + return new CanonicalGameplayAdmissionBarrierTuple(initializer); + } + + private CanonicalGameplayIssuerAdmissionBarrierValue readFrozenInitializer( + DSLContext transaction, + Record row, + CanonicalGameplayTenantGameplayTagRepository.Assignment expectedTarget, + CanonicalGameplayIssuerInstalledAnchor anchor, + CanonicalGameplayIssuerAdmissionControlValue control, + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState current) { + if (row == null) throw conflict("The durable original tenant initializer is missing"); + byte[] payload = requireBytes(row, "open_payload_bytes"); + CanonicalGameplayIssuerAdmissionBarrierValue value = + CanonicalGameplayIssuerAdmissionBarrierValue.decode(payload); + CanonicalGameplayIssuerAdmissionBarrierValue.Initializer initializer = value.initializer(); + requirePersistedInitializer(row, value); + String state = row.get("initialization_state", String.class); + if (initializer == null + || value.state() != CanonicalGameplayIssuerAdmissionBarrierValue.State.OPEN + || !initializer.operationId().equals(row.get("operation_id", UUID.class)) + || !initializer.issuerId().equals(row.get("issuer_id", String.class)) + || !control.liveBarrierEpoch().equals(initializer.admissionEpoch()) + || !initializer.matchesCurrentIssuerState(current) + || !Arrays.equals(initializer.anchorBytes(), anchor.exactAnchorBytes()) + || !initializer.anchorDigest().equals(anchor.exactAnchorDigest()) + || !List.of("PREPARED", "INITIALIZING", "OPEN_CONFIRMED").contains(state)) { + throw conflict("Frozen tenant initializer differs from current positive source and control"); + } + requireCurrentTagMapping( + transaction, initializer.tenantId(), initializer.tenantGameplayTag()); + if (expectedTarget != null) requireSameTargetAssignment(expectedTarget, initializer); + return value; + } + + private static void requireCurrentTagMapping( + DSLContext transaction, UUID tenantId, String expectedTag) { + Record mapping = + transaction.fetchOne( + "SELECT allocation_version, tenant_gameplay_tag FROM " + TENANT_TAG + + " WHERE tenant_id = ? FOR SHARE", + tenantId); + Integer version = mapping == null ? null : mapping.get("allocation_version", Integer.class); + String tag = mapping == null ? null : mapping.get("tenant_gameplay_tag", String.class); + if (version == null + || version <= 0 + || tag == null + || !tag.equals(expectedTag) + || !tag.equals("g" + version + "-" + tenantId.toString().replace("-", ""))) { + throw conflict("Frozen issuer target has no exact current SQL tenant gameplay-tag mapping"); + } + } + + private static void persistOriginalInitializer( + DSLContext transaction, CanonicalGameplayIssuerAdmissionBarrierValue value) { + CanonicalGameplayIssuerAdmissionBarrierValue.Initializer initializer = value.initializer(); + Record prior = + transaction.fetchOne( + "SELECT * FROM " + INITIALIZER + " WHERE operation_id = ? AND issuer_id = ? FOR UPDATE", + initializer.operationId(), + ISSUER); + if (prior != null) { + requirePersistedInitializer(prior, value); + return; + } + int inserted = + transaction.execute( + "INSERT INTO " + INITIALIZER + + " (operation_id, issuer_id, tenant_id, playable_state_namespace_id," + + " tenant_gameplay_tag, live_barrier_epoch, initialization_state," + + " initializer_exact_bytes," + + " initializer_digest, open_payload_bytes, open_payload_digest)" + + " VALUES (?, ?, ?, ?, ?, ?, 'PREPARED', ?, ?, ?, ?)", + initializer.operationId(), + initializer.issuerId(), + initializer.tenantId(), + initializer.playableStateNamespaceId(), + initializer.tenantGameplayTag(), + initializer.admissionEpoch(), + initializer.exactBytes(), + initializer.exactDigest(), + value.exactBytes(), + value.exactDigest()); + if (inserted != 1) throw conflict("Original issuer initializer did not persist before OPEN"); + Record saved = + transaction.fetchOne( + "SELECT * FROM " + INITIALIZER + " WHERE operation_id = ? AND issuer_id = ? FOR UPDATE", + initializer.operationId(), + ISSUER); + requirePersistedInitializer(saved, value); + } + + private static void requirePersistedInitializer( + Record row, CanonicalGameplayIssuerAdmissionBarrierValue expected) { + if (row == null + || !expected.issuerId().equals(row.get("issuer_id", String.class)) + || !expected.tenantId().equals(row.get("tenant_id", UUID.class)) + || !expected.playableStateNamespaceId().equals( + row.get("playable_state_namespace_id", UUID.class)) + || !expected.tenantGameplayTag().equals(row.get("tenant_gameplay_tag", String.class)) + || !expected.admissionEpoch().equals(readBigInteger(row, "live_barrier_epoch")) + || !Arrays.equals( + expected.initializer().exactBytes(), requireBytes(row, "initializer_exact_bytes")) + || !expected.initializer().exactDigest().equals(row.get("initializer_digest", String.class)) + || !Arrays.equals(expected.exactBytes(), requireBytes(row, "open_payload_bytes")) + || !expected.exactDigest().equals(row.get("open_payload_digest", String.class))) { + throw conflict("Persisted original issuer initializer differs from its exact retry source"); + } + } + + private CanonicalGameplayIssuerAdmissionBarrierRedisOwner.PreparedInitializer prepared( + CanonicalGameplayIssuerAdmissionBarrierValue value, + CanonicalGameplayTenantGameplayTagRepository.Assignment assignment, + UUID requestOperationId, + boolean createPermit) { + return new CanonicalGameplayIssuerAdmissionBarrierRedisOwner.PreparedInitializer( + value, + assignment, + requestOperationId, + CanonicalGameplayIssuerAdmissionBarrierKey.forTarget( + ISSUER, + value.tenantId(), + value.playableStateNamespaceId(), + value.tenantGameplayTag()), + createPermit); + } + + /** + * Consumes the sole durable authority to create the first Redis OPEN. The state transition is + * committed before the Redis owner can attempt its command; every later call is replay-only. + */ + private boolean claimFirstCreatePermit( + UUID operationId, + CanonicalGameplayIssuerAdmissionBarrierValue value, + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState current) { + return dsl.transactionResult( + configuration -> { + DSLContext transaction = DSL.using(configuration); + CanonicalGameplayBindingInventoryRepository.lockInventoryRevision(transaction); + CanonicalGameplayIssuerInstalledAnchor anchor = + CanonicalGameplayIssuerBootstrapCoverageRepository + .readInstalledAnchorForBindingPreparationInTransaction(transaction, current); + CanonicalGameplayIssuerAdmissionControlValue control = + CanonicalGameplayIssuerAdmissionControlRepository.requireOpenInTransaction( + transaction, anchor, current); + if (!control.liveBarrierEpoch().equals(value.admissionEpoch()) + || !control.currentOperationId().equals(anchor.bootstrapOperationId())) { + throw conflict("Original initializer no longer belongs to the current OPEN live control"); + } + Record saved = + transaction.fetchOne( + "SELECT * FROM " + INITIALIZER + + " WHERE operation_id = ? AND issuer_id = ? FOR UPDATE", + operationId, + ISSUER); + requirePersistedInitializer(saved, value); + String state = saved.get("initialization_state", String.class); + if ("PREPARED".equals(state)) { + Record origin = + transaction.fetchOne( + "SELECT transition.status AS transition_status FROM " + LOCAL_OPERATION + + " operation JOIN game_session_canonical_binding_transition transition" + + " ON transition.transition_id = operation.transition_id" + + " WHERE operation.operation_id = ? AND operation.issuer_id = ?" + + " FOR SHARE OF operation, transition", + operationId, + ISSUER); + if (origin == null) { + throw conflict("Original initializer lost its persisted local-operation provenance"); + } + if ("ABORTED".equals(origin.get("transition_status", String.class))) { + return false; + } + if (!List.of("PROVISIONAL", "COMMITTED") + .contains(origin.get("transition_status", String.class))) { + throw conflict("Original initializer source is no longer an eligible first NEW"); + } + int claimed = + transaction.execute( + "UPDATE " + INITIALIZER + + " SET initialization_state = 'INITIALIZING'" + + " WHERE operation_id = ? AND issuer_id = ?" + + " AND initialization_state = 'PREPARED'", + operationId, + ISSUER); + if (claimed != 1) { + throw conflict("Original initializer first-create permit was not uniquely claimed"); + } + return true; + } + if ("INITIALIZING".equals(state) || "OPEN_CONFIRMED".equals(state)) return false; + throw conflict("Original initializer has an unknown or non-admitting durable state"); + }); + } + + private UUID transitionForLocalOperation(UUID operationId) { + Record row = + dsl.fetchOne( + "SELECT transition_id FROM " + LOCAL_OPERATION + + " WHERE operation_id = ? AND issuer_id = ?", + operationId, + ISSUER); + if (row == null) throw conflict("The exact original issuer local operation is unavailable"); + return requiredUuid(row, "transition_id"); + } + + private CanonicalGameplayIssuerInstalledAnchor readInstalledAnchor( + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState current) { + return dsl.transactionResult( + configuration -> { + DSLContext transaction = DSL.using(configuration); + CanonicalGameplayBindingInventoryRepository.lockInventoryRevision(transaction); + return CanonicalGameplayIssuerBootstrapCoverageRepository + .readInstalledAnchorForBindingPreparationInTransaction(transaction, current); + }); + } + + private CanonicalGameplayIssuerAdmissionControlValue readCurrentControl( + DSLContext transaction, + CanonicalGameplayIssuerInstalledAnchor anchor, + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState current) { + Record row = + transaction.fetchOne( + "SELECT * FROM " + CONTROL + " WHERE issuer_id = ? FOR UPDATE", ISSUER); + if (row == null) throw conflict("The positive live issuer admission-control row is missing"); + CanonicalGameplayIssuerAdmissionControlValue value = + CanonicalGameplayIssuerAdmissionControlValue.decode(requireBytes(row, "control_exact_bytes")); + if (!CanonicalGameplayIssuerAdmissionControlValue.sha256(value.exactBytes()) + .equals(row.get("control_exact_digest", String.class)) + || !value.issuerId().equals(row.get("issuer_id", String.class)) + || !value.matchesCurrentIssuerState(current) + || !Arrays.equals(value.anchorExactBytes(), anchor.exactAnchorBytes()) + || !value.anchorExactDigest().equals(anchor.exactAnchorDigest())) { + throw conflict("Issuer control differs from its exact installed anchor and fresh current source"); + } + return value; + } + + private CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState readCurrentState() { + try { + return Objects.requireNonNull( + currentStateSource.readFreshCurrentState(), "Current issuer source returned null"); + } catch (RuntimeException failure) { + throw conflict("Current Account issuer source or stable incarnation is unavailable"); + } + } + + private static void requireSameAssignment( + CanonicalGameplayTenantGameplayTagRepository.Assignment expected, + CanonicalGameplayTenantGameplayTagRepository.Assignment actual) { + if (!expected.tenantId().equals(actual.tenantId()) + || !expected.accountId().equals(actual.accountId()) + || !expected.playableStateNamespaceId().equals(actual.playableStateNamespaceId()) + || !expected.tenantGameplayTag().equals(actual.tenantGameplayTag()) + || !Objects.equals(expected.transitionId(), actual.transitionId())) { + throw conflict("Current tenant target assignment differs from the exact durable original"); + } + } + + private static void requireSameTargetAssignment( + CanonicalGameplayTenantGameplayTagRepository.Assignment expected, + CanonicalGameplayIssuerAdmissionBarrierValue.Initializer actual) { + if (!expected.tenantId().equals(actual.tenantId()) + || !expected.playableStateNamespaceId().equals(actual.playableStateNamespaceId()) + || !expected.tenantGameplayTag().equals(actual.tenantGameplayTag())) { + throw conflict("Fresh NEW request scope differs from the frozen tenant initializer target"); + } + } + + private static byte[] requireBytes(Record row, String field) { + byte[] value = row == null ? null : row.get(field, byte[].class); + if (value == null) throw conflict("Persisted issuer admission bytes are missing: " + field); + return value.clone(); + } + + private static UUID requiredUuid(Record row, String field) { + UUID value = row == null ? null : row.get(field, UUID.class); + if (value == null) throw conflict("Persisted issuer admission UUID is missing: " + field); + return value; + } + + private static String requireText(Record row, String field) { + String value = row == null ? null : row.get(field, String.class); + if (value == null) throw conflict("Persisted issuer admission text is missing: " + field); + return value; + } + + private static BigInteger readBigInteger(Record row, String field) { + java.math.BigDecimal value = row == null ? null : row.get(field, java.math.BigDecimal.class); + if (value == null) throw conflict("Persisted issuer admission integer is missing: " + field); + try { + return value.toBigIntegerExact(); + } catch (ArithmeticException malformed) { + throw conflict("Persisted issuer admission integer is malformed: " + field); + } + } + + private static void requireNonNil(UUID value, String name) { + if (value == null || value.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException(name + " must be a non-nil UUID"); + } + } + + private void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw conflict("Issuer tenant barrier owner cannot join an ambient SQL transaction"); + } + try { + dsl.connectionResult( + connection -> { + if (!connection.getAutoCommit()) { + throw conflict("Issuer tenant barrier owner cannot join a jOOQ transaction"); + } + return Boolean.TRUE; + }); + } catch (RuntimeException failure) { + if (failure instanceof CanonicalGameplayBindingInventoryConflictException) throw failure; + throw new CanonicalGameplayBindingInventoryConflictException( + "Issuer tenant barrier SQL connection state is unavailable", failure); + } + } + + private static CanonicalGameplayBindingInventoryConflictException conflict(String message) { + return new CanonicalGameplayBindingInventoryConflictException(message); + } + + private record CanonicalGameplayAdmissionBarrierTuple( + CanonicalGameplayIssuerAdmissionBarrierValue.Initializer initializer) {} + + private record PreparedInitializerSource( + CanonicalGameplayIssuerAdmissionBarrierValue value, + CanonicalGameplayTenantGameplayTagRepository.Assignment requestAssignment) {} + + private record CurrentRequestTarget( + UUID transitionId, + UUID tenantId, + UUID namespaceId, + UUID accountId, + byte[] bindingRef) { + private CurrentRequestTarget { + Objects.requireNonNull(transitionId, "transitionId"); + Objects.requireNonNull(tenantId, "tenantId"); + Objects.requireNonNull(namespaceId, "namespaceId"); + Objects.requireNonNull(accountId, "accountId"); + bindingRef = Objects.requireNonNull(bindingRef, "bindingRef").clone(); + } + + @Override + public byte[] bindingRef() { + return bindingRef.clone(); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierValue.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierValue.java new file mode 100644 index 0000000000..c63c0cfa52 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierValue.java @@ -0,0 +1,558 @@ +package net.firedevops.firemud.gamesession.repository; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.math.BigInteger; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.util.Arrays; +import java.util.HexFormat; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; + +/** Exact tenant-local issuer admission barrier payload; it is not an issuer-wide proof. */ +final class CanonicalGameplayIssuerAdmissionBarrierValue { + static final String SCHEMA = "gs_issuer_admission_barrier/v1"; + static final int MAX_BYTES = 512 * 1024; + private static final String TARGET_ENCODING = "canonical-issuer-admission-target/v1"; + private static final String VALUE_ENCODING = "canonical-issuer-admission-barrier/v1"; + + enum State { + OPEN, + CLOSED + } + + /** Full immutable initializer source retained by OPEN and any later CLOSED value. */ + static final class Initializer { + private final String issuerId; + private final UUID tenantId; + private final UUID playableStateNamespaceId; + private final String tenantGameplayTag; + private final UUID operationId; + private final BigInteger admissionEpoch; + private final UUID transitionId; + private final UUID accountId; + private final byte[] bindingRefBytes; + private final byte[] reservationBytes; + private final String reservationDigest; + private final byte[] anchorBytes; + private final String anchorDigest; + private final BigInteger accountIssuerAuthGeneration; + private final byte[] accountCheckpointBytes; + private final String accountCheckpointDigest; + private final byte[] accountSourceEventBytes; + private final String accountSourceEventDigest; + private final byte[] incarnationBytes; + private final String incarnationDigest; + private final byte[] registeredTargetBytes; + private final String registeredTargetDigest; + private final byte[] exactBytes; + private final String exactDigest; + + Initializer( + String issuerId, + UUID tenantId, + UUID playableStateNamespaceId, + String tenantGameplayTag, + UUID operationId, + BigInteger admissionEpoch, + UUID transitionId, + UUID accountId, + byte[] bindingRefBytes, + byte[] reservationBytes, + String reservationDigest, + byte[] anchorBytes, + String anchorDigest, + BigInteger accountIssuerAuthGeneration, + byte[] accountCheckpointBytes, + String accountCheckpointDigest, + byte[] accountSourceEventBytes, + String accountSourceEventDigest, + byte[] incarnationBytes, + String incarnationDigest, + byte[] registeredTargetBytes, + String registeredTargetDigest) { + this.issuerId = requireIssuer(issuerId); + this.tenantId = requireNonNil(tenantId, "tenantId"); + this.playableStateNamespaceId = + requireNonNil(playableStateNamespaceId, "playableStateNamespaceId"); + this.tenantGameplayTag = requireTag(tenantGameplayTag); + this.operationId = requireNonNil(operationId, "operationId"); + this.admissionEpoch = requirePositive(admissionEpoch, "admissionEpoch"); + this.transitionId = requireNonNil(transitionId, "transitionId"); + this.accountId = requireNonNil(accountId, "accountId"); + this.bindingRefBytes = nonEmpty(bindingRefBytes, "bindingRefBytes"); + this.reservationBytes = nonEmpty(reservationBytes, "reservationBytes"); + this.reservationDigest = requireDigest(reservationDigest, "reservationDigest"); + requireDigestMatches(this.reservationBytes, this.reservationDigest, "reservation"); + this.anchorBytes = nonEmpty(anchorBytes, "anchorBytes"); + this.anchorDigest = requireDigest(anchorDigest, "anchorDigest"); + requireDigestMatches(this.anchorBytes, this.anchorDigest, "installed anchor"); + this.accountIssuerAuthGeneration = + requirePositive(accountIssuerAuthGeneration, "accountIssuerAuthGeneration"); + this.accountCheckpointBytes = nonEmpty(accountCheckpointBytes, "accountCheckpointBytes"); + this.accountCheckpointDigest = + requireDigest(accountCheckpointDigest, "accountCheckpointDigest"); + requireDigestMatches( + this.accountCheckpointBytes, this.accountCheckpointDigest, "Account checkpoint"); + if ((accountSourceEventBytes == null) != (accountSourceEventDigest == null)) { + throw new IllegalArgumentException("Account source event bytes and digest must be paired"); + } + this.accountSourceEventBytes = + accountSourceEventBytes == null + ? null + : nonEmpty(accountSourceEventBytes, "accountSourceEventBytes"); + this.accountSourceEventDigest = + accountSourceEventDigest == null + ? null + : requireDigest(accountSourceEventDigest, "accountSourceEventDigest"); + if (this.accountSourceEventBytes != null) { + requireDigestMatches( + this.accountSourceEventBytes, this.accountSourceEventDigest, "Account source event"); + } + this.incarnationBytes = nonEmpty(incarnationBytes, "incarnationBytes"); + this.incarnationDigest = requireDigest(incarnationDigest, "incarnationDigest"); + requireDigestMatches(this.incarnationBytes, this.incarnationDigest, "incarnation"); + this.registeredTargetBytes = nonEmpty(registeredTargetBytes, "registeredTargetBytes"); + this.registeredTargetDigest = + requireDigest(registeredTargetDigest, "registeredTargetDigest"); + requireDigestMatches( + this.registeredTargetBytes, this.registeredTargetDigest, "registered target"); + long boundedBytes = + (long) this.bindingRefBytes.length + + this.reservationBytes.length + + this.anchorBytes.length + + this.accountCheckpointBytes.length + + (this.accountSourceEventBytes == null ? 0 : this.accountSourceEventBytes.length) + + this.incarnationBytes.length + + this.registeredTargetBytes.length + + 16_384L; + if (boundedBytes > MAX_BYTES) { + throw new IllegalArgumentException("Issuer initializer tuple exceeds its encoded bound"); + } + this.exactBytes = encodeTarget(); + this.exactDigest = sha256(this.exactBytes); + if (this.exactBytes.length > MAX_BYTES) { + throw new IllegalArgumentException("Issuer initializer tuple exceeds its encoded bound"); + } + } + + private byte[] encodeTarget() { + return encode( + out -> { + writeText(out, TARGET_ENCODING); + writeText(out, issuerId); + writeUuid(out, tenantId); + writeUuid(out, playableStateNamespaceId); + writeText(out, tenantGameplayTag); + writeUuid(out, operationId); + writeBigInteger(out, admissionEpoch); + writeUuid(out, transitionId); + writeUuid(out, accountId); + writeBytes(out, bindingRefBytes); + writeBytes(out, reservationBytes); + writeText(out, reservationDigest); + writeBytes(out, anchorBytes); + writeText(out, anchorDigest); + writeBigInteger(out, accountIssuerAuthGeneration); + writeBytes(out, accountCheckpointBytes); + writeText(out, accountCheckpointDigest); + writeNullableBytes(out, accountSourceEventBytes); + writeNullableText(out, accountSourceEventDigest); + writeBytes(out, incarnationBytes); + writeText(out, incarnationDigest); + writeBytes(out, registeredTargetBytes); + writeText(out, registeredTargetDigest); + }); + } + + private static Initializer decode(byte[] bytes) { + if (bytes == null || bytes.length == 0 || bytes.length > MAX_BYTES) throw malformed(); + try (DataInputStream in = new DataInputStream(new ByteArrayInputStream(bytes))) { + if (!TARGET_ENCODING.equals(readText(in))) throw malformed(); + Initializer result = + new Initializer( + readText(in), + readUuid(in), + readUuid(in), + readText(in), + readUuid(in), + readPositive(in), + readUuid(in), + readUuid(in), + readBytes(in), + readBytes(in), + readText(in), + readBytes(in), + readText(in), + readPositive(in), + readBytes(in), + readText(in), + readNullableBytes(in), + readNullableText(in), + readBytes(in), + readText(in), + readBytes(in), + readText(in)); + if (in.available() != 0 || !Arrays.equals(bytes, result.exactBytes())) throw malformed(); + return result; + } catch (IOException | RuntimeException invalid) { + throw malformed(); + } + } + + String issuerId() { return issuerId; } + UUID tenantId() { return tenantId; } + UUID playableStateNamespaceId() { return playableStateNamespaceId; } + String tenantGameplayTag() { return tenantGameplayTag; } + UUID operationId() { return operationId; } + BigInteger admissionEpoch() { return admissionEpoch; } + UUID transitionId() { return transitionId; } + UUID accountId() { return accountId; } + byte[] bindingRefBytes() { return bindingRefBytes.clone(); } + byte[] reservationBytes() { return reservationBytes.clone(); } + String reservationDigest() { return reservationDigest; } + byte[] anchorBytes() { return anchorBytes.clone(); } + String anchorDigest() { return anchorDigest; } + BigInteger accountIssuerAuthGeneration() { return accountIssuerAuthGeneration; } + byte[] accountCheckpointBytes() { return accountCheckpointBytes.clone(); } + String accountCheckpointDigest() { return accountCheckpointDigest; } + byte[] accountSourceEventBytes() { + return accountSourceEventBytes == null ? null : accountSourceEventBytes.clone(); + } + String accountSourceEventDigest() { return accountSourceEventDigest; } + byte[] incarnationBytes() { return incarnationBytes.clone(); } + String incarnationDigest() { return incarnationDigest; } + byte[] registeredTargetBytes() { return registeredTargetBytes.clone(); } + String registeredTargetDigest() { return registeredTargetDigest; } + byte[] exactBytes() { return exactBytes.clone(); } + String exactDigest() { return exactDigest; } + + boolean matchesCurrentIssuerState( + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState current) { + Objects.requireNonNull(current, "current"); + var checkpoint = current.accountCheckpoint(); + return issuerId.equals(checkpoint.issuerId()) + && accountIssuerAuthGeneration.equals(checkpoint.issuerAuthGeneration()) + && Arrays.equals(accountCheckpointBytes, checkpoint.exactCheckpointBytes()) + && accountCheckpointDigest.equals(checkpoint.checkpointDigest()) + && Arrays.equals(accountSourceEventBytes, checkpoint.latestIssuerEventBytes()) + && Objects.equals(accountSourceEventDigest, checkpoint.latestIssuerEventDigest()) + && Arrays.equals( + incarnationBytes, + CanonicalGameplayIssuerInstalledAnchor.encodeIncarnation(current.incarnation())); + } + } + + private final String issuerId; + private final UUID tenantId; + private final UUID playableStateNamespaceId; + private final String tenantGameplayTag; + private final State state; + private final BigInteger admissionEpoch; + private final UUID ownerOperationId; + private final Initializer initializer; + private final byte[] exactBytes; + private final String exactDigest; + + private CanonicalGameplayIssuerAdmissionBarrierValue( + String issuerId, + UUID tenantId, + UUID playableStateNamespaceId, + String tenantGameplayTag, + State state, + BigInteger admissionEpoch, + UUID ownerOperationId, + Initializer initializer) { + this.issuerId = requireIssuer(issuerId); + this.tenantId = requireNonNil(tenantId, "tenantId"); + this.playableStateNamespaceId = + requireNonNil(playableStateNamespaceId, "playableStateNamespaceId"); + this.tenantGameplayTag = requireTag(tenantGameplayTag); + this.state = Objects.requireNonNull(state, "state"); + this.admissionEpoch = requirePositive(admissionEpoch, "admissionEpoch"); + this.ownerOperationId = requireNonNil(ownerOperationId, "ownerOperationId"); + this.initializer = initializer; + if (initializer != null + && (!this.issuerId.equals(initializer.issuerId()) + || !this.tenantId.equals(initializer.tenantId()) + || !this.playableStateNamespaceId.equals(initializer.playableStateNamespaceId()) + || !this.tenantGameplayTag.equals(initializer.tenantGameplayTag()))) { + throw new IllegalArgumentException("Barrier initializer belongs to a different target"); + } + if (state == State.OPEN + && (initializer == null + || !ownerOperationId.equals(initializer.operationId()) + || !admissionEpoch.equals(initializer.admissionEpoch()))) { + throw new IllegalArgumentException("OPEN requires its exact original initializer tuple"); + } + if (state == State.CLOSED + && initializer != null + && (admissionEpoch.compareTo(initializer.admissionEpoch()) <= 0 + || ownerOperationId.equals(initializer.operationId()))) { + throw new IllegalArgumentException("CLOSED must advance past a captured initializer epoch"); + } + this.exactBytes = encodeValue(); + this.exactDigest = sha256(this.exactBytes); + if (this.exactBytes.length > MAX_BYTES) { + throw new IllegalArgumentException("Issuer admission barrier exceeds its encoded bound"); + } + } + + static CanonicalGameplayIssuerAdmissionBarrierValue open(Initializer initializer) { + Objects.requireNonNull(initializer, "initializer"); + return new CanonicalGameplayIssuerAdmissionBarrierValue( + initializer.issuerId(), + initializer.tenantId(), + initializer.playableStateNamespaceId(), + initializer.tenantGameplayTag(), + State.OPEN, + initializer.admissionEpoch(), + initializer.operationId(), + initializer); + } + + static CanonicalGameplayIssuerAdmissionBarrierValue closed( + String issuerId, + UUID tenantId, + UUID playableStateNamespaceId, + String tenantGameplayTag, + BigInteger cutoffEpoch, + UUID cutoffOperationId, + Initializer capturedInitializer) { + return new CanonicalGameplayIssuerAdmissionBarrierValue( + issuerId, + tenantId, + playableStateNamespaceId, + tenantGameplayTag, + State.CLOSED, + cutoffEpoch, + cutoffOperationId, + capturedInitializer); + } + + static CanonicalGameplayIssuerAdmissionBarrierValue decode(byte[] bytes) { + if (bytes == null || bytes.length == 0 || bytes.length > MAX_BYTES) throw malformed(); + try (DataInputStream in = new DataInputStream(new ByteArrayInputStream(bytes))) { + if (!VALUE_ENCODING.equals(readText(in))) throw malformed(); + String issuerId = readText(in); + UUID tenantId = readUuid(in); + UUID namespaceId = readUuid(in); + String tag = readText(in); + State state = State.valueOf(readText(in)); + BigInteger epoch = readPositive(in); + UUID ownerOperationId = readUuid(in); + byte[] initializerBytes = readNullableBytes(in); + String initializerDigest = readNullableText(in); + Initializer initializer = null; + if (initializerBytes != null) { + initializer = Initializer.decode(initializerBytes); + if (!initializer.exactDigest().equals(initializerDigest)) throw malformed(); + } else if (initializerDigest != null) { + throw malformed(); + } + CanonicalGameplayIssuerAdmissionBarrierValue result = + new CanonicalGameplayIssuerAdmissionBarrierValue( + issuerId, + tenantId, + namespaceId, + tag, + state, + epoch, + ownerOperationId, + initializer); + if (in.available() != 0 || !Arrays.equals(bytes, result.exactBytes())) throw malformed(); + return result; + } catch (IOException | RuntimeException invalid) { + throw malformed(); + } + } + + private byte[] encodeValue() { + return encode( + out -> { + writeText(out, VALUE_ENCODING); + writeText(out, issuerId); + writeUuid(out, tenantId); + writeUuid(out, playableStateNamespaceId); + writeText(out, tenantGameplayTag); + writeText(out, state.name()); + writeBigInteger(out, admissionEpoch); + writeUuid(out, ownerOperationId); + writeNullableBytes(out, initializer == null ? null : initializer.exactBytes()); + writeNullableText(out, initializer == null ? null : initializer.exactDigest()); + }); + } + + String issuerId() { return issuerId; } + UUID tenantId() { return tenantId; } + UUID playableStateNamespaceId() { return playableStateNamespaceId; } + String tenantGameplayTag() { return tenantGameplayTag; } + State state() { return state; } + BigInteger admissionEpoch() { return admissionEpoch; } + UUID ownerOperationId() { return ownerOperationId; } + Initializer initializer() { return initializer; } + byte[] exactBytes() { return exactBytes.clone(); } + String exactDigest() { return exactDigest; } + + static String sha256(byte[] bytes) { + try { + return "sha256:" + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (Exception failure) { + throw new IllegalStateException("Could not digest exact issuer admission bytes", failure); + } + } + + private static byte[] encode(Writer writer) { + try { + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + try (DataOutputStream output = new DataOutputStream(bytes)) { + writer.write(output); + } + return bytes.toByteArray(); + } catch (IOException impossible) { + throw new IllegalStateException("Could not encode exact issuer admission bytes", impossible); + } + } + + private static void writeText(DataOutputStream out, String value) throws IOException { + byte[] bytes = Objects.requireNonNull(value, "text").getBytes(StandardCharsets.UTF_8); + writeBytes(out, bytes); + } + + private static void writeBigInteger(DataOutputStream out, BigInteger value) throws IOException { + writeText(out, requirePositive(value, "counter").toString()); + } + + private static void writeUuid(DataOutputStream out, UUID value) throws IOException { + writeText(out, requireNonNil(value, "uuid").toString()); + } + + private static void writeBytes(DataOutputStream out, byte[] value) throws IOException { + if (value.length > MAX_BYTES) throw new IllegalArgumentException("Byte field exceeds bound"); + out.writeInt(value.length); + out.write(value); + } + + private static void writeNullableBytes(DataOutputStream out, byte[] value) throws IOException { + out.writeBoolean(value != null); + if (value != null) writeBytes(out, value); + } + + private static void writeNullableText(DataOutputStream out, String value) throws IOException { + out.writeBoolean(value != null); + if (value != null) writeText(out, value); + } + + private static String readText(DataInputStream in) throws IOException { + return decodeUtf8(readBytes(in)); + } + + private static byte[] readBytes(DataInputStream in) throws IOException { + int length = in.readInt(); + if (length < 1 || length > MAX_BYTES || length > in.available()) throw malformed(); + return in.readNBytes(length); + } + + private static byte[] readNullableBytes(DataInputStream in) throws IOException { + return in.readBoolean() ? readBytes(in) : null; + } + + private static String readNullableText(DataInputStream in) throws IOException { + return in.readBoolean() ? readText(in) : null; + } + + private static UUID readUuid(DataInputStream in) throws IOException { + String text = readText(in); + UUID value; + try { + value = UUID.fromString(text); + } catch (IllegalArgumentException invalid) { + throw malformed(); + } + if (!value.toString().equals(text) || value.equals(new UUID(0L, 0L))) throw malformed(); + return value; + } + + private static BigInteger readPositive(DataInputStream in) throws IOException { + String text = readText(in); + if (!text.matches("[1-9][0-9]{0,255}")) throw malformed(); + return new BigInteger(text); + } + + private static String decodeUtf8(byte[] bytes) throws IOException { + try { + return StandardCharsets.UTF_8.newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(java.nio.ByteBuffer.wrap(bytes)) + .toString(); + } catch (CharacterCodingException invalid) { + throw malformed(); + } + } + + private static IllegalArgumentException malformed() { + return new IllegalArgumentException("Issuer admission barrier payload is malformed"); + } + + private static byte[] nonEmpty(byte[] value, String name) { + Objects.requireNonNull(value, name); + if (value.length == 0 || value.length > MAX_BYTES) { + throw new IllegalArgumentException(name + " is outside the exact payload bound"); + } + return value.clone(); + } + + private static UUID requireNonNil(UUID value, String name) { + Objects.requireNonNull(value, name); + if (value.equals(new UUID(0L, 0L))) throw new IllegalArgumentException(name + " must not be nil"); + return value; + } + + private static BigInteger requirePositive(BigInteger value, String name) { + Objects.requireNonNull(value, name); + if (value.signum() <= 0 || value.toString().length() > 256) { + throw new IllegalArgumentException(name + " must be a bounded positive integer"); + } + return value; + } + + private static String requireIssuer(String value) { + if (!GameSessionAccountDelegationProfile.ISSUER.equals(value)) { + throw new IllegalArgumentException("Issuer admission barrier requires the Account issuer"); + } + return value; + } + + private static String requireTag(String value) { + Objects.requireNonNull(value, "tenantGameplayTag"); + if (!value.matches("g[1-9][0-9]{0,9}-[0-9a-f]{32}")) { + throw new IllegalArgumentException("Issuer admission barrier requires an exact gameplay tag"); + } + return value; + } + + private static String requireDigest(String value, String name) { + Objects.requireNonNull(value, name); + if (!value.matches("sha256:[0-9a-f]{64}")) { + throw new IllegalArgumentException(name + " must be canonical SHA-256"); + } + return value; + } + + private static void requireDigestMatches(byte[] bytes, String digest, String name) { + if (!sha256(bytes).equals(digest)) throw new IllegalArgumentException(name + " digest differs"); + } + + @FunctionalInterface + private interface Writer { + void write(DataOutputStream output) throws IOException; + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionControlRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionControlRepository.java new file mode 100644 index 0000000000..be4c6957d5 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionControlRepository.java @@ -0,0 +1,1214 @@ +package net.firedevops.firemud.gamesession.repository; + +import java.math.BigInteger; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Arrays; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.HexFormat; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.impl.DSL; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** SQL owner for the positive, reset-sensitive live issuer admission-control row. */ +final class CanonicalGameplayIssuerAdmissionControlRepository { + private static final String ISSUER = GameSessionAccountDelegationProfile.ISSUER; + private static final String CONTROL = "game_session_canonical_issuer_admission_control"; + private static final String COUNTER = "game_session_canonical_issuer_admission_epoch_counter"; + private static final String OPERATION = "game_session_canonical_issuer_admission_operation"; + private static final String LAYOUT_CONTROL = "game_session_canonical_issuer_layout_bootstrap_control"; + private static final String ANCHOR = "game_session_canonical_issuer_installed_anchor"; + private static final String LOCAL_OPERATION = + "game_session_canonical_issuer_binding_local_operation"; + private static final String BOOTSTRAP_MEMBER_OPERATION = + "game_session_canonical_issuer_bootstrap_member_operation"; + private static final String COHORT = "game_session_canonical_issuer_admission_cohort_row"; + private static final String INITIALIZER = "game_session_canonical_issuer_admission_initializer"; + private static final String INITIALIZER_RECEIPT = + "game_session_canonical_issuer_admission_initializer_receipt"; + private static final String CUTOFF_TARGET = + "game_session_canonical_issuer_admission_cutoff_target"; + private static final String TENANT_TAG = "game_session_canonical_tenant_gameplay_tag"; + + private final DSLContext dsl; + + CanonicalGameplayIssuerAdmissionControlRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + } + + /** + * Positively installs the first live OPEN row from an already-qualified immutable anchor. The + * source and incarnation are controlled local observations, not authority produced here. + */ + CanonicalGameplayIssuerAdmissionControlValue installInitialOpen( + CanonicalGameplayIssuerInstalledAnchor anchor, + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerStateSource currentStateSource) { + Objects.requireNonNull(anchor, "anchor"); + Objects.requireNonNull(currentStateSource, "currentStateSource"); + requireNoAmbientTransaction(); + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState before = + Objects.requireNonNull(currentStateSource.readFreshCurrentState(), "current state source returned null"); + CanonicalGameplayIssuerAdmissionControlValue installed = + dsl.transactionResult( + configuration -> installInitialInTransaction(DSL.using(configuration), anchor, before)); + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState after = + Objects.requireNonNull(currentStateSource.readFreshCurrentState(), "current state source returned null after install"); + if (!installed.matchesCurrentIssuerState(after)) { + throw conflict("Current Account issuer source or stable incarnation moved during live-control installation"); + } + return installed; + } + + /** + * Freezes the complete current issuer cohort and advances the positive live-control epoch before + * any tenant-local CLOSED writes are attempted. Tenant keys come from the locked cohort and + * each key must have its exact positive current SQL tenant-tag mapping. + */ + CanonicalGameplayIssuerAdmissionControlValue beginCutoff( + UUID cutoffOperationId, + UUID requestId, + CanonicalGameplayIssuerInstalledAnchor anchor, + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState currentState) { + requireNonNil(cutoffOperationId, "cutoffOperationId"); + requireNonNil(requestId, "requestId"); + Objects.requireNonNull(anchor, "anchor"); + Objects.requireNonNull(currentState, "currentState"); + if (cutoffOperationId.equals(requestId)) { + throw conflict("Issuer cutoff operation and request identities must be distinct"); + } + requireNoAmbientTransaction(); + return dsl.transactionResult( + configuration -> { + DSLContext transaction = DSL.using(configuration); + BigInteger snapshotRevision = + CanonicalGameplayBindingInventoryRepository.lockInventoryRevision(transaction); + lockLayoutControl(transaction, anchor); + Record controlRow = + transaction.fetchOne( + "SELECT * FROM " + CONTROL + " WHERE issuer_id = ? FOR UPDATE", ISSUER); + if (controlRow == null) { + throw conflict("Issuer cutoff requires a positively installed live control row"); + } + CanonicalGameplayIssuerAdmissionControlValue control = loadControl(controlRow); + requireExactAnchorAndCurrentSource(control, anchor, currentState); + Record counter = + transaction.fetchOne( + "SELECT * FROM " + COUNTER + " WHERE issuer_id = ? FOR UPDATE", ISSUER); + if (counter == null) throw conflict("The positive live issuer epoch counter is missing"); + requireCounterMatchesCurrent(transaction, control.liveBarrierEpoch()); + + Record priorOperation = + transaction.fetchOne( + "SELECT * FROM " + OPERATION + " WHERE operation_id = ? FOR UPDATE", + cutoffOperationId); + if (control.state() == CanonicalGameplayIssuerAdmissionControlValue.State.CUTOFF_PENDING + && control.currentOperationId().equals(cutoffOperationId)) { + if (priorOperation == null + || !requestId.equals(uuid(priorOperation, "request_id")) + || !"CUTOFF".equals(text(priorOperation, "operation_kind")) + || !"CUTOFF_PENDING".equals(text(priorOperation, "operation_state"))) { + throw conflict("Issuer cutoff retry differs from its exact pending operation"); + } + verifyFrozenCohort(transaction, control); + verifyCutoffTargets(transaction, control); + return control; + } + if (control.state() != CanonicalGameplayIssuerAdmissionControlValue.State.OPEN + || control.currentOperationKind() + != CanonicalGameplayIssuerAdmissionControlValue.OperationKind.INITIAL_ANCHOR_INSTALL + || !control.currentOperationId().equals(anchor.bootstrapOperationId()) + || priorOperation != null) { + throw conflict("Issuer live control cannot be reset, reopened, or replaced by this cutoff"); + } + requireInitialOperationCurrent(transaction, control); + + List rows = captureCutoffCohort(transaction, snapshotRevision); + Map> targets = groupTargets(rows); + Map tagByTarget = new TreeMap<>(); + for (TargetScope scope : targets.keySet()) { + tagByTarget.put(scope, requireCurrentTenantTagMapping(transaction, scope.tenantId())); + } + + BigInteger priorEpoch = control.liveBarrierEpoch(); + Record allocated = + transaction.fetchOne( + "UPDATE " + COUNTER + + " SET last_live_barrier_epoch = last_live_barrier_epoch + 1," + + " updated_at = CURRENT_TIMESTAMP" + + " WHERE issuer_id = ? AND last_live_barrier_epoch = ?" + + " RETURNING last_live_barrier_epoch", + ISSUER, + priorEpoch); + if (allocated == null) { + throw conflict("Issuer cutoff lost its serialized live epoch allocation"); + } + BigInteger cutoffEpoch = integer(allocated, "last_live_barrier_epoch"); + String cohortDigest = digestCohort(rows); + CanonicalGameplayIssuerAdmissionControlValue pending = + control.cutoffPending( + cutoffOperationId, + cutoffEpoch, + snapshotRevision, + rows.size(), + cohortDigest); + insertCutoffOperation(transaction, pending, requestId, priorEpoch); + updateControl(transaction, pending, control.liveBarrierEpoch()); + insertCohortRows(transaction, pending.currentOperationId(), rows); + insertCutoffTargets( + transaction, + pending, + targets, + tagByTarget); + verifyFrozenCohort(transaction, pending); + verifyCutoffTargets(transaction, pending); + return pending; + }); + } + + /** Publishes INSTALLED only after every captured tenant target has an exact CLOSED readback. */ + CanonicalGameplayIssuerAdmissionControlValue completeCutoff( + UUID cutoffOperationId, + CanonicalGameplayIssuerInstalledAnchor anchor, + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState currentState) { + requireNonNil(cutoffOperationId, "cutoffOperationId"); + Objects.requireNonNull(anchor, "anchor"); + Objects.requireNonNull(currentState, "currentState"); + requireNoAmbientTransaction(); + return dsl.transactionResult( + configuration -> { + DSLContext transaction = DSL.using(configuration); + CanonicalGameplayBindingInventoryRepository.lockInventoryRevision(transaction); + lockLayoutControl(transaction, anchor); + Record controlRow = + transaction.fetchOne( + "SELECT * FROM " + CONTROL + " WHERE issuer_id = ? FOR UPDATE", ISSUER); + if (controlRow == null) throw conflict("Issuer cutoff control row is missing"); + CanonicalGameplayIssuerAdmissionControlValue control = loadControl(controlRow); + requireExactAnchorAndCurrentSource(control, anchor, currentState); + requireCounterMatchesCurrent(transaction, control.liveBarrierEpoch()); + if (!control.currentOperationId().equals(cutoffOperationId) + || control.state() != CanonicalGameplayIssuerAdmissionControlValue.State.CUTOFF_PENDING + || control.currentOperationKind() + != CanonicalGameplayIssuerAdmissionControlValue.OperationKind.CUTOFF) { + if (control.currentOperationId().equals(cutoffOperationId) + && control.state() == CanonicalGameplayIssuerAdmissionControlValue.State.INSTALLED) { + requireCutoffOperationCurrent(transaction, control); + verifyFrozenCohort(transaction, control); + verifyCutoffTargets(transaction, control); + return control; + } + throw conflict("The exact current cutoff is not pending completion"); + } + requireCutoffOperationCurrent(transaction, control); + verifyFrozenCohort(transaction, control); + verifyCutoffTargets(transaction, control); + Record remaining = + transaction.fetchOne( + "SELECT EXISTS (SELECT 1 FROM " + CUTOFF_TARGET + + " WHERE operation_id = ? AND issuer_id = ? AND target_state <> 'CLOSED')" + + " AS has_open_target", + cutoffOperationId, + ISSUER); + if (remaining == null || Boolean.TRUE.equals(remaining.get("has_open_target", Boolean.class))) { + throw conflict("Every frozen issuer tenant target must read back CLOSED before installation"); + } + CanonicalGameplayIssuerAdmissionControlValue installed = control.installed(); + int updatedOperation = + transaction.execute( + "UPDATE " + OPERATION + + " SET operation_state = 'INSTALLED', installed_at = CURRENT_TIMESTAMP" + + " WHERE operation_id = ? AND issuer_id = ? AND operation_kind = 'CUTOFF'" + + " AND operation_state = 'CUTOFF_PENDING' AND live_barrier_epoch = ?" + + " AND prior_live_barrier_epoch = ?", + cutoffOperationId, + ISSUER, + control.liveBarrierEpoch(), + control.liveBarrierEpoch().subtract(BigInteger.ONE)); + if (updatedOperation != 1) throw conflict("Issuer cutoff operation changed before installation"); + updateControl(transaction, installed, control.liveBarrierEpoch()); + Record saved = + transaction.fetchOne( + "SELECT * FROM " + CONTROL + " WHERE issuer_id = ? FOR UPDATE", ISSUER); + if (saved == null || !Arrays.equals(loadControl(saved).exactBytes(), installed.exactBytes())) { + throw conflict("Installed issuer cutoff did not read back exactly"); + } + return installed; + }); + } + + /** Revalidates a requested CLOSED key against the complete frozen cutoff cohort. */ + void verifyCurrentCutoffTarget( + DSLContext transaction, + CanonicalGameplayIssuerAdmissionControlValue control, + UUID tenantId, + UUID namespaceId, + byte[] expectedClosedPayload) { + Objects.requireNonNull(transaction, "transaction"); + Objects.requireNonNull(control, "control"); + requireNonNil(tenantId, "tenantId"); + requireNonNil(namespaceId, "namespaceId"); + if (control.state() != CanonicalGameplayIssuerAdmissionControlValue.State.CUTOFF_PENDING + || control.currentOperationKind() + != CanonicalGameplayIssuerAdmissionControlValue.OperationKind.CUTOFF) { + throw conflict("A CLOSED target requires the current pending issuer cutoff"); + } + requireCutoffOperationCurrent(transaction, control); + verifyFrozenCohort(transaction, control); + verifyCutoffTargets(transaction, control); + Record target = + transaction.fetchOne( + "SELECT * FROM " + CUTOFF_TARGET + + " WHERE operation_id = ? AND issuer_id = ? AND tenant_id = ?" + + " AND playable_state_namespace_id = ? FOR UPDATE", + control.currentOperationId(), + ISSUER, + tenantId, + namespaceId); + if (target == null + || (expectedClosedPayload != null + && !Arrays.equals(bytes(target, "closed_payload_bytes"), expectedClosedPayload))) { + throw conflict("Requested CLOSED target differs from the exact frozen cutoff cohort"); + } + } + + private static List captureCutoffCohort( + DSLContext transaction, BigInteger snapshotRevision) { + requireNoFutureCutoffRows(transaction, snapshotRevision); + String sql = + "SELECT source_kind, source_key, source_revision, source_row_json, tenant_id," + + " playable_state_namespace_id, transition_id FROM (" + + " SELECT 'BINDING' AS source_kind, encode(i.binding_ref, 'hex') AS source_key," + + " i.inventory_revision AS source_revision, to_jsonb(i)::text AS source_row_json," + + " i.tenant_id, i.playable_state_namespace_id, i.transition_id" + + " FROM game_session_canonical_gameplay_binding_inventory i" + + " WHERE i.issuer_id = ? AND i.inventory_revision <= ?" + + " UNION ALL SELECT 'TRANSITION', t.transition_id::text, t.inventory_revision," + + " to_jsonb(t)::text, t.tenant_id, t.playable_state_namespace_id, t.transition_id" + + " FROM game_session_canonical_binding_transition t" + + " JOIN game_session_canonical_gameplay_binding_inventory i" + + " ON i.transition_id = t.transition_id AND i.issuer_id = ?" + + " WHERE t.inventory_revision <= ?" + + " UNION ALL SELECT 'RESERVATION', r.reservation_id::text, r.inventory_revision," + + " to_jsonb(r)::text, r.tenant_id, r.playable_state_namespace_id, r.transition_id" + + " FROM game_session_canonical_issuer_partition_reservation r" + + " WHERE r.issuer_id = ? AND r.inventory_revision <= ?" + + " UNION ALL SELECT 'ACCOUNT_OBLIGATION'," + + " a.transition_id::text || ':' || a.obligation_ordinal::text, a.inventory_revision," + + " to_jsonb(a)::text, t.tenant_id, t.playable_state_namespace_id, t.transition_id" + + " FROM game_session_canonical_binding_account_index_obligation a" + + " JOIN game_session_canonical_binding_transition t ON t.transition_id = a.transition_id" + + " JOIN game_session_canonical_gameplay_binding_inventory i" + + " ON i.binding_ref = a.binding_ref AND i.issuer_id = ?" + + " WHERE a.inventory_revision <= ?" + + " UNION ALL SELECT 'ISSUER_OBLIGATION'," + + " encode(o.binding_ref, 'hex') || ':' || o.transition_id::text, o.inventory_revision," + + " to_jsonb(o)::text, t.tenant_id, t.playable_state_namespace_id, t.transition_id" + + " FROM game_session_canonical_binding_issuer_index_obligation o" + + " JOIN game_session_canonical_binding_transition t ON t.transition_id = o.transition_id" + + " JOIN game_session_canonical_gameplay_binding_inventory i" + + " ON i.binding_ref = o.binding_ref AND i.issuer_id = ?" + + " WHERE o.inventory_revision <= ?" + + " UNION ALL SELECT 'REGION_OBLIGATION', g.transition_id::text, g.inventory_revision," + + " to_jsonb(g)::text, t.tenant_id, t.playable_state_namespace_id, t.transition_id" + + " FROM game_session_canonical_binding_region_bridge_obligation g" + + " JOIN game_session_canonical_binding_transition t ON t.transition_id = g.transition_id" + + " JOIN game_session_canonical_gameplay_binding_inventory i" + + " ON i.binding_ref = g.binding_ref AND i.issuer_id = ?" + + " WHERE g.inventory_revision <= ?" + + " UNION ALL SELECT 'LOCAL_OPERATION', o.operation_id::text," + + " o.local_inventory_snapshot_revision, to_jsonb(o)::text, t.tenant_id," + + " t.playable_state_namespace_id, t.transition_id" + + " FROM game_session_canonical_issuer_binding_local_operation o" + + " JOIN game_session_canonical_binding_transition t ON t.transition_id = o.transition_id" + + " WHERE o.issuer_id = ? AND o.local_inventory_snapshot_revision <= ?" + + " UNION ALL SELECT 'BOOTSTRAP_MEMBER_OPERATION', m.member_operation_id::text," + + " m.original_inventory_snapshot_revision, to_jsonb(m)::text, r.tenant_id," + + " r.playable_state_namespace_id, r.transition_id" + + " FROM game_session_canonical_issuer_bootstrap_member_operation m" + + " JOIN game_session_canonical_issuer_partition_reservation r" + + " ON r.reservation_id = m.reservation_id" + + " WHERE m.issuer_id = ? AND m.original_inventory_snapshot_revision <= ?" + + " UNION ALL SELECT 'PENDING_INITIALIZER', init.operation_id::text," + + " local.local_inventory_snapshot_revision, to_jsonb(init)::text, init.tenant_id," + + " init.playable_state_namespace_id, local.transition_id" + + " FROM game_session_canonical_issuer_admission_initializer init" + + " JOIN game_session_canonical_issuer_binding_local_operation local" + + " ON local.operation_id = init.operation_id AND local.issuer_id = init.issuer_id" + + " LEFT JOIN game_session_canonical_issuer_admission_initializer_receipt receipt" + + " ON receipt.operation_id = init.operation_id AND receipt.issuer_id = init.issuer_id" + + " WHERE init.issuer_id = ? AND receipt.operation_id IS NULL" + + " AND local.local_inventory_snapshot_revision <= ?" + + ") captured ORDER BY source_kind COLLATE \"C\", source_key COLLATE \"C\""; + List binds = new ArrayList<>(); + for (int index = 0; index < 9; index++) { + binds.add(ISSUER); + binds.add(snapshotRevision); + } + return transaction + .fetch(sql, binds.toArray()) + .map( + row -> { + String json = text(row, "source_row_json"); + String digest = CanonicalGameplayIssuerAdmissionControlValue.sha256( + json.getBytes(StandardCharsets.UTF_8)); + BigInteger revision = integer(row, "source_revision"); + if (revision.signum() <= 0 || revision.compareTo(snapshotRevision) > 0) { + throw conflict("Issuer cutoff cohort contains a source outside its locked snapshot"); + } + return new CohortRow( + text(row, "source_kind"), + text(row, "source_key"), + revision, + json, + uuid(row, "tenant_id"), + uuid(row, "playable_state_namespace_id"), + uuid(row, "transition_id"), + digest); + }); + } + + private static void requireNoFutureCutoffRows( + DSLContext transaction, BigInteger snapshotRevision) { + String sql = + "SELECT EXISTS (SELECT 1 FROM game_session_canonical_gameplay_binding_inventory" + + " WHERE issuer_id = ? AND inventory_revision > ?)" + + " OR EXISTS (SELECT 1 FROM game_session_canonical_binding_transition t" + + " JOIN game_session_canonical_gameplay_binding_inventory i" + + " ON i.transition_id = t.transition_id AND i.issuer_id = ?" + + " WHERE t.inventory_revision > ?)" + + " OR EXISTS (SELECT 1 FROM game_session_canonical_issuer_partition_reservation" + + " WHERE issuer_id = ? AND inventory_revision > ?)" + + " OR EXISTS (SELECT 1 FROM game_session_canonical_binding_account_index_obligation a" + + " JOIN game_session_canonical_gameplay_binding_inventory i" + + " ON i.binding_ref = a.binding_ref AND i.issuer_id = ?" + + " WHERE a.inventory_revision > ?)" + + " OR EXISTS (SELECT 1 FROM game_session_canonical_binding_issuer_index_obligation o" + + " JOIN game_session_canonical_gameplay_binding_inventory i" + + " ON i.binding_ref = o.binding_ref AND i.issuer_id = ?" + + " WHERE o.inventory_revision > ?)" + + " OR EXISTS (SELECT 1 FROM game_session_canonical_binding_region_bridge_obligation g" + + " JOIN game_session_canonical_gameplay_binding_inventory i" + + " ON i.binding_ref = g.binding_ref AND i.issuer_id = ?" + + " WHERE g.inventory_revision > ?)" + + " OR EXISTS (SELECT 1 FROM game_session_canonical_issuer_binding_local_operation" + + " WHERE issuer_id = ? AND local_inventory_snapshot_revision > ?)" + + " OR EXISTS (SELECT 1 FROM game_session_canonical_issuer_bootstrap_member_operation" + + " WHERE issuer_id = ? AND original_inventory_snapshot_revision > ?)" + + " OR EXISTS (SELECT 1 FROM game_session_canonical_issuer_admission_initializer init" + + " JOIN game_session_canonical_issuer_binding_local_operation local" + + " ON local.operation_id = init.operation_id AND local.issuer_id = init.issuer_id" + + " WHERE init.issuer_id = ? AND local.local_inventory_snapshot_revision > ?)" + + " AS has_future_rows"; + List binds = new ArrayList<>(); + for (int index = 0; index < 9; index++) { + binds.add(ISSUER); + binds.add(snapshotRevision); + } + Record future = transaction.fetchOne(sql, binds.toArray()); + if (future == null || Boolean.TRUE.equals(future.get("has_future_rows", Boolean.class))) { + throw conflict("Issuer cutoff found source rows newer than its serialized inventory snapshot"); + } + } + + private static Map> groupTargets(List rows) { + Map> targets = new TreeMap<>(); + for (CohortRow row : rows) { + TargetScope scope = new TargetScope(row.tenantId(), row.namespaceId()); + targets.computeIfAbsent(scope, ignored -> new ArrayList<>()).add(row); + } + return targets; + } + + private static void insertCutoffOperation( + DSLContext transaction, + CanonicalGameplayIssuerAdmissionControlValue value, + UUID requestId, + BigInteger priorEpoch) { + int inserted = + transaction.execute( + "INSERT INTO " + OPERATION + + " (operation_id, request_id, issuer_id, operation_kind, operation_state," + + " live_barrier_epoch, prior_live_barrier_epoch, bootstrap_operation_id," + + " bootstrap_request_id, bootstrap_control_epoch, anchor_exact_bytes," + + " anchor_exact_digest, account_issuer_auth_generation, account_checkpoint_bytes," + + " account_checkpoint_digest, account_source_event_bytes, account_source_event_digest," + + " stable_incarnation_bytes, stable_incarnation_digest, inventory_snapshot_revision," + + " cohort_row_count, cohort_digest, installed_at)" + + " VALUES (?, ?, ?, 'CUTOFF', 'CUTOFF_PENDING', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NULL)", + value.currentOperationId(), + requestId, + value.issuerId(), + value.liveBarrierEpoch(), + priorEpoch, + value.bootstrapOperationId(), + value.bootstrapRequestId(), + value.bootstrapControlEpoch(), + value.anchorExactBytes(), + value.anchorExactDigest(), + value.accountIssuerAuthGeneration(), + value.accountCheckpointBytes(), + value.accountCheckpointDigest(), + value.accountSourceEventBytes(), + value.accountSourceEventDigest(), + value.stableIncarnationBytes(), + value.stableIncarnationDigest(), + value.inventorySnapshotRevision(), + value.cohortRowCount(), + value.cohortDigest()); + if (inserted != 1) throw conflict("Issuer cutoff operation did not persist"); + } + + private static void insertCohortRows( + DSLContext transaction, UUID operationId, List rows) { + for (int index = 0; index < rows.size(); index++) { + CohortRow row = rows.get(index); + int inserted = + transaction.execute( + "INSERT INTO " + COHORT + + " (operation_id, issuer_id, row_ordinal, source_kind, source_key," + + " source_inventory_revision, source_row_json, source_row_digest)" + + " VALUES (?, ?, ?, ?, ?, ?, ?, ?)", + operationId, + ISSUER, + (long) index, + row.sourceKind(), + row.sourceKey(), + row.sourceRevision(), + row.sourceJson(), + row.sourceDigest()); + if (inserted != 1) throw conflict("Issuer cutoff cohort row did not persist"); + } + } + + private static void insertCutoffTargets( + DSLContext transaction, + CanonicalGameplayIssuerAdmissionControlValue control, + Map> targets, + Map tagByTarget) { + int ordinal = 0; + for (Map.Entry> entry : targets.entrySet()) { + TargetScope scope = entry.getKey(); + String tenantTag = tagByTarget.get(scope); + if (tenantTag == null) throw conflict("Issuer cutoff target has no current SQL tenant tag"); + Record initializerRow = + transaction.fetchOne( + "SELECT * FROM " + INITIALIZER + + " WHERE issuer_id = ? AND tenant_id = ? AND playable_state_namespace_id = ?" + + " AND live_barrier_epoch <= ? ORDER BY live_barrier_epoch DESC LIMIT 1 FOR UPDATE", + ISSUER, + scope.tenantId(), + scope.namespaceId(), + control.liveBarrierEpoch().subtract(BigInteger.ONE)); + CanonicalGameplayIssuerAdmissionBarrierValue.Initializer initializer = null; + byte[] openPayload = null; + String openDigest = null; + UUID initializerOperationId = null; + BigInteger initializerEpoch = null; + String initializerDigest = null; + if (initializerRow != null) { + initializerOperationId = uuid(initializerRow, "operation_id"); + initializerEpoch = integer(initializerRow, "live_barrier_epoch"); + byte[] initializerBytes = bytes(initializerRow, "initializer_exact_bytes"); + initializerDigest = text(initializerRow, "initializer_digest"); + openPayload = bytes(initializerRow, "open_payload_bytes"); + openDigest = text(initializerRow, "open_payload_digest"); + if (!CanonicalGameplayIssuerAdmissionControlValue.sha256(initializerBytes) + .equals(initializerDigest) + || !CanonicalGameplayIssuerAdmissionControlValue.sha256(openPayload).equals(openDigest)) { + throw conflict("Persisted original issuer initializer digest is invalid"); + } + CanonicalGameplayIssuerAdmissionBarrierValue decoded = + CanonicalGameplayIssuerAdmissionBarrierValue.decode(openPayload); + initializer = decoded.initializer(); + if (decoded.state() != CanonicalGameplayIssuerAdmissionBarrierValue.State.OPEN + || !decoded.issuerId().equals(ISSUER) + || !decoded.tenantId().equals(scope.tenantId()) + || !decoded.playableStateNamespaceId().equals(scope.namespaceId()) + || !decoded.tenantGameplayTag().equals(tenantTag) + || !decoded.ownerOperationId().equals(initializerOperationId) + || !decoded.admissionEpoch().equals(initializerEpoch) + || initializer == null + || !initializer.exactDigest().equals(initializerDigest) + || !initializer.operationId().equals(initializerOperationId) + || !initializer.admissionEpoch().equals(initializerEpoch) + || !initializer.tenantGameplayTag().equals(tenantTag) + || !Arrays.equals(initializer.anchorBytes(), control.anchorExactBytes()) + || !initializer.anchorDigest().equals(control.anchorExactDigest()) + || !initializer.accountIssuerAuthGeneration().equals(control.accountIssuerAuthGeneration()) + || !Arrays.equals(initializer.accountCheckpointBytes(), control.accountCheckpointBytes()) + || !initializer.accountCheckpointDigest().equals(control.accountCheckpointDigest()) + || !Arrays.equals(initializer.accountSourceEventBytes(), control.accountSourceEventBytes()) + || !Objects.equals(initializer.accountSourceEventDigest(), control.accountSourceEventDigest()) + || !Arrays.equals(initializer.incarnationBytes(), control.stableIncarnationBytes()) + || !initializer.incarnationDigest().equals(control.stableIncarnationDigest())) { + throw conflict("Captured original OPEN initializer differs from the frozen issuer source"); + } + } + String targetDigest = digestTargetSource(entry.getValue()); + CanonicalGameplayIssuerAdmissionBarrierValue closed = + CanonicalGameplayIssuerAdmissionBarrierValue.closed( + ISSUER, + scope.tenantId(), + scope.namespaceId(), + tenantTag, + control.liveBarrierEpoch(), + control.currentOperationId(), + initializer); + int inserted = + transaction.execute( + "INSERT INTO " + CUTOFF_TARGET + + " (operation_id, issuer_id, target_ordinal, tenant_id," + + " playable_state_namespace_id, tenant_gameplay_tag, target_source_digest," + + " captured_initializer_operation_id, captured_initializer_epoch," + + " captured_initializer_digest, captured_open_payload_bytes," + + " captured_open_payload_digest, closed_payload_bytes, closed_payload_digest," + + " exact_closed_readback_bytes, exact_closed_readback_digest, script_outcome, target_state)" + + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, NULL, NULL, 'REQUIRED')", + control.currentOperationId(), + ISSUER, + (long) ordinal++, + scope.tenantId(), + scope.namespaceId(), + tenantTag, + targetDigest, + initializerOperationId, + initializerEpoch, + initializerDigest, + openPayload, + openDigest, + closed.exactBytes(), + closed.exactDigest()); + if (inserted != 1) throw conflict("Issuer cutoff target did not persist"); + } + } + + private static void verifyFrozenCohort( + DSLContext transaction, CanonicalGameplayIssuerAdmissionControlValue control) { + List rows = + transaction + .fetch( + "SELECT * FROM " + COHORT + + " WHERE operation_id = ? AND issuer_id = ? ORDER BY row_ordinal", + control.currentOperationId(), + ISSUER) + .map( + row -> { + String json = text(row, "source_row_json"); + String storedDigest = text(row, "source_row_digest"); + if (!CanonicalGameplayIssuerAdmissionControlValue.sha256( + json.getBytes(StandardCharsets.UTF_8)) + .equals(storedDigest)) { + throw conflict("Issuer cutoff cohort source digest differs from its stored JSON"); + } + return new CohortRow( + text(row, "source_kind"), + text(row, "source_key"), + integer(row, "source_inventory_revision"), + json, + null, + null, + null, + storedDigest); + }); + for (int index = 0; index < rows.size(); index++) { + if (rows.get(index).sourceRevision().compareTo(control.inventorySnapshotRevision()) > 0) { + throw conflict("Issuer cutoff cohort row is newer than its frozen inventory snapshot"); + } + Record ordinal = + transaction.fetchOne( + "SELECT row_ordinal FROM " + COHORT + + " WHERE operation_id = ? AND issuer_id = ? AND source_kind = ? AND source_key = ?", + control.currentOperationId(), + ISSUER, + rows.get(index).sourceKind(), + rows.get(index).sourceKey()); + if (ordinal == null || longInteger(ordinal, "row_ordinal") != index) { + throw conflict("Issuer cutoff cohort ordinals are not contiguous and canonical"); + } + } + if (rows.size() != control.cohortRowCount() + || !digestCohort(rows).equals(control.cohortDigest())) { + throw conflict("Issuer cutoff cohort no longer matches its frozen complete digest"); + } + } + + private static String requireCurrentTenantTagMapping(DSLContext transaction, UUID tenantId) { + Record mapping = + transaction.fetchOne( + "SELECT allocation_version, tenant_gameplay_tag FROM " + TENANT_TAG + + " WHERE tenant_id = ? FOR SHARE", + tenantId); + Integer version = mapping == null ? null : mapping.get("allocation_version", Integer.class); + String tag = mapping == null ? null : mapping.get("tenant_gameplay_tag", String.class); + if (version == null + || version <= 0 + || tag == null + || !tag.matches("g[1-9][0-9]{0,9}-[0-9a-f]{32}") + || !tag.equals("g" + version + "-" + tenantId.toString().replace("-", ""))) { + throw conflict("Issuer cutoff requires a positive exact SQL tenant gameplay-tag mapping"); + } + return tag; + } + + private static void verifyCutoffTargets( + DSLContext transaction, CanonicalGameplayIssuerAdmissionControlValue control) { + List rows = + transaction.fetch( + "SELECT * FROM " + CUTOFF_TARGET + + " WHERE operation_id = ? AND issuer_id = ? ORDER BY target_ordinal", + control.currentOperationId(), + ISSUER); + Map> cohortTargets = + groupTargets(captureCutoffCohort(transaction, control.inventorySnapshotRevision())); + if (rows.size() != cohortTargets.size()) { + throw conflict("Issuer cutoff target set differs from its complete frozen cohort"); + } + for (int index = 0; index < rows.size(); index++) { + Record row = rows.get(index); + UUID tenantId = uuid(row, "tenant_id"); + UUID namespaceId = uuid(row, "playable_state_namespace_id"); + String tenantTag = text(row, "tenant_gameplay_tag"); + TargetScope scope = new TargetScope(tenantId, namespaceId); + List sources = cohortTargets.get(scope); + if (!tenantTag.equals(requireCurrentTenantTagMapping(transaction, tenantId))) { + throw conflict("Issuer cutoff tenant tag differs from the current immutable SQL mapping"); + } + if (sources == null + || longInteger(row, "target_ordinal") != index + || !CanonicalGameplayIssuerAdmissionControlValue.sha256( + bytes(row, "closed_payload_bytes")) + .equals(text(row, "closed_payload_digest")) + || !digestTargetSource(sources).equals(text(row, "target_source_digest"))) { + throw conflict("Issuer cutoff target differs from its immutable captured source"); + } + CanonicalGameplayIssuerAdmissionBarrierValue closed = + CanonicalGameplayIssuerAdmissionBarrierValue.decode(bytes(row, "closed_payload_bytes")); + if (closed.state() != CanonicalGameplayIssuerAdmissionBarrierValue.State.CLOSED + || !closed.issuerId().equals(ISSUER) + || !closed.tenantId().equals(tenantId) + || !closed.playableStateNamespaceId().equals(namespaceId) + || !closed.tenantGameplayTag().equals(tenantTag) + || !closed.ownerOperationId().equals(control.currentOperationId()) + || !closed.admissionEpoch().equals(control.liveBarrierEpoch())) { + throw conflict("Issuer cutoff target payload does not bind its exact live cutoff"); + } + byte[] capturedOpen = nullableBytes(row, "captured_open_payload_bytes"); + if (capturedOpen != null) { + CanonicalGameplayIssuerAdmissionBarrierValue open = + CanonicalGameplayIssuerAdmissionBarrierValue.decode(capturedOpen); + if (open.state() != CanonicalGameplayIssuerAdmissionBarrierValue.State.OPEN + || closed.initializer() == null + || !Arrays.equals(open.initializer().exactBytes(), closed.initializer().exactBytes()) + || !CanonicalGameplayIssuerAdmissionControlValue.sha256(capturedOpen) + .equals(text(row, "captured_open_payload_digest"))) { + throw conflict("Issuer cutoff target lost its exact captured original OPEN value"); + } + } else if (closed.initializer() != null + || nullableBytes(row, "captured_open_payload_digest") != null + || row.get("captured_initializer_operation_id", UUID.class) != null + || row.get("captured_initializer_epoch", java.math.BigDecimal.class) != null + || row.get("captured_initializer_digest", String.class) != null) { + throw conflict("Issuer cutoff target has partial initializer evidence"); + } + byte[] readback = nullableBytes(row, "exact_closed_readback_bytes"); + if ("CLOSED".equals(text(row, "target_state"))) { + if (readback == null + || !CanonicalGameplayIssuerAdmissionControlValue.sha256(readback) + .equals(text(row, "exact_closed_readback_digest")) + || !Arrays.equals(readback, closed.exactBytes())) { + throw conflict("Issuer CLOSED receipt differs from its exact persistent target payload"); + } + } else if (!"REQUIRED".equals(text(row, "target_state")) || readback != null) { + throw conflict("Issuer cutoff target has an unknown or partial readback state"); + } + } + } + + private static void requireCutoffOperationCurrent( + DSLContext transaction, CanonicalGameplayIssuerAdmissionControlValue control) { + Record operation = + transaction.fetchOne( + "SELECT * FROM " + OPERATION + " WHERE operation_id = ? FOR UPDATE", + control.currentOperationId()); + if (operation == null + || !ISSUER.equals(text(operation, "issuer_id")) + || !"CUTOFF".equals(text(operation, "operation_kind")) + || !text(operation, "operation_state").equals(control.state().name()) + || !control.liveBarrierEpoch().equals(integer(operation, "live_barrier_epoch")) + || !control.bootstrapOperationId().equals(uuid(operation, "bootstrap_operation_id")) + || !control.bootstrapRequestId().equals(uuid(operation, "bootstrap_request_id")) + || !control.bootstrapControlEpoch().equals(integer(operation, "bootstrap_control_epoch")) + || !Arrays.equals(control.anchorExactBytes(), bytes(operation, "anchor_exact_bytes")) + || !control.anchorExactDigest().equals(text(operation, "anchor_exact_digest")) + || !control.accountIssuerAuthGeneration().equals(integer(operation, "account_issuer_auth_generation")) + || !Arrays.equals(control.accountCheckpointBytes(), bytes(operation, "account_checkpoint_bytes")) + || !control.accountCheckpointDigest().equals(text(operation, "account_checkpoint_digest")) + || !Arrays.equals(control.accountSourceEventBytes(), nullableBytes(operation, "account_source_event_bytes")) + || !Objects.equals(control.accountSourceEventDigest(), nullableText(operation, "account_source_event_digest")) + || !Arrays.equals(control.stableIncarnationBytes(), bytes(operation, "stable_incarnation_bytes")) + || !control.stableIncarnationDigest().equals(text(operation, "stable_incarnation_digest")) + || !control.inventorySnapshotRevision().equals(integer(operation, "inventory_snapshot_revision")) + || control.cohortRowCount() != longInteger(operation, "cohort_row_count") + || !control.cohortDigest().equals(text(operation, "cohort_digest"))) { + throw conflict("Live issuer cutoff has no exact current durable operation"); + } + } + + private static void updateControl( + DSLContext transaction, CanonicalGameplayIssuerAdmissionControlValue value, BigInteger expectedEpoch) { + int updated = + transaction.execute( + "UPDATE " + CONTROL + + " SET state = ?, live_barrier_epoch = ?, current_operation_id = ?," + + " current_operation_kind = ?, bootstrap_operation_id = ?, bootstrap_request_id = ?," + + " bootstrap_control_epoch = ?, anchor_exact_bytes = ?, anchor_exact_digest = ?," + + " account_issuer_auth_generation = ?, account_checkpoint_bytes = ?," + + " account_checkpoint_digest = ?, account_source_event_bytes = ?," + + " account_source_event_digest = ?, stable_incarnation_bytes = ?," + + " stable_incarnation_digest = ?, inventory_snapshot_revision = ?," + + " cohort_row_count = ?, cohort_digest = ?, control_exact_bytes = ?," + + " control_exact_digest = ?, updated_at = CURRENT_TIMESTAMP" + + " WHERE issuer_id = ? AND live_barrier_epoch = ?", + value.state().name(), + value.liveBarrierEpoch(), + value.currentOperationId(), + value.currentOperationKind().name(), + value.bootstrapOperationId(), + value.bootstrapRequestId(), + value.bootstrapControlEpoch(), + value.anchorExactBytes(), + value.anchorExactDigest(), + value.accountIssuerAuthGeneration(), + value.accountCheckpointBytes(), + value.accountCheckpointDigest(), + value.accountSourceEventBytes(), + value.accountSourceEventDigest(), + value.stableIncarnationBytes(), + value.stableIncarnationDigest(), + value.inventorySnapshotRevision(), + value.cohortRowCount(), + value.cohortDigest(), + value.exactBytes(), + value.exactDigest(), + value.issuerId(), + expectedEpoch); + if (updated != 1) throw conflict("Live issuer control changed before its exact update"); + } + + private static String digestCohort(List rows) { + MessageDigest digest = sha256Digest(); + rows.stream() + .sorted( + Comparator.comparing(CohortRow::sourceKind) + .thenComparing(CohortRow::sourceKey)) + .forEach( + row -> { + updateFramed(digest, row.sourceKind().getBytes(StandardCharsets.UTF_8)); + updateFramed(digest, row.sourceKey().getBytes(StandardCharsets.UTF_8)); + updateFramed(digest, row.sourceRevision().toString().getBytes(StandardCharsets.US_ASCII)); + updateFramed(digest, row.sourceDigest().getBytes(StandardCharsets.US_ASCII)); + }); + return "sha256:" + HexFormat.of().formatHex(digest.digest()); + } + + private static String digestTargetSource(List rows) { + MessageDigest digest = sha256Digest(); + rows.stream() + .sorted( + Comparator.comparing(CohortRow::sourceKind) + .thenComparing(CohortRow::sourceKey)) + .forEach( + row -> { + updateFramed(digest, row.sourceKind().getBytes(StandardCharsets.UTF_8)); + updateFramed(digest, row.sourceKey().getBytes(StandardCharsets.UTF_8)); + updateFramed(digest, row.sourceDigest().getBytes(StandardCharsets.US_ASCII)); + }); + return "sha256:" + HexFormat.of().formatHex(digest.digest()); + } + + private static MessageDigest sha256Digest() { + try { + return MessageDigest.getInstance("SHA-256"); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 is unavailable", impossible); + } + } + + private static void updateFramed(MessageDigest digest, byte[] value) { + digest.update(ByteBuffer.allocate(Integer.BYTES).putInt(value.length).array()); + digest.update(value); + } + + private static void requireNonNil(UUID value, String name) { + if (value == null || value.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException(name + " must be a non-nil UUID"); + } + } + + private record CohortRow( + String sourceKind, + String sourceKey, + BigInteger sourceRevision, + String sourceJson, + UUID tenantId, + UUID namespaceId, + UUID transitionId, + String sourceDigest) {} + + private record TargetScope(UUID tenantId, UUID namespaceId) implements Comparable { + @Override + public int compareTo(TargetScope other) { + int tenant = tenantId.compareTo(other.tenantId); + return tenant != 0 ? tenant : namespaceId.compareTo(other.namespaceId); + } + } + + /** + * Requires a positive current OPEN control after the caller has locked inventory, then layout + * control. Missing state, source movement, and every cutoff state deny preparation. + */ + static CanonicalGameplayIssuerAdmissionControlValue requireOpenInTransaction( + DSLContext transaction, + CanonicalGameplayIssuerInstalledAnchor anchor, + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState currentState) { + Objects.requireNonNull(transaction, "transaction"); + Objects.requireNonNull(anchor, "anchor"); + Objects.requireNonNull(currentState, "currentState"); + lockLayoutControl(transaction, anchor); + Record row = transaction.fetchOne("SELECT * FROM " + CONTROL + " WHERE issuer_id = ? FOR UPDATE", ISSUER); + if (row == null) throw conflict("Ordinary issuer work requires a positive live admission-control row"); + CanonicalGameplayIssuerAdmissionControlValue value = loadControl(row); + requireExactAnchorAndCurrentSource(value, anchor, currentState); + if (value.state() != CanonicalGameplayIssuerAdmissionControlValue.State.OPEN + || value.currentOperationKind() + != CanonicalGameplayIssuerAdmissionControlValue.OperationKind.INITIAL_ANCHOR_INSTALL) { + throw conflict("Live issuer admission control is cutting off or installed closed"); + } + requireCounterMatchesCurrent(transaction, value.liveBarrierEpoch()); + requireInitialOperationCurrent(transaction, value); + return value; + } + + private CanonicalGameplayIssuerAdmissionControlValue installInitialInTransaction( + DSLContext transaction, + CanonicalGameplayIssuerInstalledAnchor anchor, + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState currentState) { + CanonicalGameplayBindingInventoryRepository.lockInventoryRevision(transaction); + lockLayoutControl(transaction, anchor); + Record existing = transaction.fetchOne("SELECT * FROM " + CONTROL + " WHERE issuer_id = ? FOR UPDATE", ISSUER); + if (existing != null) { + CanonicalGameplayIssuerAdmissionControlValue prior = loadControl(existing); + requireExactAnchorAndCurrentSource(prior, anchor, currentState); + if (prior.state() == CanonicalGameplayIssuerAdmissionControlValue.State.OPEN + && prior.currentOperationKind() + == CanonicalGameplayIssuerAdmissionControlValue.OperationKind.INITIAL_ANCHOR_INSTALL + && prior.currentOperationId().equals(anchor.bootstrapOperationId())) { + requireCounterMatchesCurrent(transaction, prior.liveBarrierEpoch()); + requireInitialOperationCurrent(transaction, prior); + return prior; + } + throw conflict("Existing issuer admission control cannot be reset or reopened"); + } + + Record counter = transaction.fetchOne("SELECT * FROM " + COUNTER + " WHERE issuer_id = ? FOR UPDATE", ISSUER); + if (counter == null) throw conflict("The positive live issuer epoch counter is missing"); + BigInteger last = integer(counter, "last_live_barrier_epoch"); + if (last.signum() != 0) { + throw conflict("Missing live issuer control cannot be reconstructed from its epoch counter"); + } + // Existing post-anchor operations have no V1046 initializer provenance and cannot be + // reclassified as safe OPEN work during this install. + Record oldLocal = + transaction.fetchOne( + "SELECT EXISTS (SELECT 1 FROM " + LOCAL_OPERATION + " WHERE issuer_id = ?) AS has_rows", + ISSUER); + if (oldLocal == null || Boolean.TRUE.equals(oldLocal.get("has_rows", Boolean.class))) { + throw conflict("Initial live control cannot adopt an unregistered local issuer operation"); + } + + Record allocated = + transaction.fetchOne( + "UPDATE " + COUNTER + + " SET last_live_barrier_epoch = last_live_barrier_epoch + 1," + + " updated_at = CURRENT_TIMESTAMP" + + " WHERE issuer_id = ? AND last_live_barrier_epoch = 0" + + " RETURNING last_live_barrier_epoch", + ISSUER); + if (allocated == null) throw conflict("Live issuer epoch allocation lost its serialized counter"); + BigInteger liveEpoch = integer(allocated, "last_live_barrier_epoch"); + CanonicalGameplayIssuerAdmissionControlValue requested = + CanonicalGameplayIssuerAdmissionControlValue.initialOpen( + anchor, + currentState, + liveEpoch, + 0L, + CanonicalGameplayIssuerAdmissionControlValue.sha256( + "issuer-admission-initial-cohort/v1".getBytes(java.nio.charset.StandardCharsets.UTF_8))); + + insertInitialOperation(transaction, requested); + insertControl(transaction, requested); + Record saved = transaction.fetchOne("SELECT * FROM " + CONTROL + " WHERE issuer_id = ? FOR UPDATE", ISSUER); + if (saved == null) throw conflict("Initial live issuer control did not persist"); + CanonicalGameplayIssuerAdmissionControlValue result = loadControl(saved); + if (!Arrays.equals(result.exactBytes(), requested.exactBytes())) { + throw conflict("Persisted initial live issuer control differs from its exact owner value"); + } + return result; + } + + private static void lockLayoutControl( + DSLContext transaction, CanonicalGameplayIssuerInstalledAnchor anchor) { + Record control = + transaction.fetchOne( + "SELECT * FROM " + LAYOUT_CONTROL + " WHERE issuer_id = ? FOR UPDATE", ISSUER); + if (control == null + || !ISSUER.equals(text(control, "issuer_id")) + || !"INITIAL_BOOTSTRAP_INTENT".equals(text(control, "state")) + || !anchor.bootstrapOperationId().equals(uuid(control, "current_operation_id")) + || !anchor.controlEpoch().equals(integer(control, "control_epoch")) + || !anchor.operationFence().equals(integer(control, "current_operation_fence")) + || !anchor.coverageFence().equals(integer(control, "current_coverage_fence"))) { + throw conflict("Live admission control requires its exact immutable V1030 bootstrap provenance"); + } + Record anchorRow = + transaction.fetchOne("SELECT exact_anchor_bytes, exact_anchor_digest FROM " + ANCHOR + " WHERE issuer_id = ? FOR UPDATE", ISSUER); + if (anchorRow == null + || !Arrays.equals(bytes(anchorRow, "exact_anchor_bytes"), anchor.exactAnchorBytes()) + || !anchor.exactAnchorDigest().equals(text(anchorRow, "exact_anchor_digest"))) { + throw conflict("Live admission control requires the exact installed anchor row"); + } + } + + private static void insertInitialOperation( + DSLContext transaction, CanonicalGameplayIssuerAdmissionControlValue value) { + int inserted = + transaction.execute( + "INSERT INTO " + OPERATION + + " (operation_id, request_id, issuer_id, operation_kind, operation_state," + + " live_barrier_epoch, prior_live_barrier_epoch, bootstrap_operation_id," + + " bootstrap_request_id, bootstrap_control_epoch, anchor_exact_bytes," + + " anchor_exact_digest, account_issuer_auth_generation, account_checkpoint_bytes," + + " account_checkpoint_digest, account_source_event_bytes, account_source_event_digest," + + " stable_incarnation_bytes, stable_incarnation_digest, inventory_snapshot_revision," + + " cohort_row_count, cohort_digest, installed_at)" + + " VALUES (?, ?, ?, 'INITIAL_ANCHOR_INSTALL', 'OPEN', ?, NULL, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP)", + value.currentOperationId(), + value.bootstrapRequestId(), + value.issuerId(), + value.liveBarrierEpoch(), + value.bootstrapOperationId(), + value.bootstrapRequestId(), + value.bootstrapControlEpoch(), + value.anchorExactBytes(), + value.anchorExactDigest(), + value.accountIssuerAuthGeneration(), + value.accountCheckpointBytes(), + value.accountCheckpointDigest(), + value.accountSourceEventBytes(), + value.accountSourceEventDigest(), + value.stableIncarnationBytes(), + value.stableIncarnationDigest(), + value.inventorySnapshotRevision(), + value.cohortRowCount(), + value.cohortDigest()); + if (inserted != 1) throw conflict("Initial live issuer control operation did not persist"); + } + + private static void insertControl( + DSLContext transaction, CanonicalGameplayIssuerAdmissionControlValue value) { + int inserted = + transaction.execute( + "INSERT INTO " + CONTROL + + " (issuer_id, state, live_barrier_epoch, current_operation_id, current_operation_kind," + + " bootstrap_operation_id, bootstrap_request_id, bootstrap_control_epoch," + + " anchor_exact_bytes, anchor_exact_digest, account_issuer_auth_generation," + + " account_checkpoint_bytes, account_checkpoint_digest, account_source_event_bytes," + + " account_source_event_digest, stable_incarnation_bytes, stable_incarnation_digest," + + " inventory_snapshot_revision, cohort_row_count, cohort_digest, control_exact_bytes," + + " control_exact_digest) VALUES (?, 'OPEN', ?, ?, 'INITIAL_ANCHOR_INSTALL', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + value.issuerId(), + value.liveBarrierEpoch(), + value.currentOperationId(), + value.bootstrapOperationId(), + value.bootstrapRequestId(), + value.bootstrapControlEpoch(), + value.anchorExactBytes(), + value.anchorExactDigest(), + value.accountIssuerAuthGeneration(), + value.accountCheckpointBytes(), + value.accountCheckpointDigest(), + value.accountSourceEventBytes(), + value.accountSourceEventDigest(), + value.stableIncarnationBytes(), + value.stableIncarnationDigest(), + value.inventorySnapshotRevision(), + value.cohortRowCount(), + value.cohortDigest(), + value.exactBytes(), + value.exactDigest()); + if (inserted != 1) throw conflict("Initial live issuer admission control did not persist"); + } + + private static CanonicalGameplayIssuerAdmissionControlValue loadControl(Record row) { + byte[] exact = bytes(row, "control_exact_bytes"); + String digest = text(row, "control_exact_digest"); + if (!CanonicalGameplayIssuerAdmissionControlValue.sha256(exact).equals(digest)) { + throw conflict("Persisted issuer admission control digest differs from its exact bytes"); + } + CanonicalGameplayIssuerAdmissionControlValue value; + try { + value = CanonicalGameplayIssuerAdmissionControlValue.decode(exact); + } catch (RuntimeException malformed) { + throw conflict("Persisted issuer admission-control value is malformed"); + } + if (!value.issuerId().equals(text(row, "issuer_id")) + || !value.state().name().equals(text(row, "state")) + || !value.liveBarrierEpoch().equals(integer(row, "live_barrier_epoch")) + || !value.currentOperationId().equals(uuid(row, "current_operation_id")) + || !value.currentOperationKind().name().equals(text(row, "current_operation_kind")) + || !value.bootstrapOperationId().equals(uuid(row, "bootstrap_operation_id")) + || !value.bootstrapRequestId().equals(uuid(row, "bootstrap_request_id")) + || !value.bootstrapControlEpoch().equals(integer(row, "bootstrap_control_epoch")) + || !Arrays.equals(value.anchorExactBytes(), bytes(row, "anchor_exact_bytes")) + || !value.anchorExactDigest().equals(text(row, "anchor_exact_digest")) + || !value.accountIssuerAuthGeneration().equals(integer(row, "account_issuer_auth_generation")) + || !Arrays.equals(value.accountCheckpointBytes(), bytes(row, "account_checkpoint_bytes")) + || !value.accountCheckpointDigest().equals(text(row, "account_checkpoint_digest")) + || !Arrays.equals(value.accountSourceEventBytes(), nullableBytes(row, "account_source_event_bytes")) + || !Objects.equals(value.accountSourceEventDigest(), nullableText(row, "account_source_event_digest")) + || !Arrays.equals(value.stableIncarnationBytes(), bytes(row, "stable_incarnation_bytes")) + || !value.stableIncarnationDigest().equals(text(row, "stable_incarnation_digest")) + || !value.inventorySnapshotRevision().equals(integer(row, "inventory_snapshot_revision")) + || value.cohortRowCount() != longInteger(row, "cohort_row_count") + || !value.cohortDigest().equals(text(row, "cohort_digest"))) { + throw conflict("Issuer admission-control columns differ from their exact typed value"); + } + return value; + } + + private static void requireExactAnchorAndCurrentSource( + CanonicalGameplayIssuerAdmissionControlValue value, + CanonicalGameplayIssuerInstalledAnchor anchor, + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState currentState) { + if (!value.bootstrapOperationId().equals(anchor.bootstrapOperationId()) + || !value.bootstrapRequestId().equals(anchor.bootstrapRequestId()) + || !value.bootstrapControlEpoch().equals(anchor.controlEpoch()) + || !Arrays.equals(value.anchorExactBytes(), anchor.exactAnchorBytes()) + || !value.anchorExactDigest().equals(anchor.exactAnchorDigest()) + || !value.matchesCurrentIssuerState(currentState)) { + throw conflict("Live issuer control no longer matches its exact anchor and current sources"); + } + } + + private static void requireCounterMatchesCurrent(DSLContext transaction, BigInteger liveEpoch) { + Record counter = transaction.fetchOne("SELECT * FROM " + COUNTER + " WHERE issuer_id = ? FOR UPDATE", ISSUER); + if (counter == null || !integer(counter, "last_live_barrier_epoch").equals(liveEpoch)) { + throw conflict("Live issuer admission epoch differs from its positive owner counter"); + } + } + + private static void requireInitialOperationCurrent( + DSLContext transaction, CanonicalGameplayIssuerAdmissionControlValue value) { + Record operation = transaction.fetchOne("SELECT * FROM " + OPERATION + " WHERE operation_id = ? FOR UPDATE", value.currentOperationId()); + if (operation == null + || !ISSUER.equals(text(operation, "issuer_id")) + || !"INITIAL_ANCHOR_INSTALL".equals(text(operation, "operation_kind")) + || !"OPEN".equals(text(operation, "operation_state")) + || !value.liveBarrierEpoch().equals(integer(operation, "live_barrier_epoch")) + || !value.bootstrapRequestId().equals(uuid(operation, "request_id")) + || !value.bootstrapOperationId().equals(uuid(operation, "bootstrap_operation_id")) + || !value.bootstrapControlEpoch().equals(integer(operation, "bootstrap_control_epoch")) + || !Arrays.equals(value.anchorExactBytes(), bytes(operation, "anchor_exact_bytes")) + || !value.anchorExactDigest().equals(text(operation, "anchor_exact_digest")) + || !value.accountIssuerAuthGeneration().equals(integer(operation, "account_issuer_auth_generation")) + || !Arrays.equals(value.accountCheckpointBytes(), bytes(operation, "account_checkpoint_bytes")) + || !value.accountCheckpointDigest().equals(text(operation, "account_checkpoint_digest")) + || !Arrays.equals(value.accountSourceEventBytes(), nullableBytes(operation, "account_source_event_bytes")) + || !Objects.equals(value.accountSourceEventDigest(), nullableText(operation, "account_source_event_digest")) + || !Arrays.equals(value.stableIncarnationBytes(), bytes(operation, "stable_incarnation_bytes")) + || !value.stableIncarnationDigest().equals(text(operation, "stable_incarnation_digest")) + || !value.inventorySnapshotRevision().equals(integer(operation, "inventory_snapshot_revision")) + || value.cohortRowCount() != longInteger(operation, "cohort_row_count") + || !value.cohortDigest().equals(text(operation, "cohort_digest"))) { + throw conflict("Live issuer control has no exact persisted initial-anchor operation"); + } + } + + private static BigInteger integer(Record row, String name) { + java.math.BigDecimal value = row.get(name, java.math.BigDecimal.class); + if (value == null) throw conflict("Persisted issuer admission field is missing: " + name); + try { + return value.toBigIntegerExact(); + } catch (ArithmeticException malformed) { + throw conflict("Persisted issuer admission integer is malformed: " + name); + } + } + + private static long longInteger(Record row, String name) { + Long value = row.get(name, Long.class); + if (value == null || value < 0) { + throw conflict("Persisted issuer admission count is missing or negative: " + name); + } + return value; + } + + private static java.util.UUID uuid(Record row, String name) { + java.util.UUID value = row.get(name, java.util.UUID.class); + if (value == null) throw conflict("Persisted issuer admission UUID is missing: " + name); + return value; + } + + private static String text(Record row, String name) { + String value = row.get(name, String.class); + if (value == null) throw conflict("Persisted issuer admission text is missing: " + name); + return value; + } + + private static byte[] bytes(Record row, String name) { + byte[] value = row.get(name, byte[].class); + if (value == null) throw conflict("Persisted issuer admission bytes are missing: " + name); + return value; + } + + private static byte[] nullableBytes(Record row, String name) { + return row.get(name, byte[].class); + } + + private static String nullableText(Record row, String name) { + return row.get(name, String.class); + } + + private void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw conflict("Issuer admission-control owner cannot join an ambient transaction"); + } + try { + dsl.connectionResult( + connection -> { + if (!connection.getAutoCommit()) { + throw conflict("Issuer admission-control owner cannot join a jOOQ transaction"); + } + return Boolean.TRUE; + }); + } catch (RuntimeException failure) { + if (failure instanceof CanonicalGameplayBindingInventoryConflictException) throw failure; + throw new CanonicalGameplayBindingInventoryConflictException( + "Issuer admission-control SQL connection state is unavailable", failure); + } + } + + private static CanonicalGameplayBindingInventoryConflictException conflict(String message) { + return new CanonicalGameplayBindingInventoryConflictException(message); + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionControlValue.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionControlValue.java new file mode 100644 index 0000000000..73607681d6 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionControlValue.java @@ -0,0 +1,473 @@ +package net.firedevops.firemud.gamesession.repository; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.DataInputStream; +import java.io.DataOutputStream; +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.security.MessageDigest; +import java.util.Arrays; +import java.util.HexFormat; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; + +/** Exact live issuer admission-control value, in its own epoch domain from the V1030 layout. */ +final class CanonicalGameplayIssuerAdmissionControlValue { + static final String SCHEMA = "gs_issuer_admission_control/v1"; + static final int MAX_BYTES = 512 * 1024; + private static final String ENCODING = "canonical-live-issuer-admission-control/v1"; + + enum State { + OPEN, + CUTOFF_PENDING, + INSTALLED + } + + enum OperationKind { + INITIAL_ANCHOR_INSTALL, + CUTOFF + } + + private final String issuerId; + private final State state; + private final BigInteger liveBarrierEpoch; + private final UUID currentOperationId; + private final OperationKind currentOperationKind; + private final UUID bootstrapOperationId; + private final UUID bootstrapRequestId; + private final BigInteger bootstrapControlEpoch; + private final byte[] anchorExactBytes; + private final String anchorExactDigest; + private final BigInteger accountIssuerAuthGeneration; + private final byte[] accountCheckpointBytes; + private final String accountCheckpointDigest; + private final byte[] accountSourceEventBytes; + private final String accountSourceEventDigest; + private final byte[] stableIncarnationBytes; + private final String stableIncarnationDigest; + private final BigInteger inventorySnapshotRevision; + private final long cohortRowCount; + private final String cohortDigest; + private final byte[] exactBytes; + private final String exactDigest; + + private CanonicalGameplayIssuerAdmissionControlValue( + String issuerId, + State state, + BigInteger liveBarrierEpoch, + UUID currentOperationId, + OperationKind currentOperationKind, + UUID bootstrapOperationId, + UUID bootstrapRequestId, + BigInteger bootstrapControlEpoch, + byte[] anchorExactBytes, + String anchorExactDigest, + BigInteger accountIssuerAuthGeneration, + byte[] accountCheckpointBytes, + String accountCheckpointDigest, + byte[] accountSourceEventBytes, + String accountSourceEventDigest, + byte[] stableIncarnationBytes, + String stableIncarnationDigest, + BigInteger inventorySnapshotRevision, + long cohortRowCount, + String cohortDigest) { + this.issuerId = requireIssuer(issuerId); + this.state = Objects.requireNonNull(state, "state"); + this.liveBarrierEpoch = requirePositive(liveBarrierEpoch, "liveBarrierEpoch"); + this.currentOperationId = requireNonNil(currentOperationId, "currentOperationId"); + this.currentOperationKind = Objects.requireNonNull(currentOperationKind, "currentOperationKind"); + this.bootstrapOperationId = requireNonNil(bootstrapOperationId, "bootstrapOperationId"); + this.bootstrapRequestId = requireNonNil(bootstrapRequestId, "bootstrapRequestId"); + this.bootstrapControlEpoch = requirePositive(bootstrapControlEpoch, "bootstrapControlEpoch"); + this.anchorExactBytes = nonEmpty(anchorExactBytes, "anchorExactBytes"); + this.anchorExactDigest = requireDigest(anchorExactDigest, "anchorExactDigest"); + requireDigestMatches(this.anchorExactBytes, this.anchorExactDigest, "installed anchor"); + this.accountIssuerAuthGeneration = + requirePositive(accountIssuerAuthGeneration, "accountIssuerAuthGeneration"); + this.accountCheckpointBytes = nonEmpty(accountCheckpointBytes, "accountCheckpointBytes"); + this.accountCheckpointDigest = requireDigest(accountCheckpointDigest, "accountCheckpointDigest"); + requireDigestMatches( + this.accountCheckpointBytes, this.accountCheckpointDigest, "Account checkpoint"); + if ((accountSourceEventBytes == null) != (accountSourceEventDigest == null)) { + throw new IllegalArgumentException("Account source event bytes and digest must be paired"); + } + this.accountSourceEventBytes = + accountSourceEventBytes == null ? null : nonEmpty(accountSourceEventBytes, "accountSourceEventBytes"); + this.accountSourceEventDigest = + accountSourceEventDigest == null ? null : requireDigest(accountSourceEventDigest, "accountSourceEventDigest"); + if (this.accountSourceEventBytes != null) { + requireDigestMatches( + this.accountSourceEventBytes, this.accountSourceEventDigest, "Account source event"); + } + this.stableIncarnationBytes = nonEmpty(stableIncarnationBytes, "stableIncarnationBytes"); + this.stableIncarnationDigest = requireDigest(stableIncarnationDigest, "stableIncarnationDigest"); + requireDigestMatches( + this.stableIncarnationBytes, this.stableIncarnationDigest, "stable incarnation"); + this.inventorySnapshotRevision = + requirePositive(inventorySnapshotRevision, "inventorySnapshotRevision"); + if (cohortRowCount < 0) throw new IllegalArgumentException("cohortRowCount must not be negative"); + this.cohortRowCount = cohortRowCount; + this.cohortDigest = requireDigest(cohortDigest, "cohortDigest"); + if ((state == State.OPEN) != (currentOperationKind == OperationKind.INITIAL_ANCHOR_INSTALL)) { + throw new IllegalArgumentException("Only the initial-anchor install may establish OPEN"); + } + this.exactBytes = encode(); + if (exactBytes.length > MAX_BYTES) { + throw new IllegalArgumentException("Issuer admission-control value exceeds its bound"); + } + this.exactDigest = sha256(exactBytes); + } + + static CanonicalGameplayIssuerAdmissionControlValue initialOpen( + CanonicalGameplayIssuerInstalledAnchor anchor, + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState current, + BigInteger liveBarrierEpoch, + long cohortRowCount, + String cohortDigest) { + Objects.requireNonNull(anchor, "anchor"); + Objects.requireNonNull(current, "current"); + var checkpoint = current.accountCheckpoint(); + byte[] anchorBytes = anchor.exactAnchorBytes(); + if (!anchor.issuerId().equals(checkpoint.issuerId()) + || !anchor.issuerAuthGeneration().equals(checkpoint.issuerAuthGeneration()) + || !Arrays.equals(anchor.sourceCheckpointBytes(), checkpoint.exactCheckpointBytes()) + || !Objects.equals(anchor.sourceEventDigest(), checkpoint.latestIssuerEventDigest()) + || !Arrays.equals(anchor.sourceEventBytes(), checkpoint.latestIssuerEventBytes()) + || !Arrays.equals( + anchor.incarnationBytes(), + CanonicalGameplayIssuerInstalledAnchor.encodeIncarnation(current.incarnation()))) { + throw new IllegalArgumentException("Live issuer control requires the exact current anchor sources"); + } + return new CanonicalGameplayIssuerAdmissionControlValue( + anchor.issuerId(), + State.OPEN, + liveBarrierEpoch, + anchor.bootstrapOperationId(), + OperationKind.INITIAL_ANCHOR_INSTALL, + anchor.bootstrapOperationId(), + anchor.bootstrapRequestId(), + anchor.controlEpoch(), + anchorBytes, + sha256(anchorBytes), + checkpoint.issuerAuthGeneration(), + checkpoint.exactCheckpointBytes(), + checkpoint.checkpointDigest(), + checkpoint.latestIssuerEventBytes(), + checkpoint.latestIssuerEventDigest(), + anchor.incarnationBytes(), + anchor.incarnationDigest(), + anchor.issuerInventorySnapshotRevision(), + cohortRowCount, + cohortDigest); + } + + CanonicalGameplayIssuerAdmissionControlValue cutoffPending( + UUID cutoffOperationId, + BigInteger targetLiveBarrierEpoch, + BigInteger snapshotRevision, + long frozenCohortRowCount, + String frozenCohortDigest) { + if (state != State.OPEN + || currentOperationKind != OperationKind.INITIAL_ANCHOR_INSTALL + || targetLiveBarrierEpoch.compareTo(liveBarrierEpoch) <= 0) { + throw new IllegalArgumentException("Issuer cutoff must advance the live admission epoch"); + } + return new CanonicalGameplayIssuerAdmissionControlValue( + issuerId, + State.CUTOFF_PENDING, + targetLiveBarrierEpoch, + requireNonNil(cutoffOperationId, "cutoffOperationId"), + OperationKind.CUTOFF, + bootstrapOperationId, + bootstrapRequestId, + bootstrapControlEpoch, + anchorExactBytes, + anchorExactDigest, + accountIssuerAuthGeneration, + accountCheckpointBytes, + accountCheckpointDigest, + accountSourceEventBytes, + accountSourceEventDigest, + stableIncarnationBytes, + stableIncarnationDigest, + snapshotRevision, + frozenCohortRowCount, + frozenCohortDigest); + } + + CanonicalGameplayIssuerAdmissionControlValue installed() { + if (state != State.CUTOFF_PENDING || currentOperationKind != OperationKind.CUTOFF) { + throw new IllegalArgumentException("Only a pending cutoff can become installed"); + } + return new CanonicalGameplayIssuerAdmissionControlValue( + issuerId, + State.INSTALLED, + liveBarrierEpoch, + currentOperationId, + currentOperationKind, + bootstrapOperationId, + bootstrapRequestId, + bootstrapControlEpoch, + anchorExactBytes, + anchorExactDigest, + accountIssuerAuthGeneration, + accountCheckpointBytes, + accountCheckpointDigest, + accountSourceEventBytes, + accountSourceEventDigest, + stableIncarnationBytes, + stableIncarnationDigest, + inventorySnapshotRevision, + cohortRowCount, + cohortDigest); + } + + static CanonicalGameplayIssuerAdmissionControlValue decode(byte[] bytes) { + if (bytes == null || bytes.length == 0 || bytes.length > MAX_BYTES) throw malformed(); + try (DataInputStream in = new DataInputStream(new ByteArrayInputStream(bytes))) { + if (!ENCODING.equals(readText(in))) throw malformed(); + CanonicalGameplayIssuerAdmissionControlValue result = + new CanonicalGameplayIssuerAdmissionControlValue( + readText(in), + State.valueOf(readText(in)), + readPositive(in), + readUuid(in), + OperationKind.valueOf(readText(in)), + readUuid(in), + readUuid(in), + readPositive(in), + readBytes(in), + readText(in), + readPositive(in), + readBytes(in), + readText(in), + readNullableBytes(in), + readNullableText(in), + readBytes(in), + readText(in), + readPositive(in), + in.readLong(), + readText(in)); + if (in.available() != 0 || !Arrays.equals(bytes, result.exactBytes())) throw malformed(); + return result; + } catch (IOException | RuntimeException invalid) { + throw malformed(); + } + } + + private byte[] encode() { + return encode( + out -> { + writeText(out, ENCODING); + writeText(out, issuerId); + writeText(out, state.name()); + writeBigInteger(out, liveBarrierEpoch); + writeUuid(out, currentOperationId); + writeText(out, currentOperationKind.name()); + writeUuid(out, bootstrapOperationId); + writeUuid(out, bootstrapRequestId); + writeBigInteger(out, bootstrapControlEpoch); + writeBytes(out, anchorExactBytes); + writeText(out, anchorExactDigest); + writeBigInteger(out, accountIssuerAuthGeneration); + writeBytes(out, accountCheckpointBytes); + writeText(out, accountCheckpointDigest); + writeNullableBytes(out, accountSourceEventBytes); + writeNullableText(out, accountSourceEventDigest); + writeBytes(out, stableIncarnationBytes); + writeText(out, stableIncarnationDigest); + writeBigInteger(out, inventorySnapshotRevision); + out.writeLong(cohortRowCount); + writeText(out, cohortDigest); + }); + } + + boolean matchesCurrentIssuerState( + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState current) { + Objects.requireNonNull(current, "current"); + var checkpoint = current.accountCheckpoint(); + return issuerId.equals(checkpoint.issuerId()) + && accountIssuerAuthGeneration.equals(checkpoint.issuerAuthGeneration()) + && Arrays.equals(accountCheckpointBytes, checkpoint.exactCheckpointBytes()) + && accountCheckpointDigest.equals(checkpoint.checkpointDigest()) + && Arrays.equals(accountSourceEventBytes, checkpoint.latestIssuerEventBytes()) + && Objects.equals(accountSourceEventDigest, checkpoint.latestIssuerEventDigest()) + && Arrays.equals( + stableIncarnationBytes, + CanonicalGameplayIssuerInstalledAnchor.encodeIncarnation(current.incarnation())); + } + + String issuerId() { return issuerId; } + State state() { return state; } + BigInteger liveBarrierEpoch() { return liveBarrierEpoch; } + UUID currentOperationId() { return currentOperationId; } + OperationKind currentOperationKind() { return currentOperationKind; } + UUID bootstrapOperationId() { return bootstrapOperationId; } + UUID bootstrapRequestId() { return bootstrapRequestId; } + BigInteger bootstrapControlEpoch() { return bootstrapControlEpoch; } + byte[] anchorExactBytes() { return anchorExactBytes.clone(); } + String anchorExactDigest() { return anchorExactDigest; } + BigInteger accountIssuerAuthGeneration() { return accountIssuerAuthGeneration; } + byte[] accountCheckpointBytes() { return accountCheckpointBytes.clone(); } + String accountCheckpointDigest() { return accountCheckpointDigest; } + byte[] accountSourceEventBytes() { return accountSourceEventBytes == null ? null : accountSourceEventBytes.clone(); } + String accountSourceEventDigest() { return accountSourceEventDigest; } + byte[] stableIncarnationBytes() { return stableIncarnationBytes.clone(); } + String stableIncarnationDigest() { return stableIncarnationDigest; } + BigInteger inventorySnapshotRevision() { return inventorySnapshotRevision; } + long cohortRowCount() { return cohortRowCount; } + String cohortDigest() { return cohortDigest; } + byte[] exactBytes() { return exactBytes.clone(); } + String exactDigest() { return exactDigest; } + + static String sha256(byte[] bytes) { + try { + return "sha256:" + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (Exception failure) { + throw new IllegalStateException("Could not digest exact issuer admission-control bytes", failure); + } + } + + private static byte[] encode(Writer writer) { + try { + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + try (DataOutputStream out = new DataOutputStream(bytes)) { + writer.write(out); + } + return bytes.toByteArray(); + } catch (IOException impossible) { + throw new IllegalStateException("Could not encode issuer admission-control bytes", impossible); + } + } + + private static void writeText(DataOutputStream out, String value) throws IOException { + byte[] bytes = Objects.requireNonNull(value, "text").getBytes(StandardCharsets.UTF_8); + writeBytes(out, bytes); + } + + private static void writeBytes(DataOutputStream out, byte[] value) throws IOException { + if (value == null || value.length == 0 || value.length > MAX_BYTES) { + throw new IllegalArgumentException("Control bytes are outside their bound"); + } + out.writeInt(value.length); + out.write(value); + } + + private static void writeNullableBytes(DataOutputStream out, byte[] value) throws IOException { + out.writeBoolean(value != null); + if (value != null) writeBytes(out, value); + } + + private static void writeNullableText(DataOutputStream out, String value) throws IOException { + out.writeBoolean(value != null); + if (value != null) writeText(out, value); + } + + private static void writeUuid(DataOutputStream out, UUID value) throws IOException { + writeText(out, requireNonNil(value, "uuid").toString()); + } + + private static void writeBigInteger(DataOutputStream out, BigInteger value) throws IOException { + writeText(out, requirePositive(value, "counter").toString()); + } + + private static String readText(DataInputStream in) throws IOException { + byte[] bytes = readBytes(in); + try { + return StandardCharsets.UTF_8.newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(bytes)) + .toString(); + } catch (CharacterCodingException invalid) { + throw malformed(); + } + } + + private static byte[] readBytes(DataInputStream in) throws IOException { + int length = in.readInt(); + if (length < 1 || length > MAX_BYTES || length > in.available()) throw malformed(); + return in.readNBytes(length); + } + + private static byte[] readNullableBytes(DataInputStream in) throws IOException { + return in.readBoolean() ? readBytes(in) : null; + } + + private static String readNullableText(DataInputStream in) throws IOException { + return in.readBoolean() ? readText(in) : null; + } + + private static UUID readUuid(DataInputStream in) throws IOException { + String value = readText(in); + UUID uuid; + try { + uuid = UUID.fromString(value); + } catch (RuntimeException malformed) { + throw malformed(); + } + if (!uuid.toString().equals(value) || uuid.equals(new UUID(0L, 0L))) throw malformed(); + return uuid; + } + + private static BigInteger readPositive(DataInputStream in) throws IOException { + String value = readText(in); + if (!value.matches("[1-9][0-9]{0,255}")) throw malformed(); + return new BigInteger(value); + } + + private static String requireIssuer(String issuerId) { + if (!GameSessionAccountDelegationProfile.ISSUER.equals(issuerId)) { + throw new IllegalArgumentException("Live issuer control requires the exact Account issuer"); + } + return issuerId; + } + + private static UUID requireNonNil(UUID value, String name) { + Objects.requireNonNull(value, name); + if (value.equals(new UUID(0L, 0L))) throw new IllegalArgumentException(name + " must not be nil"); + return value; + } + + private static BigInteger requirePositive(BigInteger value, String name) { + Objects.requireNonNull(value, name); + if (value.signum() <= 0 || value.toString().length() > 256) { + throw new IllegalArgumentException(name + " must be a bounded positive integer"); + } + return value; + } + + private static byte[] nonEmpty(byte[] value, String name) { + Objects.requireNonNull(value, name); + if (value.length == 0 || value.length > MAX_BYTES) { + throw new IllegalArgumentException(name + " is outside its byte bound"); + } + return value.clone(); + } + + private static String requireDigest(String digest, String name) { + Objects.requireNonNull(digest, name); + if (!digest.matches("sha256:[0-9a-f]{64}")) throw new IllegalArgumentException(name + " is malformed"); + return digest; + } + + private static void requireDigestMatches(byte[] bytes, String digest, String name) { + if (!sha256(bytes).equals(digest)) throw new IllegalArgumentException(name + " digest differs"); + } + + private static IllegalArgumentException malformed() { + return new IllegalArgumentException("Issuer admission-control value is malformed"); + } + + @FunctionalInterface + private interface Writer { + void write(DataOutputStream out) throws IOException; + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalProjectionRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalProjectionRepository.java index f50da2b422..403715a8c5 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalProjectionRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalProjectionRepository.java @@ -91,6 +91,7 @@ private PreparedPartitionWork readPreparedPartitionWork( transaction, target, anchor, + before, prepareAddMutation, requireCurrentTargetAccountControl); }); @@ -116,7 +117,7 @@ PreparedPartitionWork readPreparedPartitionWorkInTransaction( CanonicalGameplayIssuerBootstrapCoverageRepository .readInstalledAnchorForBindingPreparationInTransaction(transaction, currentState); requireSameAnchor(target.anchor(), anchor); - return prepareInTransaction(transaction, target, anchor, false, true); + return prepareInTransaction(transaction, target, anchor, currentState, false, true); } /** Re-reads the durable set and all currentness inputs after the Redis round trip. */ @@ -147,8 +148,15 @@ private PreparedPartitionWork prepareInTransaction( DSLContext transaction, CanonicalGameplayIssuerBindingLocalOperation target, CanonicalGameplayIssuerInstalledAnchor anchor, + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState currentState, boolean prepareAddMutation, boolean requireCurrentTargetAccountControl) { + if (requireCurrentTargetAccountControl) { + // ADD and admitting ACK join live OPEN control. Historical release/retirement reads + // retain their original source guards without claiming new admission authority. + CanonicalGameplayIssuerAdmissionControlRepository.requireOpenInTransaction( + transaction, anchor, currentState); + } BigInteger targetPartition = target.reservation().partitionId(); CanonicalGameplayIssuerPartitionMutationRepository.PartitionMutationHead mutationHead = CanonicalGameplayIssuerPartitionMutationRepository.readHeadInTransaction( diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCandidate.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCandidate.java new file mode 100644 index 0000000000..62b39b3e36 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCandidate.java @@ -0,0 +1,215 @@ +package net.firedevops.firemud.gamesession.repository; + +import java.math.BigInteger; +import java.util.Arrays; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAdmissionDecision; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingIdentity; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingInventoryEntry; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingProvisionalCasEvidence; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingRef; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingTransitionSnapshot; +import net.firedevops.firemud.gamesession.binding.CanonicalIssuerPartitionReservation; +import net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget; + +/** + * Exact, typed source bytes for the non-admitting original {@code NEW} session candidate. + * + *

This is a data carrier only. It does not prove that any input came from Account or the + * durable Game Session owners, establish a physical Redis readback, finalize the Account lease, or + * authorize gameplay. Authenticated session readers must reject its separate purpose discriminator. + * + *

The payload retains the complete immutable Account lease and original decision sources plus + * the durable candidate, transition, reservation, and target identities. It deliberately omits + * mutable preparation status and current inventory revisions so a retry after unrelated SQL + * inventory progress reproduces the original candidate bytes. + */ +public final class CanonicalGameplayOriginalNewCandidate { + public static final String PURPOSE = "original-new-non-admitting-candidate/v1"; + + private final UUID bindingDecisionId; + private final AccountGameplayAdmissionLeaseEvidence leaseEvidence; + private final CanonicalGameplayBindingIdentity bindingIdentity; + private final CanonicalPlayableTarget targetEvidence; + private final TransitionSource transition; + private final ReservationSource reservation; + + CanonicalGameplayOriginalNewCandidate( + UUID bindingDecisionId, + AccountGameplayAdmissionLeaseEvidence leaseEvidence, + CanonicalGameplayBindingIdentity bindingIdentity, + CanonicalPlayableTarget targetEvidence, + TransitionSource transition, + ReservationSource reservation) { + this.bindingDecisionId = Objects.requireNonNull(bindingDecisionId, "bindingDecisionId"); + this.leaseEvidence = Objects.requireNonNull(leaseEvidence, "leaseEvidence"); + this.bindingIdentity = Objects.requireNonNull(bindingIdentity, "bindingIdentity"); + this.targetEvidence = Objects.requireNonNull(targetEvidence, "targetEvidence"); + this.transition = Objects.requireNonNull(transition, "transition"); + this.reservation = Objects.requireNonNull(reservation, "reservation"); + } + + /** + * Freezes the selected original sources after checking their shared identity and NEW-only + * preconditions. This factory is structural and does not elevate either source to authority. + */ + static CanonicalGameplayOriginalNewCandidate fromOriginalSources( + CanonicalGameplayBindingProvisionalCasEvidence provisionalEvidence, + CanonicalGameplayAdmissionDecision originalDecision) { + Objects.requireNonNull(provisionalEvidence, "provisionalEvidence"); + Objects.requireNonNull(originalDecision, "originalDecision"); + CanonicalGameplayOriginalNewCandidateCodec.requireOriginalNewSources( + provisionalEvidence, originalDecision); + CanonicalGameplayBindingTransitionSnapshot transition = provisionalEvidence.transition(); + CanonicalGameplayBindingInventoryEntry candidate = provisionalEvidence.candidate(); + CanonicalIssuerPartitionReservation reservation = provisionalEvidence.candidateReservation(); + return new CanonicalGameplayOriginalNewCandidate( + originalDecision.bindingDecisionId(), + originalDecision.leaseEvidence(), + candidate.identity(), + originalDecision.targetEvidence(), + new TransitionSource( + transition.transitionId(), + transition.bindingRef(), + transition.bindingGeneration(), + transition.issuerReservationId(), + transition.reservationFence(), + transition.candidateAccountIndexFence()), + CanonicalGameplayOriginalNewCandidateCodec.reservationSource(reservation)); + } + + /** Parses only this closed candidate format; the result is not a verified readback capability. */ + public static CanonicalGameplayOriginalNewCandidate parseCanonical(byte[] encoded) { + return CanonicalGameplayOriginalNewCandidateCodec.decode(encoded); + } + + public UUID bindingDecisionId() { + return bindingDecisionId; + } + + /** Complete immutable lease carrier, including its unchanged baseline, tuple, and checkpoints. */ + public AccountGameplayAdmissionLeaseEvidence leaseEvidence() { + return leaseEvidence; + } + + /** Exact canonical session identity from which the session key is derived by its owner. */ + public CanonicalGameplayBindingIdentity bindingIdentity() { + return bindingIdentity; + } + + /** Full original canonical target source retained with the decision. */ + public CanonicalPlayableTarget targetEvidence() { + return targetEvidence; + } + + /** Stable transition identity and fences used by the original provisional CAS. */ + public TransitionSource transition() { + return transition; + } + + /** Immutable reservation identity, fences and original snapshot; current revisions may advance. */ + public ReservationSource reservation() { + return reservation; + } + + /** The one exact canonical JSON preimage to install and later exact-compare. */ + public byte[] canonicalBytes() { + return CanonicalGameplayOriginalNewCandidateCodec.encode(this); + } + + public String canonicalJson() { + return new String(canonicalBytes(), java.nio.charset.StandardCharsets.UTF_8); + } + + /** Exact byte comparison for a physical preimage/readback or final-CAS expected value. */ + public boolean exactlyMatches(byte[] physicalValue) { + return physicalValue != null && Arrays.equals(canonicalBytes(), physicalValue); + } + + /** + * Compares every retained original-decision field. The decision class has no value equality, so + * this comparison is explicit and includes its complete Account lease and full target source. + */ + public boolean matchesOriginalDecision(CanonicalGameplayAdmissionDecision decision) { + return CanonicalGameplayOriginalNewCandidateCodec.matchesOriginalDecision(this, decision); + } + + /** Checks stable source identity while allowing only the documented PREPARED/PROVISIONAL retry. */ + public boolean matchesProvisionalSources( + CanonicalGameplayBindingProvisionalCasEvidence evidence) { + return CanonicalGameplayOriginalNewCandidateCodec.matchesProvisionalSources(this, evidence); + } + + @Override + public boolean equals(Object other) { + return other instanceof CanonicalGameplayOriginalNewCandidate candidate + && Arrays.equals(canonicalBytes(), candidate.canonicalBytes()); + } + + @Override + public int hashCode() { + return Arrays.hashCode(canonicalBytes()); + } + + /** Avoid logging the lease or source payload through implicit object formatting. */ + @Override + public String toString() { + return "CanonicalGameplayOriginalNewCandidate[purpose=" + PURPOSE + ", nonAdmitting=true]"; + } + + /** Immutable stable projection of the transition's original identity and fences. */ + public record TransitionSource( + UUID transitionId, + CanonicalGameplayBindingRef bindingRef, + BigInteger bindingGeneration, + UUID issuerReservationId, + UUID reservationFence, + UUID candidateAccountIndexFence) { + public TransitionSource { + Objects.requireNonNull(transitionId, "transitionId"); + Objects.requireNonNull(bindingRef, "bindingRef"); + requirePositive(bindingGeneration, "bindingGeneration"); + Objects.requireNonNull(issuerReservationId, "issuerReservationId"); + Objects.requireNonNull(reservationFence, "reservationFence"); + Objects.requireNonNull(candidateAccountIndexFence, "candidateAccountIndexFence"); + } + } + + /** Immutable reservation source fields; the current mutable inventory revision is excluded. */ + public record ReservationSource( + UUID reservationId, + CanonicalGameplayBindingRef ownerBindingRef, + BigInteger bindingGeneration, + UUID transitionId, + BigInteger partitionId, + UUID reservationFence, + UUID issuerCoverageOperationId, + BigInteger issuerCoverageOperationFence, + BigInteger coverageFence, + BigInteger inventorySnapshotRevision) { + public ReservationSource { + Objects.requireNonNull(reservationId, "reservationId"); + Objects.requireNonNull(ownerBindingRef, "ownerBindingRef"); + requirePositive(bindingGeneration, "bindingGeneration"); + Objects.requireNonNull(transitionId, "transitionId"); + requireNonNegative(partitionId, "partitionId"); + Objects.requireNonNull(reservationFence, "reservationFence"); + Objects.requireNonNull(issuerCoverageOperationId, "issuerCoverageOperationId"); + requirePositive(issuerCoverageOperationFence, "issuerCoverageOperationFence"); + requirePositive(coverageFence, "coverageFence"); + requirePositive(inventorySnapshotRevision, "inventorySnapshotRevision"); + } + } + + private static void requirePositive(BigInteger value, String name) { + Objects.requireNonNull(value, name); + if (value.signum() <= 0) throw new IllegalArgumentException(name + " must be positive"); + } + + private static void requireNonNegative(BigInteger value, String name) { + Objects.requireNonNull(value, name); + if (value.signum() < 0) throw new IllegalArgumentException(name + " must not be negative"); + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCandidateCodec.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCandidateCodec.java new file mode 100644 index 0000000000..348785dc12 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCandidateCodec.java @@ -0,0 +1,721 @@ +package net.firedevops.firemud.gamesession.repository; + +import com.fasterxml.jackson.core.JsonFactory; +import com.fasterxml.jackson.core.StreamReadConstraints; +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.time.Instant; +import java.util.Arrays; +import java.util.Base64; +import java.util.HashSet; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAdmissionDecision; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingIdentity; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingInventoryEntry; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingProvisionalCasEvidence; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingRef; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingTransitionSnapshot; +import net.firedevops.firemud.gamesession.binding.CanonicalIssuerPartitionReservation; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionOwnerProof; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionRequest; +import net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget; + +/** Closed, bounded RFC 8785 codec for the distinct original-NEW candidate purpose. */ +final class CanonicalGameplayOriginalNewCandidateCodec { + static final int MAX_CANDIDATE_BYTES = 128 * 1024; + private static final int MAX_COUNTER_DIGITS = 256; + private static final Pattern POSITIVE_DECIMAL = Pattern.compile("[1-9][0-9]{0,255}"); + private static final Pattern NON_NEGATIVE_DECIMAL = Pattern.compile("(?:0|[1-9][0-9]{0,255})"); + private static final JsonFactory JSON_FACTORY = + JsonFactory.builder() + .streamReadConstraints( + StreamReadConstraints.builder() + .maxNestingDepth(12) + .maxStringLength(MAX_CANDIDATE_BYTES) + .maxNumberLength(8) + .build()) + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .build(); + private static final ObjectMapper JSON = + new ObjectMapper(JSON_FACTORY).enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS); + private static final Set ROOT_FIELDS = + Set.of("purpose", "bindingDecisionId", "leaseEvidence", "binding", "target", "transition", "reservation"); + private static final Set BINDING_FIELDS = + Set.of( + "accountId", + "tenantId", + "playableStateNamespaceId", + "characterId", + "playableStateScope", + "gameInstanceId", + "runtimeGameInstanceId", + "sessionId", + "regionId", + "regionEpoch", + "issuerId", + "issuerAuthGeneration", + "issuerIndexLayoutVersion", + "issuerIndexPartitionCount", + "issuerIndexPartitionCapacity"); + private static final Set TARGET_FIELDS = + Set.of( + "targetNamespace", + "tenantSlug", + "canonicalTenantId", + "worldSlug", + "worldDisplayName", + "realmId", + "realmSlug", + "realmDisplayName", + "gameSessionTenantId", + "gameInstanceId", + "playableStateNamespaceId", + "playableStateScope", + "canonicalGameInstanceId", + "canonicalVersionId", + "runtimeVersionId", + "catalogRevision", + "pointerVersion", + "admissionPointerSnapshotDigest", + "activeWorldEpoch", + "initialAdmissionRequestId", + "initialAdmissionRequestDigest", + "initialAdmissionOriginKind", + "holdId", + "holdFence", + "holdBindingDigest", + "auditEventId", + "ownerProofDigest", + "ownerProofOutcome", + "positiveDurableAbort", + "ownerProofTerminalAt", + "characterCreationPolicy"); + private static final Set TRANSITION_FIELDS = + Set.of( + "transitionId", + "bindingRef", + "bindingGeneration", + "issuerReservationId", + "reservationFence", + "candidateAccountIndexFence"); + private static final Set RESERVATION_FIELDS = + Set.of( + "reservationId", + "ownerBindingRef", + "bindingGeneration", + "transitionId", + "partitionId", + "lifecycle", + "reservationFence", + "issuerCoverageOperationId", + "issuerCoverageOperationFence", + "coverageFence", + "inventorySnapshotRevision"); + + private CanonicalGameplayOriginalNewCandidateCodec() {} + + static byte[] encode(CanonicalGameplayOriginalNewCandidate candidate) { + Objects.requireNonNull(candidate, "candidate"); + try { + requireCounterLimit(candidate.bindingIdentity().regionEpoch(), "regionEpoch", false); + requireCounterLimit( + candidate.bindingIdentity().issuerAuthGeneration(), "issuerAuthGeneration", false); + requireCounterLimit( + candidate.bindingIdentity().issuerIndexLayoutVersion(), + "issuerIndexLayoutVersion", + false); + requireCounterLimit( + candidate.bindingIdentity().issuerIndexPartitionCount(), + "issuerIndexPartitionCount", + false); + requireCounterLimit( + candidate.bindingIdentity().issuerIndexPartitionCapacity(), + "issuerIndexPartitionCapacity", + false); + requireCounterLimit(candidate.transition().bindingGeneration(), "bindingGeneration", false); + requireCounterLimit( + candidate.reservation().bindingGeneration(), "reservation.bindingGeneration", false); + requireCounterLimit(candidate.reservation().partitionId(), "partitionId", true); + requireCounterLimit( + candidate.reservation().issuerCoverageOperationFence(), + "issuerCoverageOperationFence", + false); + requireCounterLimit(candidate.reservation().coverageFence(), "coverageFence", false); + requireCounterLimit(candidate.reservation().inventorySnapshotRevision(), + "inventorySnapshotRevision", false); + + ObjectNode root = JSON.createObjectNode(); + root.put("purpose", CanonicalGameplayOriginalNewCandidate.PURPOSE); + root.put("bindingDecisionId", candidate.bindingDecisionId().toString()); + root.set("leaseEvidence", parseCanonicalLeaseNode(candidate.leaseEvidence())); + root.set("binding", bindingNode(candidate.bindingIdentity())); + root.set("target", targetNode(candidate.targetEvidence())); + root.set("transition", transitionNode(candidate.transition())); + root.set("reservation", reservationNode(candidate.reservation())); + byte[] canonical = Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(root)); + if (canonical.length == 0 || canonical.length > MAX_CANDIDATE_BYTES) { + throw invalid("Original NEW candidate exceeds its 128 KiB resource bound"); + } + return canonical; + } catch (IOException failure) { + throw new IllegalArgumentException("Could not encode original NEW candidate", failure); + } + } + + static CanonicalGameplayOriginalNewCandidate decode(byte[] encoded) { + Objects.requireNonNull(encoded, "encoded"); + if (encoded.length == 0 || encoded.length > MAX_CANDIDATE_BYTES) { + throw invalid("Original NEW candidate is empty or exceeds its resource bound"); + } + String json = decodeUtf8(encoded); + try { + ObjectNode root = requireObject(JSON.readTree(json), "candidate"); + requireFields(root, ROOT_FIELDS, "candidate"); + if (!text(root, "purpose").equals(CanonicalGameplayOriginalNewCandidate.PURPOSE)) { + throw invalid("Candidate purpose is unsupported"); + } + + AccountGameplayAdmissionLeaseEvidence leaseEvidence = + parseLeaseEvidence(root.get("leaseEvidence")); + CanonicalGameplayBindingIdentity binding = parseBinding(root.get("binding")); + CanonicalPlayableTarget target = parseTarget(root.get("target")); + CanonicalGameplayOriginalNewCandidate.TransitionSource transition = + parseTransition(root.get("transition")); + CanonicalGameplayOriginalNewCandidate.ReservationSource reservation = + parseReservation(root.get("reservation")); + UUID decisionId = uuid(root, "bindingDecisionId"); + + var decoded = + new CanonicalGameplayOriginalNewCandidate( + decisionId, leaseEvidence, binding, target, transition, reservation); + validateDecodedSources(decoded); + if (!Arrays.equals(encode(decoded), encoded)) { + throw invalid("Original NEW candidate bytes are not canonical"); + } + return decoded; + } catch (IOException failure) { + throw new IllegalArgumentException("Malformed original NEW candidate", failure); + } + } + + static boolean matchesOriginalDecision( + CanonicalGameplayOriginalNewCandidate candidate, + CanonicalGameplayAdmissionDecision decision) { + return decision != null + && decision.status() == CanonicalGameplayAdmissionDecision.Status.PROVISIONAL + && candidate.bindingDecisionId().equals(decision.bindingDecisionId()) + && candidate.leaseEvidence().hasSameIdentity(decision.leaseEvidence()) + && candidate.bindingIdentity().equals(decision.candidate()) + && candidate.transition().bindingGeneration().equals(decision.bindingGeneration()) + && decision.expectedOldBindingGeneration() == null + && decision.resumeEpisodeId() == null + && candidate.targetEvidence().equals(decision.targetEvidence()) + && isPublicProductionNewLease(decision.leaseEvidence()); + } + + static boolean matchesProvisionalSources( + CanonicalGameplayOriginalNewCandidate candidate, + CanonicalGameplayBindingProvisionalCasEvidence evidence) { + if (evidence == null) return false; + try { + requireCandidateSourceShape(evidence); + CanonicalGameplayBindingTransitionSnapshot transition = evidence.transition(); + CanonicalGameplayBindingInventoryEntry entry = evidence.candidate(); + CanonicalIssuerPartitionReservation reservation = evidence.candidateReservation(); + return candidate.bindingIdentity().equals(entry.identity()) + && candidate.transition().transitionId().equals(transition.transitionId()) + && candidate.transition().bindingRef().equals(transition.bindingRef()) + && candidate.transition().bindingGeneration().equals(transition.bindingGeneration()) + && candidate.transition().issuerReservationId().equals(transition.issuerReservationId()) + && candidate.transition().reservationFence().equals(transition.reservationFence()) + && candidate.transition() + .candidateAccountIndexFence() + .equals(transition.candidateAccountIndexFence()) + && candidate.transition().bindingRef().equals(entry.bindingRef()) + && candidate.transition().bindingGeneration().equals(entry.bindingGeneration()) + && candidate.transition().candidateAccountIndexFence().equals(entry.accountIndexFence()) + && candidate.reservation().equals(reservationSource(reservation)); + } catch (RuntimeException invalidSource) { + return false; + } + } + + static void requireOriginalNewSources( + CanonicalGameplayBindingProvisionalCasEvidence evidence, + CanonicalGameplayAdmissionDecision decision) { + requireCandidateSourceShape(evidence); + if (!isPublicProductionNewLease(decision.leaseEvidence())) { + throw invalid("Only the selected public-production original NEW lease is supported"); + } + CanonicalGameplayBindingTransitionSnapshot transition = evidence.transition(); + CanonicalGameplayBindingInventoryEntry candidate = evidence.candidate(); + CanonicalIssuerPartitionReservation reservation = evidence.candidateReservation(); + if (!transition.transitionId().equals(decision.bindingDecisionId()) + || !candidate.identity().equals(decision.candidate()) + || !candidate.bindingGeneration().equals(decision.bindingGeneration()) + || decision.expectedOldBindingGeneration() != null + || decision.resumeEpisodeId() != null + || !candidate.identity().equals(reservation.owner()) + || !candidate.bindingGeneration().equals(reservation.bindingGeneration()) + || !transition.transitionId().equals(reservation.transitionId()) + || !transition.reservationFence().equals(reservation.reservationFence()) + || !transition.issuerReservationId().equals(reservation.reservationId())) { + throw invalid("Decision, candidate, transition, and reservation identities differ"); + } + } + + private static void requireCandidateSourceShape( + CanonicalGameplayBindingProvisionalCasEvidence evidence) { + Objects.requireNonNull(evidence, "provisionalEvidence"); + CanonicalGameplayBindingTransitionSnapshot transition = evidence.transition(); + CanonicalGameplayBindingInventoryEntry candidate = evidence.candidate(); + CanonicalIssuerPartitionReservation reservation = evidence.candidateReservation(); + if (evidence.expectedPrior() != null + || evidence.expectedPriorReservation() != null + || (transition.status() != CanonicalGameplayBindingTransitionSnapshot.Status.PREPARED + && transition.status() != CanonicalGameplayBindingTransitionSnapshot.Status.PROVISIONAL) + || transition.expectedPriorBindingRef() != null + || transition.expectedPriorBindingGeneration() != null + || !transition.transitionId().equals(candidate.transitionId()) + || !transition.bindingRef().equals(candidate.bindingRef()) + || !transition.bindingGeneration().equals(candidate.bindingGeneration()) + || !transition.candidate().equals(candidate.identity()) + || !transition.issuerReservationId().equals(candidate.issuerReservationId()) + || !transition.candidateAccountIndexFence().equals(candidate.accountIndexFence()) + || !reservation.owner().equals(candidate.identity()) + || !reservation.bindingGeneration().equals(candidate.bindingGeneration()) + || !reservation.transitionId().equals(transition.transitionId()) + || !reservation.reservationId().equals(transition.issuerReservationId()) + || !reservation.reservationFence().equals(transition.reservationFence()) + || reservation.lifecycle() != CanonicalIssuerPartitionReservation.Lifecycle.RESERVED) { + throw invalid("Source is not an exact no-prior PREPARED or PROVISIONAL NEW candidate"); + } + } + + private static boolean isPublicProductionNewLease( + AccountGameplayAdmissionLeaseEvidence evidence) { + return evidence != null + && evidence.leaseKind() == AccountGameplayAdmissionLeaseEvidence.LeaseKind.NEW_BINDING + && "PUBLIC_PRODUCTION".equals(evidence.carrier().get("mode")) + && !evidence.carrier().containsKey("expectedOldBindingGeneration") + && !evidence.carrier().containsKey("resumeEpisodeId"); + } + + private static void validateDecodedSources(CanonicalGameplayOriginalNewCandidate candidate) { + var binding = candidate.bindingIdentity(); + var transition = candidate.transition(); + var reservation = candidate.reservation(); + if (!candidate.bindingDecisionId().equals(transition.transitionId()) + || !binding.bindingRef().equals(transition.bindingRef()) + || !binding.bindingRef().equals(reservation.ownerBindingRef()) + || !transition.bindingGeneration().equals(bindingGeneration(candidate.leaseEvidence())) + || !transition.bindingGeneration().equals(reservation.bindingGeneration()) + || !transition.transitionId().equals(reservation.transitionId()) + || !transition.issuerReservationId().equals(reservation.reservationId()) + || !transition.reservationFence().equals(reservation.reservationFence()) + || !reservation.partitionId().equals(binding.bindingRef().partitionId(binding.issuerIndexPartitionCount()))) { + throw invalid("Candidate source identities, generation, or fences do not agree"); + } + if (!isPublicProductionNewLease(candidate.leaseEvidence())) { + throw invalid("Candidate does not retain the selected public-production NEW lease"); + } + try { + // Reuse the existing decision's cross-source checks. This temporary shape check is not + // returned as an original decision and establishes neither provenance nor readback. + new CanonicalGameplayAdmissionDecision( + candidate.bindingDecisionId(), + candidate.leaseEvidence(), + binding, + transition.bindingGeneration(), + null, + candidate.targetEvidence()); + } catch (RuntimeException mismatch) { + throw invalid("Candidate target differs from its complete lease binding", mismatch); + } + } + + private static BigInteger bindingGeneration(AccountGameplayAdmissionLeaseEvidence lease) { + Object scope = lease.carrier().get("bindingScope"); + if (!(scope instanceof java.util.Map map) + || !(map.get("bindingGeneration") instanceof String generation)) { + throw invalid("Lease has no binding generation"); + } + return positiveDecimal(generation, "bindingGeneration"); + } + + static CanonicalGameplayOriginalNewCandidate.ReservationSource reservationSource( + CanonicalIssuerPartitionReservation reservation) { + return new CanonicalGameplayOriginalNewCandidate.ReservationSource( + reservation.reservationId(), + reservation.owner().bindingRef(), + reservation.bindingGeneration(), + reservation.transitionId(), + reservation.partitionId(), + reservation.reservationFence(), + reservation.issuerCoverageOperationId(), + reservation.issuerCoverageOperationFence(), + reservation.coverageFence(), + reservation.inventorySnapshotRevision()); + } + + private static ObjectNode bindingNode(CanonicalGameplayBindingIdentity binding) { + ObjectNode node = JSON.createObjectNode(); + node.put("accountId", binding.accountId().toString()); + node.put("tenantId", binding.tenantId().toString()); + node.put("playableStateNamespaceId", binding.playableStateNamespaceId().toString()); + node.put("characterId", binding.characterId().toString()); + node.put("playableStateScope", binding.playableStateScope()); + node.put("gameInstanceId", binding.gameInstanceId().toString()); + node.put("runtimeGameInstanceId", Long.toString(binding.runtimeGameInstanceId())); + node.put("sessionId", binding.sessionId()); + node.put("regionId", binding.regionId().toString()); + node.put("regionEpoch", binding.regionEpoch().toString()); + node.put("issuerId", binding.issuerId()); + node.put("issuerAuthGeneration", binding.issuerAuthGeneration().toString()); + node.put("issuerIndexLayoutVersion", binding.issuerIndexLayoutVersion().toString()); + node.put("issuerIndexPartitionCount", binding.issuerIndexPartitionCount().toString()); + node.put("issuerIndexPartitionCapacity", binding.issuerIndexPartitionCapacity().toString()); + return node; + } + + private static ObjectNode targetNode(CanonicalPlayableTarget target) { + ObjectNode node = JSON.createObjectNode(); + node.put("targetNamespace", target.targetNamespace()); + node.put("tenantSlug", target.tenantSlug()); + node.put("canonicalTenantId", target.canonicalTenantId().toString()); + node.put("worldSlug", target.worldSlug()); + node.put("worldDisplayName", target.worldDisplayName()); + node.put("realmId", target.realmId().toString()); + node.put("realmSlug", target.realmSlug()); + node.put("realmDisplayName", target.realmDisplayName()); + node.put("gameSessionTenantId", Long.toString(target.gameSessionTenantId())); + node.put("gameInstanceId", Long.toString(target.gameInstanceId())); + node.put("playableStateNamespaceId", target.playableStateNamespaceId().toString()); + node.put("playableStateScope", target.playableStateScope()); + node.put("canonicalGameInstanceId", target.canonicalGameInstanceId().toString()); + node.put("canonicalVersionId", target.canonicalVersionId().toString()); + node.put("runtimeVersionId", Long.toString(target.runtimeVersionId())); + node.put("catalogRevision", Long.toString(target.catalogRevision())); + node.put("pointerVersion", Long.toString(target.pointerVersion())); + node.put("admissionPointerSnapshotDigest", target.admissionPointerSnapshotDigest()); + node.put("activeWorldEpoch", Long.toString(target.activeWorldEpoch())); + node.put("initialAdmissionRequestId", target.initialAdmissionRequestId()); + node.put("initialAdmissionRequestDigest", target.initialAdmissionRequestDigest()); + node.put("initialAdmissionOriginKind", target.initialAdmissionOriginKind().name()); + if (target.expectedPriorPointerVersion() != null) { + node.put("expectedPriorPointerVersion", Long.toString(target.expectedPriorPointerVersion())); + } + node.put("holdId", target.holdId().toString()); + node.put("holdFence", target.holdFence().toString()); + node.put("holdBindingDigest", target.holdBindingDigest()); + node.put("auditEventId", Long.toString(target.auditEventId())); + node.put("ownerProofDigest", target.ownerProofDigest()); + node.put("ownerProofOutcome", target.ownerProofOutcome().name()); + node.put("positiveDurableAbort", target.positiveDurableAbort()); + node.put("ownerProofTerminalAt", target.ownerProofTerminalAt().toString()); + node.put("characterCreationPolicy", target.characterCreationPolicy()); + return node; + } + + private static ObjectNode transitionNode( + CanonicalGameplayOriginalNewCandidate.TransitionSource transition) { + ObjectNode node = JSON.createObjectNode(); + node.put("transitionId", transition.transitionId().toString()); + node.put("bindingRef", base64(transition.bindingRef().bytes())); + node.put("bindingGeneration", transition.bindingGeneration().toString()); + node.put("issuerReservationId", transition.issuerReservationId().toString()); + node.put("reservationFence", transition.reservationFence().toString()); + node.put("candidateAccountIndexFence", transition.candidateAccountIndexFence().toString()); + return node; + } + + private static ObjectNode reservationNode( + CanonicalGameplayOriginalNewCandidate.ReservationSource reservation) { + ObjectNode node = JSON.createObjectNode(); + node.put("reservationId", reservation.reservationId().toString()); + node.put("ownerBindingRef", base64(reservation.ownerBindingRef().bytes())); + node.put("bindingGeneration", reservation.bindingGeneration().toString()); + node.put("transitionId", reservation.transitionId().toString()); + node.put("partitionId", reservation.partitionId().toString()); + node.put("lifecycle", CanonicalIssuerPartitionReservation.Lifecycle.RESERVED.name()); + node.put("reservationFence", reservation.reservationFence().toString()); + node.put("issuerCoverageOperationId", reservation.issuerCoverageOperationId().toString()); + node.put( + "issuerCoverageOperationFence", reservation.issuerCoverageOperationFence().toString()); + node.put("coverageFence", reservation.coverageFence().toString()); + node.put("inventorySnapshotRevision", reservation.inventorySnapshotRevision().toString()); + return node; + } + + private static JsonNode parseCanonicalLeaseNode( + AccountGameplayAdmissionLeaseEvidence evidence) throws IOException { + return JSON.readTree(evidence.canonicalJson()); + } + + private static AccountGameplayAdmissionLeaseEvidence parseLeaseEvidence(JsonNode node) + throws IOException { + ObjectNode object = requireObject(node, "leaseEvidence"); + byte[] canonical = Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(object)); + if (canonical.length > AccountGameplayAdmissionLeaseEvidence.MAX_EVIDENCE_BYTES) { + throw invalid("Complete Account lease evidence exceeds its local bound"); + } + return AccountGameplayAdmissionLeaseEvidence.parseCanonical( + new String(canonical, StandardCharsets.UTF_8)); + } + + private static CanonicalGameplayBindingIdentity parseBinding(JsonNode source) + throws IOException { + ObjectNode node = requireObject(source, "binding"); + requireFields(node, BINDING_FIELDS, "binding"); + return new CanonicalGameplayBindingIdentity( + uuid(node, "accountId"), + uuid(node, "tenantId"), + uuid(node, "playableStateNamespaceId"), + uuid(node, "characterId"), + text(node, "playableStateScope"), + uuid(node, "gameInstanceId"), + positiveLong(node, "runtimeGameInstanceId"), + text(node, "sessionId"), + uuid(node, "regionId"), + positive(node, "regionEpoch"), + text(node, "issuerId"), + positive(node, "issuerAuthGeneration"), + positive(node, "issuerIndexLayoutVersion"), + positive(node, "issuerIndexPartitionCount"), + positive(node, "issuerIndexPartitionCapacity")); + } + + private static CanonicalPlayableTarget parseTarget(JsonNode source) throws IOException { + ObjectNode node = requireObject(source, "target"); + CanonicalInitialAdmissionRequest.OriginKind originKind = + enumValue( + CanonicalInitialAdmissionRequest.OriginKind.class, + text(node, "initialAdmissionOriginKind"), + "initialAdmissionOriginKind"); + Set expectedFields = new HashSet<>(TARGET_FIELDS); + if (originKind == CanonicalInitialAdmissionRequest.OriginKind.EXPECT_CLOSED) { + expectedFields.add("expectedPriorPointerVersion"); + } + requireFields(node, expectedFields, "target"); + Long expectedPriorPointerVersion = + originKind == CanonicalInitialAdmissionRequest.OriginKind.NO_PRIOR_POINTER + ? null + : positiveLong(node, "expectedPriorPointerVersion"); + return new CanonicalPlayableTarget( + text(node, "targetNamespace"), + text(node, "tenantSlug"), + uuid(node, "canonicalTenantId"), + text(node, "worldSlug"), + text(node, "worldDisplayName"), + uuid(node, "realmId"), + text(node, "realmSlug"), + text(node, "realmDisplayName"), + positiveLong(node, "gameSessionTenantId"), + positiveLong(node, "gameInstanceId"), + uuid(node, "playableStateNamespaceId"), + text(node, "playableStateScope"), + uuid(node, "canonicalGameInstanceId"), + uuid(node, "canonicalVersionId"), + positiveLong(node, "runtimeVersionId"), + positiveLong(node, "catalogRevision"), + positiveLong(node, "pointerVersion"), + text(node, "admissionPointerSnapshotDigest"), + positiveLong(node, "activeWorldEpoch"), + text(node, "initialAdmissionRequestId"), + text(node, "initialAdmissionRequestDigest"), + originKind, + expectedPriorPointerVersion, + uuid(node, "holdId"), + uuid(node, "holdFence"), + text(node, "holdBindingDigest"), + positiveLong(node, "auditEventId"), + text(node, "ownerProofDigest"), + enumValue( + CanonicalInitialAdmissionOwnerProof.Outcome.class, + text(node, "ownerProofOutcome"), + "ownerProofOutcome"), + bool(node, "positiveDurableAbort"), + instant(node, "ownerProofTerminalAt"), + text(node, "characterCreationPolicy")); + } + + private static CanonicalGameplayOriginalNewCandidate.TransitionSource parseTransition( + JsonNode source) throws IOException { + ObjectNode node = requireObject(source, "transition"); + requireFields(node, TRANSITION_FIELDS, "transition"); + return new CanonicalGameplayOriginalNewCandidate.TransitionSource( + uuid(node, "transitionId"), + CanonicalGameplayBindingRef.fromExactBytes(base64(node, "bindingRef")), + positive(node, "bindingGeneration"), + uuid(node, "issuerReservationId"), + uuid(node, "reservationFence"), + uuid(node, "candidateAccountIndexFence")); + } + + private static CanonicalGameplayOriginalNewCandidate.ReservationSource parseReservation( + JsonNode source) throws IOException { + ObjectNode node = requireObject(source, "reservation"); + requireFields(node, RESERVATION_FIELDS, "reservation"); + if (!text(node, "lifecycle").equals(CanonicalIssuerPartitionReservation.Lifecycle.RESERVED.name())) { + throw invalid("Original NEW candidate reservation must remain RESERVED"); + } + return new CanonicalGameplayOriginalNewCandidate.ReservationSource( + uuid(node, "reservationId"), + CanonicalGameplayBindingRef.fromExactBytes(base64(node, "ownerBindingRef")), + positive(node, "bindingGeneration"), + uuid(node, "transitionId"), + nonNegative(node, "partitionId"), + uuid(node, "reservationFence"), + uuid(node, "issuerCoverageOperationId"), + positive(node, "issuerCoverageOperationFence"), + positive(node, "coverageFence"), + positive(node, "inventorySnapshotRevision")); + } + + private static ObjectNode requireObject(JsonNode node, String name) { + if (!(node instanceof ObjectNode object)) throw invalid(name + " must be an object"); + return object; + } + + private static void requireFields(ObjectNode node, Set expected, String name) { + Set fields = new HashSet<>(); + node.fieldNames().forEachRemaining(fields::add); + if (!fields.equals(expected)) throw invalid(name + " has missing or unknown fields"); + } + + private static String text(JsonNode node, String field) { + JsonNode value = node.get(field); + if (value == null || !value.isTextual() || value.textValue().isEmpty()) { + throw invalid(field + " must be non-empty text"); + } + return value.textValue(); + } + + private static boolean bool(JsonNode node, String field) { + JsonNode value = node.get(field); + if (value == null || !value.isBoolean()) throw invalid(field + " must be a JSON boolean"); + return value.booleanValue(); + } + + private static UUID uuid(JsonNode node, String field) { + String text = text(node, field); + try { + UUID value = UUID.fromString(text); + if (!value.toString().equals(text) || value.equals(new UUID(0L, 0L))) { + throw invalid(field + " must be a canonical non-nil UUID"); + } + return value; + } catch (IllegalArgumentException malformed) { + throw invalid(field + " must be a canonical non-nil UUID", malformed); + } + } + + private static BigInteger positive(JsonNode node, String field) { + return positiveDecimal(text(node, field), field); + } + + private static BigInteger nonNegative(JsonNode node, String field) { + String value = text(node, field); + if (!NON_NEGATIVE_DECIMAL.matcher(value).matches()) { + throw invalid(field + " must be a bounded canonical non-negative decimal string"); + } + return new BigInteger(value); + } + + private static BigInteger positiveDecimal(String value, String field) { + if (!POSITIVE_DECIMAL.matcher(value).matches()) { + throw invalid(field + " must be a bounded canonical positive decimal string"); + } + return new BigInteger(value); + } + + private static long positiveLong(JsonNode node, String field) { + String value = text(node, field); + if (!POSITIVE_DECIMAL.matcher(value).matches()) { + throw invalid(field + " must be a positive decimal string within the long range"); + } + try { + return Long.parseLong(value); + } catch (NumberFormatException malformed) { + throw invalid(field + " exceeds the supported long range", malformed); + } + } + + private static Instant instant(JsonNode node, String field) { + String value = text(node, field); + try { + Instant parsed = Instant.parse(value); + if (!parsed.toString().equals(value)) throw invalid(field + " is not canonical UTC time"); + return parsed; + } catch (RuntimeException malformed) { + throw invalid(field + " is not canonical UTC time", malformed); + } + } + + private static > E enumValue( + Class enumType, String value, String field) { + try { + return Enum.valueOf(enumType, value); + } catch (IllegalArgumentException malformed) { + throw invalid(field + " is unsupported", malformed); + } + } + + private static byte[] base64(JsonNode node, String field) { + String value = text(node, field); + try { + byte[] decoded = Base64.getDecoder().decode(value); + if (!base64(decoded).equals(value)) throw invalid(field + " is not canonical padded Base64"); + return decoded; + } catch (IllegalArgumentException malformed) { + throw invalid(field + " is not canonical padded Base64", malformed); + } + } + + private static String base64(byte[] bytes) { + return Base64.getEncoder().encodeToString(bytes); + } + + private static void requireCounterLimit(BigInteger value, String name, boolean zeroAllowed) { + Objects.requireNonNull(value, name); + int digits = value.toString().length(); + if (digits > MAX_COUNTER_DIGITS || value.signum() < 0 || (!zeroAllowed && value.signum() == 0)) { + throw invalid(name + " exceeds its canonical integer bounds"); + } + } + + private static String decodeUtf8(byte[] encoded) { + try { + return StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(encoded)) + .toString(); + } catch (CharacterCodingException malformed) { + throw invalid("Original NEW candidate is not valid UTF-8", malformed); + } + } + + private static IllegalArgumentException invalid(String message) { + return new IllegalArgumentException(message); + } + + private static IllegalArgumentException invalid(String message, Throwable cause) { + return new IllegalArgumentException(message, cause); + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayProtectedIncarnationReceiver.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayProtectedIncarnationReceiver.java index 7f7b2c1d95..9ccc4f0fc1 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayProtectedIncarnationReceiver.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayProtectedIncarnationReceiver.java @@ -38,6 +38,8 @@ */ final class CanonicalGameplayProtectedIncarnationReceiver { private static final String OBSERVATION_SCHEMA = "firemud.gs.protected-incarnation-read/v1"; + private static final String INITIAL_OBSERVATION_SCHEMA = + "firemud.gs.protected-initial-account-barrier-read/v1"; private static final String INCARNATION_BINDING_SCHEMA = "firemud.gs.protected-incarnation-binding/v1"; private static final Pattern KEY_ID = Pattern.compile("[A-Za-z0-9_-]{1,64}"); @@ -67,6 +69,20 @@ final class CanonicalGameplayProtectedIncarnationReceiver { "inventorySnapshotRevision", "cohortDigest", "barrierTargetDigest"); + private static final Set INITIAL_OWNER_FIELDS = + Set.of( + "ownerKind", + "initializerId", + "originalRequestId", + "originalCallerContextId", + "originalAttemptFence", + "accountId", + "sourceControlState", + "sourceControlEpoch", + "inventorySnapshotRevision", + "accountLoginEvidenceDigest", + "sourceControlDigest", + "targetDigest"); private static final Set TARGET_FIELDS = Set.of( "targetOrdinal", @@ -95,6 +111,7 @@ final class CanonicalGameplayProtectedIncarnationReceiver { .build(); private final CanonicalGameplayAccountAdmissionBarrierRepository intentRepository; + private final CanonicalGameplayAccountInitialBarrierInitializerRepository initialRepository; private final CanonicalGameplayTenantGameplayTagRepository tenantTagRepository; private final ProtectedObservationChannel observationChannel; private final TrustedConfiguration trustedConfiguration; @@ -109,6 +126,7 @@ final class CanonicalGameplayProtectedIncarnationReceiver { Clock clock) { this( intentRepository, + null, tenantTagRepository, observationChannel, trustedConfiguration, @@ -123,7 +141,42 @@ final class CanonicalGameplayProtectedIncarnationReceiver { TrustedConfiguration trustedConfiguration, Clock clock, SecureRandom secureRandom) { + this( + intentRepository, + null, + tenantTagRepository, + observationChannel, + trustedConfiguration, + clock, + secureRandom); + } + + CanonicalGameplayProtectedIncarnationReceiver( + CanonicalGameplayAccountInitialBarrierInitializerRepository initialRepository, + CanonicalGameplayTenantGameplayTagRepository tenantTagRepository, + ProtectedObservationChannel observationChannel, + TrustedConfiguration trustedConfiguration, + Clock clock) { + this( + null, + initialRepository, + tenantTagRepository, + observationChannel, + trustedConfiguration, + clock, + new SecureRandom()); + } + + private CanonicalGameplayProtectedIncarnationReceiver( + CanonicalGameplayAccountAdmissionBarrierRepository intentRepository, + CanonicalGameplayAccountInitialBarrierInitializerRepository initialRepository, + CanonicalGameplayTenantGameplayTagRepository tenantTagRepository, + ProtectedObservationChannel observationChannel, + TrustedConfiguration trustedConfiguration, + Clock clock, + SecureRandom secureRandom) { this.intentRepository = intentRepository; + this.initialRepository = initialRepository; this.tenantTagRepository = tenantTagRepository; this.observationChannel = observationChannel; this.trustedConfiguration = trustedConfiguration; @@ -143,9 +196,23 @@ VerifiedIncarnation observeForFenceTarget(UUID operationId, long targetOrdinal) if (targetOrdinal < 0) { throw new IllegalArgumentException("targetOrdinal must not be negative"); } - requireAvailable(); - + requireAvailable(OwnerKind.ACCOUNT_FENCE); CurrentContext before = loadCurrentContext(operationId, targetOrdinal); + return observeCurrentContext( + before, () -> loadCurrentContext(operationId, targetOrdinal)); + } + + /** Reads a separate INITIAL original-attempt context under the same trusted signature verifier. */ + VerifiedIncarnation observeForInitialAccountBarrier(UUID originalRequestId) { + requireNoAmbientTransaction(); + requireNonNil(originalRequestId, "originalRequestId"); + requireAvailable(OwnerKind.INITIAL_ACCOUNT_BARRIER); + CurrentContext before = loadInitialCurrentContext(originalRequestId); + return observeCurrentContext(before, () -> loadInitialCurrentContext(originalRequestId)); + } + + private VerifiedIncarnation observeCurrentContext( + CurrentContext before, java.util.function.Supplier reload) { long issuedAt = clock.millis(); if (issuedAt <= 0L) { throw new ObservationUnavailableException("Protected observation clock is unavailable"); @@ -184,9 +251,8 @@ VerifiedIncarnation observeForFenceTarget(UUID operationId, long targetOrdinal) if (signed == null) { throw new ObservationUnavailableException("Protected observation source returned no bytes"); } - VerifiedPayload payload = verifyObservation(signed, request, before); - CurrentContext after = loadCurrentContext(operationId, targetOrdinal); + CurrentContext after = reload.get(); if (!before.equals(after)) { throw new ObservationRejectedException("Protected observation owner context changed"); } @@ -198,7 +264,6 @@ VerifiedIncarnation observeForFenceTarget(UUID operationId, long targetOrdinal) || payload.expiresAtEpochMillis() != expiresAt) { throw new ObservationRejectedException("Protected observation is expired or out of window"); } - String incarnationDigest = incarnationDigest(trustedConfiguration); return new VerifiedIncarnation( before, trustedConfiguration.acceptedAttestationDigest(), @@ -208,11 +273,12 @@ VerifiedIncarnation observeForFenceTarget(UUID operationId, long targetOrdinal) payload.observedAtEpochMillis(), expiresAt, payload.payloadDigest(), - incarnationDigest); + incarnationDigest(trustedConfiguration)); } - private void requireAvailable() { - if (intentRepository == null + private void requireAvailable(OwnerKind ownerKind) { + if ((ownerKind == OwnerKind.ACCOUNT_FENCE && intentRepository == null) + || (ownerKind == OwnerKind.INITIAL_ACCOUNT_BARRIER && initialRepository == null) || tenantTagRepository == null || observationChannel == null || trustedConfiguration == null @@ -260,6 +326,7 @@ private CurrentContext loadCurrentContext(UUID operationId, long targetOrdinal) } CanonicalGameplaySessionRedisKeys.accountAdmissionBarrier(assignment); return new CurrentContext( + OwnerKind.ACCOUNT_FENCE, intent.operationId(), intent.requestId(), intent.accountId(), @@ -273,7 +340,54 @@ private CurrentContext loadCurrentContext(UUID operationId, long targetOrdinal) target.playableStateNamespaceId(), assignment.tenantGameplayTag(), assignment.workloadNamespace(), - assignment.allocationVersion()); + assignment.allocationVersion(), + null, + 0L, + null, + null, + null, + null); + } + + private CurrentContext loadInitialCurrentContext(UUID originalRequestId) { + requireNoAmbientTransaction(); + CanonicalGameplayAccountInitialBarrierInitializerRepository.InitialObservationContext context = + initialRepository.readCurrentObservationContext(originalRequestId); + CanonicalGameplayTenantGameplayTagRepository.Assignment assignment = + tenantTagRepository.assignmentForInitialBarrierTarget(originalRequestId); + CanonicalGameplayAccountInitialBarrierKey.forTarget( + assignment, context.initializerId(), context.originalRequestId()); + if (!assignment.isInitialBarrierTarget() + || !context.initializerId().equals(assignment.initialBarrierInitializerId()) + || !context.originalRequestId().equals(assignment.initialBarrierOriginalRequestId()) + || !context.accountId().equals(assignment.accountId()) + || !context.tenantId().equals(assignment.tenantId()) + || !context.playableStateNamespaceId().equals(assignment.playableStateNamespaceId())) { + throw new ObservationRejectedException( + "Protected INITIAL observation target differs from current SQL source"); + } + return new CurrentContext( + OwnerKind.INITIAL_ACCOUNT_BARRIER, + context.initializerId(), + context.originalRequestId(), + context.accountId(), + null, + null, + context.inventorySnapshotRevision().toString(), + context.sourceControlDigest(), + context.targetDigest(), + 0L, + context.tenantId(), + context.playableStateNamespaceId(), + assignment.tenantGameplayTag(), + assignment.workloadNamespace(), + assignment.allocationVersion(), + context.originalCallerContextId(), + context.originalAttemptFence(), + context.sourceControlState(), + context.sourceControlEpoch().toString(), + context.accountLoginEvidenceDigest(), + context.sourceControlDigest()); } private VerifiedPayload verifyObservation( @@ -306,7 +420,11 @@ private VerifiedPayload verifyObservation( verifyDetachedSignature(publicKey, canonical, signatureBytes); requireExactFields(root, ROOT_FIELDS); - requireText(root, "schema", OBSERVATION_SCHEMA); + String expectedSchema = + expected.ownerKind() == OwnerKind.ACCOUNT_FENCE + ? OBSERVATION_SCHEMA + : INITIAL_OBSERVATION_SCHEMA; + requireText(root, "schema", expectedSchema); requireText(root, "attestorBinding", trustedConfiguration.attestorBinding()); requireText(root, "attestorKeyId", keyId); requireText(root, "acceptedAttestationDigest", request.acceptedAttestationDigest()); @@ -322,16 +440,38 @@ private VerifiedPayload verifyObservation( } JsonNode owner = requiredObject(root, "owner"); - requireExactFields(owner, OWNER_FIELDS); - requireText(owner, "operationId", expected.operationId().toString()); - requireText(owner, "requestId", expected.requestId().toString()); - requireText(owner, "accountId", expected.accountId().toString()); - requireText(owner, "operationFence", expected.operationFence()); - requireText( - owner, "plannedAccountAdmissionFence", expected.plannedAccountAdmissionFence().toString()); - requireText(owner, "inventorySnapshotRevision", expected.inventorySnapshotRevision()); - requireText(owner, "cohortDigest", expected.cohortDigest()); - requireText(owner, "barrierTargetDigest", expected.barrierTargetDigest()); + if (expected.ownerKind() == OwnerKind.ACCOUNT_FENCE) { + requireExactFields(owner, OWNER_FIELDS); + requireText(owner, "operationId", expected.operationId().toString()); + requireText(owner, "requestId", expected.requestId().toString()); + requireText(owner, "accountId", expected.accountId().toString()); + requireText(owner, "operationFence", expected.operationFence()); + requireText( + owner, + "plannedAccountAdmissionFence", + expected.plannedAccountAdmissionFence().toString()); + requireText(owner, "inventorySnapshotRevision", expected.inventorySnapshotRevision()); + requireText(owner, "cohortDigest", expected.cohortDigest()); + requireText(owner, "barrierTargetDigest", expected.barrierTargetDigest()); + } else { + requireExactFields(owner, INITIAL_OWNER_FIELDS); + requireText(owner, "ownerKind", OwnerKind.INITIAL_ACCOUNT_BARRIER.name()); + requireText(owner, "initializerId", expected.operationId().toString()); + requireText(owner, "originalRequestId", expected.requestId().toString()); + requireText( + owner, "originalCallerContextId", expected.originalCallerContextId().toString()); + if (requiredPositiveLong(owner, "originalAttemptFence") + != expected.originalAttemptFence()) { + throw new ObservationRejectedException("Protected INITIAL attempt fence differs"); + } + requireText(owner, "accountId", expected.accountId().toString()); + requireText(owner, "sourceControlState", expected.sourceControlState()); + requireText(owner, "sourceControlEpoch", expected.sourceControlEpoch()); + requireText(owner, "inventorySnapshotRevision", expected.inventorySnapshotRevision()); + requireText(owner, "accountLoginEvidenceDigest", expected.accountLoginEvidenceDigest()); + requireText(owner, "sourceControlDigest", expected.sourceControlDigest()); + requireText(owner, "targetDigest", expected.barrierTargetDigest()); + } JsonNode target = requiredObject(root, "target"); requireExactFields(target, TARGET_FIELDS); @@ -403,7 +543,11 @@ private static boolean isCanonicalNodeOrder(List nodes) { return sorted.equals(nodes); } - private static void requireNoAmbientTransaction() { + private void requireNoAmbientTransaction() { + if (initialRepository != null) { + initialRepository.requireNoAmbientTransaction(); + return; + } if (TransactionSynchronizationManager.isActualTransactionActive() || TransactionSynchronizationManager.isSynchronizationActive()) { throw new IllegalStateException( @@ -798,8 +942,14 @@ private static void requireDigestValue(String value, String field) { } } - /** Current owner and exact target tuple obtained from the actual SQL owners. */ + enum OwnerKind { + ACCOUNT_FENCE, + INITIAL_ACCOUNT_BARRIER + } + + /** Discriminated current owner and exact target tuple obtained from the actual SQL owners. */ record CurrentContext( + OwnerKind ownerKind, UUID operationId, UUID requestId, UUID accountId, @@ -813,7 +963,45 @@ record CurrentContext( UUID playableStateNamespaceId, String tenantGameplayTag, String workloadNamespace, - int allocationVersion) {} + int allocationVersion, + UUID originalCallerContextId, + long originalAttemptFence, + String sourceControlState, + String sourceControlEpoch, + String accountLoginEvidenceDigest, + String sourceControlDigest) { + CurrentContext { + Objects.requireNonNull(ownerKind, "ownerKind"); + Objects.requireNonNull(operationId, "operationId"); + Objects.requireNonNull(requestId, "requestId"); + Objects.requireNonNull(accountId, "accountId"); + Objects.requireNonNull(tenantId, "tenantId"); + Objects.requireNonNull(playableStateNamespaceId, "playableStateNamespaceId"); + Objects.requireNonNull(tenantGameplayTag, "tenantGameplayTag"); + Objects.requireNonNull(workloadNamespace, "workloadNamespace"); + if (ownerKind == OwnerKind.ACCOUNT_FENCE) { + Objects.requireNonNull(plannedAccountAdmissionFence, "plannedAccountAdmissionFence"); + Objects.requireNonNull(operationFence, "operationFence"); + Objects.requireNonNull(cohortDigest, "cohortDigest"); + Objects.requireNonNull(barrierTargetDigest, "barrierTargetDigest"); + } else { + Objects.requireNonNull(originalCallerContextId, "originalCallerContextId"); + Objects.requireNonNull(sourceControlState, "sourceControlState"); + Objects.requireNonNull(sourceControlEpoch, "sourceControlEpoch"); + Objects.requireNonNull(accountLoginEvidenceDigest, "accountLoginEvidenceDigest"); + Objects.requireNonNull(sourceControlDigest, "sourceControlDigest"); + if (originalAttemptFence <= 0L + || operationFence != null + || plannedAccountAdmissionFence != null + || !"NO_ACTIVE_ACCOUNT_WIDE_FLOW".equals(sourceControlState) + || sourceControlEpoch == null + || !sourceControlEpoch.matches("0|[1-9][0-9]{0,255}")) { + throw new IllegalArgumentException( + "INITIAL owner context is not the positively read NO_ACTIVE arm"); + } + } + } + } private record VerifiedPayload( String observationNonce, @@ -858,6 +1046,42 @@ UUID operationId() { return context.operationId(); } + OwnerKind ownerKind() { + return context.ownerKind(); + } + + UUID requestId() { + return context.requestId(); + } + + UUID originalCallerContextId() { + return context.originalCallerContextId(); + } + + long originalAttemptFence() { + return context.originalAttemptFence(); + } + + String sourceControlState() { + return context.sourceControlState(); + } + + String sourceControlEpoch() { + return context.sourceControlEpoch(); + } + + String inventorySnapshotRevision() { + return context.inventorySnapshotRevision(); + } + + String accountLoginEvidenceDigest() { + return context.accountLoginEvidenceDigest(); + } + + String sourceControlDigest() { + return context.sourceControlDigest(); + } + long targetOrdinal() { return context.targetOrdinal(); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplaySessionRedisKeys.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplaySessionRedisKeys.java index bdcdeb62a1..abc6adbe8e 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplaySessionRedisKeys.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplaySessionRedisKeys.java @@ -53,6 +53,28 @@ public static String accountAdmissionBarrier( throw new IllegalArgumentException( "Account admission barrier keys require a persisted acquisition-intent target"); } + return accountAdmissionBarrierKey(assignment); + } + + /** Builds the same canonical key only for one persisted original-attempt INITIAL target. */ + static String initialAccountAdmissionBarrier( + CanonicalGameplayTenantGameplayTagRepository.Assignment assignment, + java.util.UUID expectedInitializerId, + java.util.UUID expectedOriginalRequestId) { + Objects.requireNonNull(assignment, "assignment"); + Objects.requireNonNull(expectedInitializerId, "expected initializer id"); + Objects.requireNonNull(expectedOriginalRequestId, "expected original request id"); + if (!assignment.isInitialBarrierTarget() + || !expectedInitializerId.equals(assignment.initialBarrierInitializerId()) + || !expectedOriginalRequestId.equals(assignment.initialBarrierOriginalRequestId())) { + throw new IllegalArgumentException( + "INITIAL account admission barrier keys require their persisted original target"); + } + return accountAdmissionBarrierKey(assignment); + } + + private static String accountAdmissionBarrierKey( + CanonicalGameplayTenantGameplayTagRepository.Assignment assignment) { return "session:game:account-admission:{" + tag(assignment) + "}:" diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayTenantGameplayTagRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayTenantGameplayTagRepository.java index 9a34cf46f7..4ee4454079 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayTenantGameplayTagRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayTenantGameplayTagRepository.java @@ -128,6 +128,72 @@ public Assignment assignmentForBarrierTarget(UUID operationId, long targetOrdina }); } + /** Resolves topology only for the persisted exact original-attempt INITIAL target. */ + Assignment assignmentForInitialBarrierTarget(UUID originalRequestId) { + requireNonNil(originalRequestId, "originalRequestId"); + return dsl.transactionResult( + configuration -> { + DSLContext transaction = DSL.using(configuration); + Record row = + transaction.fetchOne( + "SELECT i.initializer_id, i.account_id, i.source_control_epoch," + + " t.target_ordinal, t.tenant_id," + + " t.playable_state_namespace_id, t.target_state, control.state AS control_state," + + " control.last_operation_fence, control.current_operation_id," + + " control.current_fence_intent_id, control.current_operation_fence," + + " control.account_admission_fence, control.historical_account_admission_fence," + + " control.coverage_fence, control.inventory_snapshot_revision," + + " control.coverage_generation" + + " FROM game_session_canonical_initial_account_barrier_initializer i" + + " JOIN game_session_canonical_initial_account_barrier_target t" + + " ON t.initializer_id = i.initializer_id" + + " AND t.original_request_id = i.original_request_id" + + " JOIN game_session_canonical_account_coverage_control control" + + " ON control.account_id = i.account_id" + + " WHERE i.original_request_id = ? AND t.target_ordinal = 0" + + " FOR UPDATE OF i, t, control", + originalRequestId); + if (row == null + || !"NO_ACTIVE_ACCOUNT_WIDE_FLOW".equals(row.get("control_state", String.class)) + || row.get("last_operation_fence", java.math.BigDecimal.class) == null + || row.get("last_operation_fence", java.math.BigDecimal.class) + .toBigIntegerExact() + .signum() + < 0 + || row.get("source_control_epoch", java.math.BigDecimal.class) == null + || !row.get("source_control_epoch", java.math.BigDecimal.class) + .toBigIntegerExact() + .equals( + row.get("last_operation_fence", java.math.BigDecimal.class) + .toBigIntegerExact()) + || row.get("current_operation_id", UUID.class) != null + || row.get("current_fence_intent_id", UUID.class) != null + || row.get("current_operation_fence") != null + || row.get("account_admission_fence", UUID.class) != null + || row.get("historical_account_admission_fence", UUID.class) != null + || row.get("coverage_fence", UUID.class) != null + || row.get("inventory_snapshot_revision") != null + || row.get("coverage_generation") != null) { + throw conflict( + "The exact INITIAL target or its positive NO_ACTIVE control is unavailable"); + } + UUID initializerId = requiredUuid(row, "initializer_id"); + UUID accountId = requiredUuid(row, "account_id"); + UUID tenantId = requiredUuid(row, "tenant_id"); + UUID namespaceId = requiredUuid(row, "playable_state_namespace_id"); + if (requiredLong(row, "target_ordinal") != 0L + || !Set.of("NEVER_DISPATCHED", "DISPATCH_POSSIBLE", "OPEN_INSTALLED") + .contains(requiredString(row, "target_state"))) { + throw conflict("The INITIAL target state is not a retained original-attempt state"); + } + requireTenantClaim(transaction, tenantId); + InitialTarget source = + new InitialTarget(initializerId, originalRequestId, accountId, tenantId, namespaceId); + return resolveMapping( + transaction, source, allocationVersion, tagFor(tenantId, allocationVersion)); + }); + } + /** * Narrow package-private collision path for native database proof. The tenant still comes from * the exact persisted transition; only the candidate output is controlled to exercise the global @@ -387,7 +453,7 @@ private static CanonicalGameplayBindingInventoryConflictException conflict(Strin return new CanonicalGameplayBindingInventoryConflictException(message); } - private sealed interface Target permits BindingTarget, BarrierTarget { + private sealed interface Target permits BindingTarget, BarrierTarget, InitialTarget { UUID tenantId(); UUID accountId(); @@ -410,6 +476,14 @@ private record BarrierTarget( UUID sourceId, long ordinal, UUID accountId, UUID tenantId, UUID namespaceId) implements Target {} + private record InitialTarget( + UUID initializerId, + UUID originalRequestId, + UUID accountId, + UUID tenantId, + UUID namespaceId) + implements Target {} + /** Owner-issued immutable mapping plus the exact SQL source needed by the key builder. */ public static final class Assignment { private final Target source; @@ -453,6 +527,18 @@ public boolean isBindingTransition() { return source instanceof BindingTarget; } + boolean isInitialBarrierTarget() { + return source instanceof InitialTarget; + } + + UUID initialBarrierInitializerId() { + return source instanceof InitialTarget initial ? initial.initializerId() : null; + } + + UUID initialBarrierOriginalRequestId() { + return source instanceof InitialTarget initial ? initial.originalRequestId() : null; + } + public UUID transitionId() { return source instanceof BindingTarget binding ? binding.sourceId() : null; } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayAccountInitialBarrierRedisScriptContribution.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayAccountInitialBarrierRedisScriptContribution.java new file mode 100644 index 0000000000..bad4527a8b --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayAccountInitialBarrierRedisScriptContribution.java @@ -0,0 +1,52 @@ +package net.firedevops.firemud.gamesession.service; + +import java.io.IOException; +import java.io.InputStream; +import java.util.Collection; +import java.util.List; +import net.firedevops.firemud.common.redis.contracts.RedisScriptContribution; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.json.JsonMapper; + +/** Passive descriptor for the one-key create-only INITIAL OPEN barrier script. */ +public final class CanonicalGameplayAccountInitialBarrierRedisScriptContribution + implements RedisScriptContribution { + public static final String SCRIPT_ID = "game-session.account-admission-barrier-initial-open.v1"; + public static final String RESOURCE_PATH = + "redis/lua/game-session-account-admission-barrier-initial-open.lua"; + private static final String DESCRIPTOR_PATH = + "/redis/scripts/game-session-account-admission-barrier-initial-open.json"; + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + @Override + public String ownerId() { + return "game-session-service"; + } + + @Override + public Collection descriptors() { + try (InputStream input = getClass().getResourceAsStream(DESCRIPTOR_PATH)) { + if (input == null) throw unavailable(); + byte[] bytes = input.readNBytes(16 * 1024 + 1); + if (bytes.length == 0 || bytes.length > 16 * 1024) throw unavailable(); + RedisScriptDescriptor descriptor = JSON.readValue(bytes, RedisScriptDescriptor.class); + if (!ownerId().equals(descriptor.owner()) || !SCRIPT_ID.equals(descriptor.scriptId())) { + throw unavailable(); + } + return List.of(descriptor); + } catch (IOException | RuntimeException failure) { + throw unavailable(); + } + } + + private static IllegalStateException unavailable() { + return new IllegalStateException("INITIAL account barrier descriptor is unavailable"); + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayIssuerAdmissionBarrierRedisScriptContribution.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayIssuerAdmissionBarrierRedisScriptContribution.java new file mode 100644 index 0000000000..9ecc7591a8 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayIssuerAdmissionBarrierRedisScriptContribution.java @@ -0,0 +1,62 @@ +package net.firedevops.firemud.gamesession.service; + +import java.io.IOException; +import java.io.InputStream; +import java.util.Collection; +import java.util.List; +import net.firedevops.firemud.common.redis.contracts.RedisScriptContribution; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.json.JsonMapper; + +/** Passive manual descriptor contribution for one-key issuer tenant barrier scripts. */ +public final class CanonicalGameplayIssuerAdmissionBarrierRedisScriptContribution + implements RedisScriptContribution { + public static final String OPEN_SCRIPT_ID = "game-session.issuer-admission-barrier-open.v1"; + public static final String CLOSE_SCRIPT_ID = "game-session.issuer-admission-barrier-close.v1"; + public static final String OPEN_RESOURCE_PATH = + "redis/lua/game-session-issuer-admission-barrier-open.lua"; + public static final String CLOSE_RESOURCE_PATH = + "redis/lua/game-session-issuer-admission-barrier-close.lua"; + private static final String OPEN_DESCRIPTOR_PATH = + "/redis/scripts/game-session-issuer-admission-barrier-open.json"; + private static final String CLOSE_DESCRIPTOR_PATH = + "/redis/scripts/game-session-issuer-admission-barrier-close.json"; + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + @Override + public String ownerId() { + return "game-session-service"; + } + + @Override + public Collection descriptors() { + return List.of(readDescriptor(OPEN_DESCRIPTOR_PATH, OPEN_SCRIPT_ID), + readDescriptor(CLOSE_DESCRIPTOR_PATH, CLOSE_SCRIPT_ID)); + } + + private RedisScriptDescriptor readDescriptor(String path, String scriptId) { + try (InputStream input = getClass().getResourceAsStream(path)) { + if (input == null) throw unavailable(); + byte[] bytes = input.readNBytes(16 * 1024 + 1); + if (bytes.length == 0 || bytes.length > 16 * 1024) throw unavailable(); + var descriptor = JSON.readValue(bytes, RedisScriptDescriptor.class); + if (!ownerId().equals(descriptor.owner()) || !scriptId.equals(descriptor.scriptId())) { + throw unavailable(); + } + return descriptor; + } catch (IOException | RuntimeException failure) { + throw unavailable(); + } + } + + private static IllegalStateException unavailable() { + return new IllegalStateException("Issuer admission barrier descriptors are unavailable"); + } +} diff --git a/services/game-session-service/src/main/resources/db/migration/V1046__canonical_issuer_live_admission_control.sql b/services/game-session-service/src/main/resources/db/migration/V1046__canonical_issuer_live_admission_control.sql new file mode 100644 index 0000000000..e98768762d --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V1046__canonical_issuer_live_admission_control.sql @@ -0,0 +1,288 @@ +-- The live tenant-barrier epoch belongs to a separate issuer control domain. The immutable +-- V1030 initial-layout control and installed anchor remain provenance only; neither is reused as +-- a live admission state or epoch. +CREATE TABLE game_session_canonical_issuer_admission_epoch_counter ( + issuer_id character varying(64) NOT NULL, + last_live_barrier_epoch numeric NOT NULL, + updated_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT pk_gs_issuer_admission_epoch_counter PRIMARY KEY (issuer_id), + CONSTRAINT chk_gs_issuer_admission_epoch_counter CHECK ( + issuer_id COLLATE "C" = 'firemud-account-service'::character varying COLLATE "C" + AND last_live_barrier_epoch >= 0) +); + +INSERT INTO game_session_canonical_issuer_admission_epoch_counter + (issuer_id, last_live_barrier_epoch) +VALUES ('firemud-account-service', 0); + +CREATE TABLE game_session_canonical_issuer_admission_control ( + issuer_id character varying(64) NOT NULL, + state character varying(32) NOT NULL, + live_barrier_epoch numeric NOT NULL, + current_operation_id uuid NOT NULL, + current_operation_kind character varying(32) NOT NULL, + bootstrap_operation_id uuid NOT NULL, + bootstrap_request_id uuid NOT NULL, + bootstrap_control_epoch numeric NOT NULL, + anchor_exact_bytes bytea NOT NULL, + anchor_exact_digest character varying(71) NOT NULL, + account_issuer_auth_generation numeric NOT NULL, + account_checkpoint_bytes bytea NOT NULL, + account_checkpoint_digest character varying(71) NOT NULL, + account_source_event_bytes bytea, + account_source_event_digest character varying(71), + stable_incarnation_bytes bytea NOT NULL, + stable_incarnation_digest character varying(71) NOT NULL, + inventory_snapshot_revision numeric NOT NULL, + cohort_row_count bigint NOT NULL, + cohort_digest character varying(71) NOT NULL, + control_exact_bytes bytea NOT NULL, + control_exact_digest character varying(71) NOT NULL, + created_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, + updated_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT pk_gs_issuer_admission_control PRIMARY KEY (issuer_id), + CONSTRAINT fk_gs_issuer_admission_control_epoch + FOREIGN KEY (issuer_id) + REFERENCES game_session_canonical_issuer_admission_epoch_counter (issuer_id), + CONSTRAINT chk_gs_issuer_admission_control CHECK ( + issuer_id COLLATE "C" = 'firemud-account-service'::character varying COLLATE "C" + AND state IN ('OPEN', 'CUTOFF_PENDING', 'INSTALLED') + AND live_barrier_epoch > 0 + AND current_operation_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND current_operation_kind IN ('INITIAL_ANCHOR_INSTALL', 'CUTOFF') + AND bootstrap_operation_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND bootstrap_request_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND bootstrap_control_epoch > 0 + AND octet_length(anchor_exact_bytes) BETWEEN 1 AND 524288 + AND anchor_exact_digest ~ '^sha256:[0-9a-f]{64}$' + AND account_issuer_auth_generation > 0 + AND octet_length(account_checkpoint_bytes) BETWEEN 1 AND 524288 + AND account_checkpoint_digest ~ '^sha256:[0-9a-f]{64}$' + AND ((account_source_event_bytes IS NULL AND account_source_event_digest IS NULL) + OR (account_source_event_bytes IS NOT NULL + AND octet_length(account_source_event_bytes) BETWEEN 1 AND 524288 + AND account_source_event_digest ~ '^sha256:[0-9a-f]{64}$')) + AND octet_length(stable_incarnation_bytes) BETWEEN 1 AND 524288 + AND stable_incarnation_digest ~ '^sha256:[0-9a-f]{64}$' + AND inventory_snapshot_revision > 0 + AND cohort_row_count >= 0 + AND cohort_digest ~ '^sha256:[0-9a-f]{64}$' + AND octet_length(control_exact_bytes) BETWEEN 1 AND 524288 + AND control_exact_digest ~ '^sha256:[0-9a-f]{64}$' + AND ((state = 'OPEN' AND current_operation_kind = 'INITIAL_ANCHOR_INSTALL') + OR (state IN ('CUTOFF_PENDING', 'INSTALLED') + AND current_operation_kind = 'CUTOFF'))) +); + +CREATE TABLE game_session_canonical_issuer_admission_operation ( + operation_id uuid NOT NULL, + request_id uuid NOT NULL, + issuer_id character varying(64) NOT NULL, + operation_kind character varying(32) NOT NULL, + operation_state character varying(32) NOT NULL, + live_barrier_epoch numeric NOT NULL, + prior_live_barrier_epoch numeric, + bootstrap_operation_id uuid NOT NULL, + bootstrap_request_id uuid NOT NULL, + bootstrap_control_epoch numeric NOT NULL, + anchor_exact_bytes bytea NOT NULL, + anchor_exact_digest character varying(71) NOT NULL, + account_issuer_auth_generation numeric NOT NULL, + account_checkpoint_bytes bytea NOT NULL, + account_checkpoint_digest character varying(71) NOT NULL, + account_source_event_bytes bytea, + account_source_event_digest character varying(71), + stable_incarnation_bytes bytea NOT NULL, + stable_incarnation_digest character varying(71) NOT NULL, + inventory_snapshot_revision numeric NOT NULL, + cohort_row_count bigint NOT NULL, + cohort_digest character varying(71) NOT NULL, + created_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, + installed_at timestamp with time zone, + CONSTRAINT pk_gs_issuer_admission_operation PRIMARY KEY (operation_id), + CONSTRAINT uq_gs_issuer_admission_operation_pair UNIQUE (operation_id, issuer_id), + CONSTRAINT uq_gs_issuer_admission_operation_request UNIQUE (issuer_id, request_id), + CONSTRAINT uq_gs_issuer_admission_operation_epoch UNIQUE (issuer_id, live_barrier_epoch), + CONSTRAINT chk_gs_issuer_admission_operation CHECK ( + operation_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND request_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND operation_id <> request_id + AND issuer_id COLLATE "C" = 'firemud-account-service'::character varying COLLATE "C" + AND operation_kind IN ('INITIAL_ANCHOR_INSTALL', 'CUTOFF') + AND operation_state IN ('OPEN', 'CUTOFF_PENDING', 'INSTALLED') + AND live_barrier_epoch > 0 + AND ((operation_kind = 'INITIAL_ANCHOR_INSTALL' + AND operation_state = 'OPEN' + AND prior_live_barrier_epoch IS NULL + AND installed_at IS NOT NULL) + OR (operation_kind = 'CUTOFF' + AND operation_state IN ('CUTOFF_PENDING', 'INSTALLED') + AND prior_live_barrier_epoch > 0 + AND live_barrier_epoch > prior_live_barrier_epoch + AND ((operation_state = 'CUTOFF_PENDING' AND installed_at IS NULL) + OR (operation_state = 'INSTALLED' AND installed_at IS NOT NULL)))) + AND bootstrap_operation_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND bootstrap_request_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND bootstrap_control_epoch > 0 + AND octet_length(anchor_exact_bytes) BETWEEN 1 AND 524288 + AND anchor_exact_digest ~ '^sha256:[0-9a-f]{64}$' + AND account_issuer_auth_generation > 0 + AND octet_length(account_checkpoint_bytes) BETWEEN 1 AND 524288 + AND account_checkpoint_digest ~ '^sha256:[0-9a-f]{64}$' + AND ((account_source_event_bytes IS NULL AND account_source_event_digest IS NULL) + OR (account_source_event_bytes IS NOT NULL + AND octet_length(account_source_event_bytes) BETWEEN 1 AND 524288 + AND account_source_event_digest ~ '^sha256:[0-9a-f]{64}$')) + AND octet_length(stable_incarnation_bytes) BETWEEN 1 AND 524288 + AND stable_incarnation_digest ~ '^sha256:[0-9a-f]{64}$' + AND inventory_snapshot_revision > 0 + AND cohort_row_count >= 0 + AND cohort_digest ~ '^sha256:[0-9a-f]{64}$') +); + +ALTER TABLE game_session_canonical_issuer_admission_control + ADD CONSTRAINT fk_gs_issuer_admission_control_operation + FOREIGN KEY (current_operation_id, issuer_id) + REFERENCES game_session_canonical_issuer_admission_operation (operation_id, issuer_id); + +CREATE TABLE game_session_canonical_issuer_admission_cohort_row ( + operation_id uuid NOT NULL, + issuer_id character varying(64) NOT NULL, + row_ordinal bigint NOT NULL, + source_kind character varying(48) NOT NULL, + source_key text NOT NULL, + source_inventory_revision numeric NOT NULL, + source_row_json text NOT NULL, + source_row_digest character varying(71) NOT NULL, + CONSTRAINT pk_gs_issuer_admission_cohort_row PRIMARY KEY (operation_id, row_ordinal), + CONSTRAINT uq_gs_issuer_admission_cohort_source UNIQUE (operation_id, source_kind, source_key), + CONSTRAINT fk_gs_issuer_admission_cohort_operation + FOREIGN KEY (operation_id, issuer_id) + REFERENCES game_session_canonical_issuer_admission_operation (operation_id, issuer_id), + CONSTRAINT chk_gs_issuer_admission_cohort_row CHECK ( + row_ordinal >= 0 + AND issuer_id COLLATE "C" = 'firemud-account-service'::character varying COLLATE "C" + AND source_kind IN ( + 'BINDING', 'TRANSITION', 'RESERVATION', 'ACCOUNT_OBLIGATION', + 'ISSUER_OBLIGATION', 'REGION_OBLIGATION', 'LOCAL_OPERATION', + 'BOOTSTRAP_MEMBER_OPERATION', 'PENDING_INITIALIZER') + AND length(source_key) > 0 + AND source_inventory_revision > 0 + AND length(source_row_json) > 1 + AND source_row_digest ~ '^sha256:[0-9a-f]{64}$') +); + +-- The complete original OPEN payload is committed before its one-key Redis operation. It is +-- immutable across retries and remains available to a later cutoff even after a lost reply. +CREATE TABLE game_session_canonical_issuer_admission_initializer ( + operation_id uuid NOT NULL, + issuer_id character varying(64) NOT NULL, + tenant_id uuid NOT NULL, + playable_state_namespace_id uuid NOT NULL, + tenant_gameplay_tag character varying(44) NOT NULL, + live_barrier_epoch numeric NOT NULL, + initialization_state character varying(24) NOT NULL, + initializer_exact_bytes bytea NOT NULL, + initializer_digest character varying(71) NOT NULL, + open_payload_bytes bytea NOT NULL, + open_payload_digest character varying(71) NOT NULL, + created_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT pk_gs_issuer_admission_initializer PRIMARY KEY (operation_id), + CONSTRAINT uq_gs_issuer_admission_initializer_target_epoch + UNIQUE (issuer_id, tenant_id, playable_state_namespace_id, live_barrier_epoch), + CONSTRAINT uq_gs_issuer_admission_initializer_operation_pair UNIQUE (operation_id, issuer_id), + CONSTRAINT fk_gs_issuer_admission_initializer_operation + FOREIGN KEY (operation_id) + REFERENCES game_session_canonical_issuer_binding_local_operation (operation_id), + CONSTRAINT chk_gs_issuer_admission_initializer CHECK ( + issuer_id COLLATE "C" = 'firemud-account-service'::character varying COLLATE "C" + AND tenant_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND playable_state_namespace_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND tenant_gameplay_tag ~ '^g[1-9][0-9]{0,9}-[0-9a-f]{32}$' + AND live_barrier_epoch > 0 + AND initialization_state IN ('PREPARED', 'INITIALIZING', 'OPEN_CONFIRMED') + AND octet_length(initializer_exact_bytes) BETWEEN 1 AND 524288 + AND initializer_digest ~ '^sha256:[0-9a-f]{64}$' + AND octet_length(open_payload_bytes) BETWEEN 1 AND 524288 + AND open_payload_digest ~ '^sha256:[0-9a-f]{64}$') +); + +CREATE TABLE game_session_canonical_issuer_admission_initializer_receipt ( + operation_id uuid NOT NULL, + issuer_id character varying(64) NOT NULL, + exact_open_payload_bytes bytea NOT NULL, + exact_open_payload_digest character varying(71) NOT NULL, + script_outcome smallint NOT NULL, + readback_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT pk_gs_issuer_admission_initializer_receipt PRIMARY KEY (operation_id), + CONSTRAINT fk_gs_issuer_admission_initializer_receipt_initializer + FOREIGN KEY (operation_id, issuer_id) + REFERENCES game_session_canonical_issuer_admission_initializer (operation_id, issuer_id), + CONSTRAINT chk_gs_issuer_admission_initializer_receipt CHECK ( + octet_length(exact_open_payload_bytes) BETWEEN 1 AND 524288 + AND exact_open_payload_digest ~ '^sha256:[0-9a-f]{64}$' + AND script_outcome IN (1, 2)) +); + +CREATE TABLE game_session_canonical_issuer_admission_cutoff_target ( + operation_id uuid NOT NULL, + issuer_id character varying(64) NOT NULL, + target_ordinal bigint NOT NULL, + tenant_id uuid NOT NULL, + playable_state_namespace_id uuid NOT NULL, + tenant_gameplay_tag character varying(44) NOT NULL, + target_source_digest character varying(71) NOT NULL, + captured_initializer_operation_id uuid, + captured_initializer_epoch numeric, + captured_initializer_digest character varying(71), + captured_open_payload_bytes bytea, + captured_open_payload_digest character varying(71), + closed_payload_bytes bytea NOT NULL, + closed_payload_digest character varying(71) NOT NULL, + exact_closed_readback_bytes bytea, + exact_closed_readback_digest character varying(71), + script_outcome smallint, + target_state character varying(24) NOT NULL, + CONSTRAINT pk_gs_issuer_admission_cutoff_target PRIMARY KEY (operation_id, target_ordinal), + CONSTRAINT uq_gs_issuer_admission_cutoff_target UNIQUE + (operation_id, tenant_id, playable_state_namespace_id), + CONSTRAINT fk_gs_issuer_admission_cutoff_target_operation + FOREIGN KEY (operation_id, issuer_id) + REFERENCES game_session_canonical_issuer_admission_operation (operation_id, issuer_id), + CONSTRAINT fk_gs_issuer_admission_cutoff_target_initializer + FOREIGN KEY (captured_initializer_operation_id) + REFERENCES game_session_canonical_issuer_admission_initializer (operation_id), + CONSTRAINT chk_gs_issuer_admission_cutoff_target CHECK ( + target_ordinal >= 0 + AND issuer_id COLLATE "C" = 'firemud-account-service'::character varying COLLATE "C" + AND tenant_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND playable_state_namespace_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND tenant_gameplay_tag ~ '^g[1-9][0-9]{0,9}-[0-9a-f]{32}$' + AND target_source_digest ~ '^sha256:[0-9a-f]{64}$' + AND ((captured_initializer_operation_id IS NULL + AND captured_initializer_epoch IS NULL + AND captured_initializer_digest IS NULL + AND captured_open_payload_bytes IS NULL + AND captured_open_payload_digest IS NULL) + OR (captured_initializer_operation_id IS NOT NULL + AND captured_initializer_epoch > 0 + AND captured_initializer_digest ~ '^sha256:[0-9a-f]{64}$' + AND octet_length(captured_open_payload_bytes) BETWEEN 1 AND 524288 + AND captured_open_payload_digest ~ '^sha256:[0-9a-f]{64}$')) + AND octet_length(closed_payload_bytes) BETWEEN 1 AND 524288 + AND closed_payload_digest ~ '^sha256:[0-9a-f]{64}$' + AND ((target_state = 'REQUIRED' + AND exact_closed_readback_bytes IS NULL + AND exact_closed_readback_digest IS NULL + AND script_outcome IS NULL) + OR (target_state = 'CLOSED' + AND octet_length(exact_closed_readback_bytes) BETWEEN 1 AND 524288 + AND exact_closed_readback_digest ~ '^sha256:[0-9a-f]{64}$' + AND script_outcome IN (1, 2, 3))) +); + +CREATE INDEX ix_gs_issuer_admission_cutoff_target_state + ON game_session_canonical_issuer_admission_cutoff_target (operation_id, target_state, target_ordinal); + +-- One issuer-wide live control must be positively installed before any ordinary issuer write can +-- proceed. The row is immutable provenance plus monotone control; absence is always closed. diff --git a/services/game-session-service/src/main/resources/db/migration/V1047__canonical_initial_account_admission_barrier.sql b/services/game-session-service/src/main/resources/db/migration/V1047__canonical_initial_account_admission_barrier.sql new file mode 100644 index 0000000000..a6bea2e81b --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V1047__canonical_initial_account_admission_barrier.sql @@ -0,0 +1,295 @@ +-- Durable original-attempt source for the first shard-local Account admission OPEN value. +-- The initial path is separate from account-wide CLOSED acquisition and never reopens a key. + +ALTER TABLE game_session_canonical_account_admission_fence_intent_cohort_row + DROP CONSTRAINT chk_gs_canonical_account_admission_fence_intent_cohort_row; + +ALTER TABLE game_session_canonical_account_admission_fence_intent_cohort_row + ADD CONSTRAINT chk_gs_canonical_account_admission_fence_intent_cohort_row CHECK ( + row_ordinal >= 0 + AND account_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND source_kind IN ( + 'BINDING', 'TRANSITION', 'RESERVATION', 'ACCOUNT_OBLIGATION', + 'ISSUER_OBLIGATION', 'REGION_OBLIGATION', 'MEMBER_REPAIR_CONTROL', + 'MEMBER_REPAIR_OPERATION', 'INITIALIZER', 'INITIAL_TARGET') + AND length(source_key) > 0 + AND ((tenant_id IS NULL AND playable_state_namespace_id IS NULL) + OR (tenant_id IS NOT NULL + AND tenant_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND playable_state_namespace_id IS NOT NULL + AND playable_state_namespace_id <> '00000000-0000-0000-0000-000000000000'::uuid)) + AND jsonb_typeof(source_row) = 'object'); + +CREATE TABLE game_session_canonical_initial_account_barrier_initializer ( + initializer_id uuid NOT NULL, + original_request_id uuid NOT NULL, + original_caller_context_id uuid NOT NULL, + original_attempt_fence bigint NOT NULL, + account_id uuid NOT NULL, + account_login_evidence_digest character varying(71) NOT NULL, + source_control_state character varying(32) NOT NULL, + source_control_epoch numeric NOT NULL, + inventory_snapshot_revision numeric NOT NULL, + source_control_digest character varying(71) NOT NULL, + created_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT pk_gs_initial_account_barrier_initializer PRIMARY KEY (initializer_id), + CONSTRAINT uq_gs_initial_account_barrier_initializer_request UNIQUE (original_request_id), + CONSTRAINT uq_gs_initial_account_barrier_initializer_scope + UNIQUE (initializer_id, original_request_id, account_id), + CONSTRAINT fk_gs_initial_account_barrier_initializer_control + FOREIGN KEY (account_id) + REFERENCES game_session_canonical_account_coverage_control (account_id), + CONSTRAINT fk_gs_initial_account_barrier_initializer_original + FOREIGN KEY (original_request_id) + REFERENCES game_session_initial_gameplay_login_journal (request_id), + CONSTRAINT chk_gs_initial_account_barrier_initializer CHECK ( + initializer_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND original_request_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND original_caller_context_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND original_attempt_fence > 0 + AND account_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND account_login_evidence_digest ~ '^sha256:[0-9a-f]{64}$' + AND source_control_state = 'NO_ACTIVE_ACCOUNT_WIDE_FLOW' + AND source_control_epoch >= 0 + AND length(source_control_epoch::text) <= 256 + AND inventory_snapshot_revision > 0 + AND source_control_digest ~ '^sha256:[0-9a-f]{64}$') +); + +CREATE TABLE game_session_canonical_initial_account_barrier_target ( + initializer_id uuid NOT NULL, + original_request_id uuid NOT NULL, + account_id uuid NOT NULL, + target_ordinal bigint NOT NULL, + tenant_id uuid NOT NULL, + playable_state_namespace_id uuid NOT NULL, + target_state character varying(32) NOT NULL, + before_accepted_attestation_digest character varying(71), + before_incarnation_digest character varying(71), + before_source_payload_digest character varying(71), + before_observation_issued_at_epoch_millis bigint, + before_observation_observed_at_epoch_millis bigint, + before_observation_expires_at_epoch_millis bigint, + installed_fields_digest character varying(71), + completed_at timestamp with time zone, + CONSTRAINT pk_gs_initial_account_barrier_target + PRIMARY KEY (initializer_id, target_ordinal), + CONSTRAINT uq_gs_initial_account_barrier_target_scope + UNIQUE (initializer_id, target_ordinal, account_id, tenant_id, playable_state_namespace_id), + CONSTRAINT uq_gs_initial_account_barrier_never_retarget + UNIQUE (account_id, tenant_id, playable_state_namespace_id), + CONSTRAINT fk_gs_initial_account_barrier_target_initializer + FOREIGN KEY (initializer_id, original_request_id, account_id) + REFERENCES game_session_canonical_initial_account_barrier_initializer + (initializer_id, original_request_id, account_id), + CONSTRAINT chk_gs_initial_account_barrier_target CHECK ( + target_ordinal = 0 + AND tenant_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND playable_state_namespace_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND ((target_state = 'NEVER_DISPATCHED' + AND before_accepted_attestation_digest IS NULL + AND before_incarnation_digest IS NULL + AND before_source_payload_digest IS NULL + AND before_observation_issued_at_epoch_millis IS NULL + AND before_observation_observed_at_epoch_millis IS NULL + AND before_observation_expires_at_epoch_millis IS NULL + AND installed_fields_digest IS NULL AND completed_at IS NULL) + OR (target_state = 'DISPATCH_POSSIBLE' + AND before_accepted_attestation_digest IS NOT NULL + AND before_accepted_attestation_digest ~ '^sha256:[0-9a-f]{64}$' + AND before_incarnation_digest IS NOT NULL + AND before_incarnation_digest ~ '^sha256:[0-9a-f]{64}$' + AND before_source_payload_digest IS NOT NULL + AND before_source_payload_digest ~ '^sha256:[0-9a-f]{64}$' + AND before_observation_issued_at_epoch_millis IS NOT NULL + AND before_observation_issued_at_epoch_millis > 0 + AND before_observation_observed_at_epoch_millis IS NOT NULL + AND before_observation_observed_at_epoch_millis + >= before_observation_issued_at_epoch_millis + AND before_observation_expires_at_epoch_millis IS NOT NULL + AND before_observation_expires_at_epoch_millis + > before_observation_observed_at_epoch_millis + AND installed_fields_digest IS NULL AND completed_at IS NULL) + OR (target_state = 'OPEN_INSTALLED' + AND before_accepted_attestation_digest IS NOT NULL + AND before_accepted_attestation_digest ~ '^sha256:[0-9a-f]{64}$' + AND before_incarnation_digest IS NOT NULL + AND before_incarnation_digest ~ '^sha256:[0-9a-f]{64}$' + AND before_source_payload_digest IS NOT NULL + AND before_source_payload_digest ~ '^sha256:[0-9a-f]{64}$' + AND before_observation_issued_at_epoch_millis IS NOT NULL + AND before_observation_issued_at_epoch_millis > 0 + AND before_observation_observed_at_epoch_millis IS NOT NULL + AND before_observation_observed_at_epoch_millis + >= before_observation_issued_at_epoch_millis + AND before_observation_expires_at_epoch_millis IS NOT NULL + AND before_observation_expires_at_epoch_millis + > before_observation_observed_at_epoch_millis + AND installed_fields_digest IS NOT NULL + AND installed_fields_digest ~ '^sha256:[0-9a-f]{64}$' + AND completed_at IS NOT NULL))) +); + +-- [jooq ignore start] +CREATE FUNCTION guard_gs_initial_account_barrier_initializer() RETURNS trigger AS $$ +BEGIN + IF TG_OP IN ('DELETE', 'TRUNCATE') THEN + RAISE EXCEPTION 'Initial account barrier initializer retention is held' USING ERRCODE = '23514'; + END IF; + IF TG_OP = 'INSERT' THEN + IF NEW.created_at IS NULL THEN + RAISE EXCEPTION 'Initial account barrier initializer creation time is required' + USING ERRCODE = '23514'; + END IF; + IF NOT EXISTS ( + SELECT 1 FROM game_session_initial_gameplay_login_journal original + WHERE original.request_id = NEW.original_request_id + AND original.caller_context_id = NEW.original_caller_context_id + AND original.expected_attempt_fence = NEW.original_attempt_fence + AND original.abandoned = FALSE + AND original.verified_token_jti IS NOT NULL + AND original.verified_token_sha256 IS NOT NULL + AND original.verified_token_generation IS NOT NULL + AND original.verified_issuance_fence IS NOT NULL) THEN + RAISE EXCEPTION 'Initial account barrier initializer differs from retained original LOGIN' + USING ERRCODE = '23514'; + END IF; + IF NOT EXISTS ( + SELECT 1 FROM game_session_canonical_account_coverage_control control + WHERE control.account_id = NEW.account_id + AND control.state = 'NO_ACTIVE_ACCOUNT_WIDE_FLOW' + AND control.last_operation_fence = NEW.source_control_epoch + AND control.current_operation_id IS NULL + AND control.current_fence_intent_id IS NULL + AND control.current_operation_fence IS NULL + AND control.account_admission_fence IS NULL + AND control.historical_account_admission_fence IS NULL + AND control.coverage_fence IS NULL + AND control.inventory_snapshot_revision IS NULL + AND control.coverage_generation IS NULL) + OR NOT EXISTS ( + SELECT 1 FROM game_session_canonical_binding_inventory_clock inventory_clock + WHERE inventory_clock.singleton_id = 1 + AND inventory_clock.inventory_revision = NEW.inventory_snapshot_revision + AND inventory_clock.inventory_revision > 0) THEN + RAISE EXCEPTION 'Initial account barrier requires positive current SQL and inventory sources' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; + END IF; + IF ROW(NEW.initializer_id, NEW.original_request_id, NEW.original_caller_context_id, + NEW.original_attempt_fence, NEW.account_id, NEW.source_control_state, + NEW.account_login_evidence_digest, NEW.source_control_epoch, NEW.inventory_snapshot_revision, + NEW.source_control_digest, NEW.created_at) + IS DISTINCT FROM + ROW(OLD.initializer_id, OLD.original_request_id, OLD.original_caller_context_id, + OLD.original_attempt_fence, OLD.account_id, OLD.source_control_state, + OLD.account_login_evidence_digest, OLD.source_control_epoch, OLD.inventory_snapshot_revision, + OLD.source_control_digest, OLD.created_at) THEN + RAISE EXCEPTION 'Initial account barrier initializer source is immutable' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER gs_initial_account_barrier_initializer_guard + BEFORE INSERT OR UPDATE OR DELETE ON game_session_canonical_initial_account_barrier_initializer + FOR EACH ROW EXECUTE FUNCTION guard_gs_initial_account_barrier_initializer(); +CREATE TRIGGER gs_initial_account_barrier_initializer_retention + BEFORE TRUNCATE ON game_session_canonical_initial_account_barrier_initializer + FOR EACH STATEMENT EXECUTE FUNCTION guard_gs_initial_account_barrier_initializer(); + +CREATE FUNCTION guard_gs_initial_account_barrier_target() RETURNS trigger AS $$ +BEGIN + IF TG_OP IN ('DELETE', 'TRUNCATE') THEN + RAISE EXCEPTION 'Initial account barrier target retention is held' USING ERRCODE = '23514'; + END IF; + IF TG_OP = 'INSERT' THEN + IF NEW.target_state <> 'NEVER_DISPATCHED' + OR NEW.before_incarnation_digest IS NOT NULL + OR NEW.installed_fields_digest IS NOT NULL THEN + RAISE EXCEPTION 'Initial account barrier target must begin never-installed' + USING ERRCODE = '23514'; + END IF; + IF NOT EXISTS ( + SELECT 1 + FROM game_session_canonical_account_coverage_control control + JOIN game_session_canonical_initial_account_barrier_initializer initializer + ON initializer.initializer_id = NEW.initializer_id + AND initializer.original_request_id = NEW.original_request_id + AND initializer.account_id = NEW.account_id + WHERE control.account_id = NEW.account_id + AND control.state = 'NO_ACTIVE_ACCOUNT_WIDE_FLOW' + AND control.last_operation_fence = initializer.source_control_epoch + AND control.current_operation_id IS NULL + AND control.current_fence_intent_id IS NULL + AND control.current_operation_fence IS NULL + AND control.account_admission_fence IS NULL + AND control.historical_account_admission_fence IS NULL + AND control.coverage_fence IS NULL + AND control.inventory_snapshot_revision IS NULL + AND control.coverage_generation IS NULL) THEN + RAISE EXCEPTION 'Initial account target requires its positive captured NO_ACTIVE SQL source' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; + END IF; + IF ROW(NEW.initializer_id, NEW.original_request_id, NEW.account_id, NEW.target_ordinal, + NEW.tenant_id, NEW.playable_state_namespace_id) + IS DISTINCT FROM + ROW(OLD.initializer_id, OLD.original_request_id, OLD.account_id, OLD.target_ordinal, + OLD.tenant_id, OLD.playable_state_namespace_id) THEN + RAISE EXCEPTION 'Initial account barrier target identity is immutable' + USING ERRCODE = '23514'; + END IF; + IF OLD.target_state = 'NEVER_DISPATCHED' AND NEW.target_state = 'DISPATCH_POSSIBLE' + AND NEW.before_incarnation_digest IS NOT NULL + AND NEW.installed_fields_digest IS NULL AND NEW.completed_at IS NULL + AND EXISTS ( + SELECT 1 + FROM game_session_canonical_account_coverage_control control + JOIN game_session_canonical_initial_account_barrier_initializer initializer + ON initializer.initializer_id = NEW.initializer_id + AND initializer.original_request_id = NEW.original_request_id + AND initializer.account_id = NEW.account_id + WHERE control.account_id = NEW.account_id + AND control.state = 'NO_ACTIVE_ACCOUNT_WIDE_FLOW' + AND control.last_operation_fence = initializer.source_control_epoch) THEN + RETURN NEW; + END IF; + IF OLD.target_state = 'DISPATCH_POSSIBLE' AND NEW.target_state = 'OPEN_INSTALLED' + AND ROW(NEW.before_accepted_attestation_digest, NEW.before_incarnation_digest, + NEW.before_source_payload_digest, NEW.before_observation_issued_at_epoch_millis, + NEW.before_observation_observed_at_epoch_millis, + NEW.before_observation_expires_at_epoch_millis) + IS NOT DISTINCT FROM + ROW(OLD.before_accepted_attestation_digest, OLD.before_incarnation_digest, + OLD.before_source_payload_digest, OLD.before_observation_issued_at_epoch_millis, + OLD.before_observation_observed_at_epoch_millis, + OLD.before_observation_expires_at_epoch_millis) + AND NEW.installed_fields_digest IS NOT NULL AND NEW.completed_at IS NOT NULL + AND EXISTS ( + SELECT 1 + FROM game_session_canonical_account_coverage_control control + JOIN game_session_canonical_initial_account_barrier_initializer initializer + ON initializer.initializer_id = NEW.initializer_id + AND initializer.original_request_id = NEW.original_request_id + AND initializer.account_id = NEW.account_id + WHERE control.account_id = NEW.account_id + AND control.state = 'NO_ACTIVE_ACCOUNT_WIDE_FLOW' + AND control.last_operation_fence = initializer.source_control_epoch) THEN + RETURN NEW; + END IF; + RAISE EXCEPTION 'Initial account barrier target cannot reset or change its original attempt' + USING ERRCODE = '23514'; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER gs_initial_account_barrier_target_guard + BEFORE INSERT OR UPDATE OR DELETE ON game_session_canonical_initial_account_barrier_target + FOR EACH ROW EXECUTE FUNCTION guard_gs_initial_account_barrier_target(); +CREATE TRIGGER gs_initial_account_barrier_target_retention + BEFORE TRUNCATE ON game_session_canonical_initial_account_barrier_target + FOR EACH STATEMENT EXECUTE FUNCTION guard_gs_initial_account_barrier_target(); +-- [jooq ignore stop] diff --git a/services/game-session-service/src/main/resources/redis/lua/game-session-account-admission-barrier-initial-open.lua b/services/game-session-service/src/main/resources/redis/lua/game-session-account-admission-barrier-initial-open.lua new file mode 100644 index 0000000000..e89bd72a34 --- /dev/null +++ b/services/game-session-service/src/main/resources/redis/lua/game-session-account-admission-barrier-initial-open.lua @@ -0,0 +1,57 @@ +-- Create the one INITIAL OPEN account barrier at its exact captured NO_ACTIVE control epoch. +-- This script is create-only. Retries after a possible dispatch must verify by readback instead. +local prefix = 'session:game:account-admission:' +local fields = { + 'schema', 'accountId', 'tenantId', 'playableStateNamespaceId', 'tenantGameplayTag', + 'ownerOperationId', 'ownerFenceEpoch', 'incarnationDigest', 'state' +} +local function uuid(value) + return type(value) == 'string' and #value == 36 + and string.match(value, '^%x%x%x%x%x%x%x%x%-%x%x%x%x%-%x%x%x%x%-%x%x%x%x%-%x%x%x%x%x%x%x%x%x%x%x%x$') + and value == string.lower(value) + and value ~= '00000000-0000-0000-0000-000000000000' +end +local function tag(value) + if type(value) ~= 'string' or #value > 44 then return false end + local version, opaque = string.match(value, '^g([1-9][0-9]*)%-([0-9a-f]+)$') + return version ~= nil and #version <= 10 and #opaque == 32 +end +local function digest(value) + return type(value) == 'string' and #value == 71 + and string.match(value, '^sha256:[0-9a-f]+$') ~= nil +end +local function epoch(value) + if type(value) ~= 'string' or #value == 0 or #value > 256 then return false end + return value == '0' or string.match(value, '^[1-9][0-9]*$') ~= nil +end + +if #KEYS ~= 1 or #ARGV ~= 9 then return -2 end +local schema = ARGV[1] +local accountId = ARGV[2] +local tenantId = ARGV[3] +local namespaceId = ARGV[4] +local gameplayTag = ARGV[5] +local initializerId = ARGV[6] +local ownerFenceEpoch = ARGV[7] +local incarnationDigest = ARGV[8] +local state = ARGV[9] +if schema ~= 'gs_account_admission_barrier/v1' + or not uuid(accountId) or not uuid(tenantId) or not uuid(namespaceId) + or not tag(gameplayTag) or not uuid(initializerId) or not epoch(ownerFenceEpoch) + or not digest(incarnationDigest) or state ~= 'OPEN' then return -2 end +local expectedKey = prefix .. '{' .. gameplayTag .. '}:' .. accountId .. ':' .. namespaceId +if KEYS[1] ~= expectedKey then return -2 end + +local kind = redis.call('TYPE', KEYS[1]).ok +if kind ~= 'none' or redis.call('PTTL', KEYS[1]) ~= -2 then return 0 end +redis.call('HSET', KEYS[1], + fields[1], schema, + fields[2], accountId, + fields[3], tenantId, + fields[4], namespaceId, + fields[5], gameplayTag, + fields[6], initializerId, + fields[7], ownerFenceEpoch, + fields[8], incarnationDigest, + fields[9], 'OPEN') +return 1 diff --git a/services/game-session-service/src/main/resources/redis/lua/game-session-issuer-admission-barrier-close.lua b/services/game-session-service/src/main/resources/redis/lua/game-session-issuer-admission-barrier-close.lua new file mode 100644 index 0000000000..9505f80010 --- /dev/null +++ b/services/game-session-service/src/main/resources/redis/lua/game-session-issuer-admission-barrier-close.lua @@ -0,0 +1,133 @@ +-- Install one exact SQL-prepared CLOSED issuer barrier for a selected-A cutoff target. +-- One tenant-slot key only; only the exact captured OPEN initializer can be replaced. +local prefix = 'session:game:issuer-admission:' +local schemaValue = 'gs_issuer_admission_barrier/v1' +local fields = { + 'schema', 'issuerId', 'tenantId', 'playableStateNamespaceId', 'tenantGameplayTag', + 'state', 'admissionEpoch', 'ownerOperationId', 'initializerOperationId', + 'initializerEpoch', 'initializerDigest', 'payloadDigest', 'payload' +} +local maxValueBytes = 524288 +local maxDecimalBytes = 256 + +local function uuid(value) + return type(value) == 'string' and #value == 36 + and string.match(value, '^%x%x%x%x%x%x%x%x%-%x%x%x%x%-%x%x%x%x%-%x%x%x%x%-%x%x%x%x%x%x%x%x%x%x%x%x$') + and value == string.lower(value) + and value ~= '00000000-0000-0000-0000-000000000000' +end + +local function positive(value) + return type(value) == 'string' and #value > 0 and #value <= maxDecimalBytes + and string.match(value, '^[1-9][0-9]*$') ~= nil +end + +local function digest(value) + return type(value) == 'string' and #value == 71 + and string.match(value, '^sha256:[0-9a-f]+$') ~= nil +end + +local function decimalLess(left, right) + if #left ~= #right then return #left < #right end + return left < right +end + +if #KEYS ~= 1 or #ARGV ~= 14 then return -2 end +local issuerId = ARGV[1] +local tenantId = ARGV[2] +local namespaceId = ARGV[3] +local gameplayTag = ARGV[4] +local cutoffOperationId = ARGV[5] +local cutoffEpoch = ARGV[6] +local cutoffPayloadDigest = ARGV[7] +local cutoffPayload = ARGV[8] +local initializerOperationId = ARGV[9] +local initializerEpoch = ARGV[10] +local initializerDigest = ARGV[11] +local expectedOpenPayloadDigest = ARGV[12] +local expectedOpenPayload = ARGV[13] +local state = ARGV[14] +local version, opaque +if type(gameplayTag) == 'string' then + version, opaque = string.match(gameplayTag, '^g([1-9][0-9]*)%-([0-9a-f]+)$') +end +if issuerId ~= 'firemud-account-service' or not uuid(tenantId) or not uuid(namespaceId) + or version == nil or #version > 10 or opaque == nil or #opaque ~= 32 or #gameplayTag > 44 + or not uuid(cutoffOperationId) or not positive(cutoffEpoch) + or not digest(cutoffPayloadDigest) or type(cutoffPayload) ~= 'string' + or #cutoffPayload == 0 or #cutoffPayload > maxValueBytes + or (initializerOperationId ~= 'none' and not uuid(initializerOperationId)) + or (initializerEpoch ~= '0' and not positive(initializerEpoch)) + or (initializerDigest ~= 'none' and not digest(initializerDigest)) + or (expectedOpenPayloadDigest ~= 'none' and not digest(expectedOpenPayloadDigest)) + or type(expectedOpenPayload) ~= 'string' or #expectedOpenPayload > maxValueBytes + or state ~= 'CLOSED' then return -2 end +if initializerOperationId == 'none' then + if initializerEpoch ~= '0' or initializerDigest ~= 'none' + or expectedOpenPayloadDigest ~= 'none' or #expectedOpenPayload ~= 0 then return -2 end +else + if initializerEpoch == '0' or initializerDigest == 'none' + or expectedOpenPayloadDigest == 'none' or #expectedOpenPayload == 0 + or not decimalLess(initializerEpoch, cutoffEpoch) then return -2 end +end +local expectedKey = prefix .. '{' .. gameplayTag .. '}:' .. issuerId .. ':' .. tenantId .. ':' .. namespaceId +if KEYS[1] ~= expectedKey then return -2 end + +local function writeClosed() + redis.call('HSET', KEYS[1], + fields[1], schemaValue, + fields[2], issuerId, + fields[3], tenantId, + fields[4], namespaceId, + fields[5], gameplayTag, + fields[6], 'CLOSED', + fields[7], cutoffEpoch, + fields[8], cutoffOperationId, + fields[9], initializerOperationId, + fields[10], initializerEpoch, + fields[11], initializerDigest, + fields[12], cutoffPayloadDigest, + fields[13], cutoffPayload) +end + +local kind = redis.call('TYPE', KEYS[1]).ok +if kind == 'none' then + if redis.call('PTTL', KEYS[1]) ~= -2 then return -1 end + writeClosed() + return 1 +end +if kind ~= 'hash' or redis.call('PTTL', KEYS[1]) ~= -1 then return -1 end +local existing = redis.call('HGETALL', KEYS[1]) +if #existing ~= 2 * #fields then return -1 end +local values = {} +for index = 1, #existing, 2 do + local field = existing[index] + local value = existing[index + 1] + if values[field] ~= nil then return -1 end + local known = false + for fieldIndex = 1, #fields do + if field == fields[fieldIndex] then known = true break end + end + if not known then return -1 end + values[field] = value +end +for fieldIndex = 1, #fields do + if values[fields[fieldIndex]] == nil then return -1 end +end +if values.schema ~= schemaValue or values.issuerId ~= issuerId or values.tenantId ~= tenantId + or values.playableStateNamespaceId ~= namespaceId or values.tenantGameplayTag ~= gameplayTag then return -1 end +if values.state == 'CLOSED' then + if values.admissionEpoch == cutoffEpoch and values.ownerOperationId == cutoffOperationId + and values.initializerOperationId == initializerOperationId + and values.initializerEpoch == initializerEpoch and values.initializerDigest == initializerDigest + and values.payloadDigest == cutoffPayloadDigest and values.payload == cutoffPayload then return 2 end + return -3 +end +if values.state ~= 'OPEN' or initializerOperationId == 'none' + or values.admissionEpoch ~= initializerEpoch or values.ownerOperationId ~= initializerOperationId + or values.initializerOperationId ~= initializerOperationId + or values.initializerEpoch ~= initializerEpoch or values.initializerDigest ~= initializerDigest + or values.payloadDigest ~= expectedOpenPayloadDigest or values.payload ~= expectedOpenPayload + or not decimalLess(values.admissionEpoch, cutoffEpoch) then return -3 end +writeClosed() +return 3 diff --git a/services/game-session-service/src/main/resources/redis/lua/game-session-issuer-admission-barrier-open.lua b/services/game-session-service/src/main/resources/redis/lua/game-session-issuer-admission-barrier-open.lua new file mode 100644 index 0000000000..09e9b1a1fd --- /dev/null +++ b/services/game-session-service/src/main/resources/redis/lua/game-session-issuer-admission-barrier-open.lua @@ -0,0 +1,106 @@ +-- Install one exact SQL-prepared initial OPEN issuer admission barrier. +-- This one tenant-slot key only; absence is usable only for this exact original initializer. +local prefix = 'session:game:issuer-admission:' +local schemaValue = 'gs_issuer_admission_barrier/v1' +local fields = { + 'schema', 'issuerId', 'tenantId', 'playableStateNamespaceId', 'tenantGameplayTag', + 'state', 'admissionEpoch', 'ownerOperationId', 'initializerOperationId', + 'initializerEpoch', 'initializerDigest', 'payloadDigest', 'payload' +} +local maxValueBytes = 524288 +local maxDecimalBytes = 256 + +local function uuid(value) + return type(value) == 'string' and #value == 36 + and string.match(value, '^%x%x%x%x%x%x%x%x%-%x%x%x%x%-%x%x%x%x%-%x%x%x%x%-%x%x%x%x%x%x%x%x%x%x%x%x$') + and value == string.lower(value) + and value ~= '00000000-0000-0000-0000-000000000000' +end + +local function positive(value) + return type(value) == 'string' and #value > 0 and #value <= maxDecimalBytes + and string.match(value, '^[1-9][0-9]*$') ~= nil +end + +local function digest(value) + return type(value) == 'string' and #value == 71 + and string.match(value, '^sha256:[0-9a-f]+$') ~= nil +end + +local function tag(value) + if type(value) ~= 'string' or #value > 44 then return false end + local version, opaque = string.match(value, '^g([1-9][0-9]*)%-([0-9a-f]+)$') + return version ~= nil and #version <= 10 and opaque ~= nil and #opaque == 32 +end + +if #KEYS ~= 1 or #ARGV ~= 11 then return -2 end +local issuerId = ARGV[1] +local tenantId = ARGV[2] +local namespaceId = ARGV[3] +local gameplayTag = ARGV[4] +local operationId = ARGV[5] +local admissionEpoch = ARGV[6] +local initializerDigest = ARGV[7] +local payloadDigest = ARGV[8] +local payload = ARGV[9] +local state = ARGV[10] +local createMode = ARGV[11] +if issuerId ~= 'firemud-account-service' or not uuid(tenantId) or not uuid(namespaceId) + or not tag(gameplayTag) + or not uuid(operationId) or not positive(admissionEpoch) + or not digest(initializerDigest) or not digest(payloadDigest) + or type(payload) ~= 'string' or #payload == 0 or #payload > maxValueBytes + or state ~= 'OPEN' + or (createMode ~= 'CREATE_ONCE' and createMode ~= 'REPLAY_ONLY') then return -2 end +local expectedKey = prefix .. '{' .. gameplayTag .. '}:' .. issuerId .. ':' .. tenantId .. ':' .. namespaceId +if KEYS[1] ~= expectedKey then return -2 end + +local function writeOpen() + redis.call('HSET', KEYS[1], + fields[1], schemaValue, + fields[2], issuerId, + fields[3], tenantId, + fields[4], namespaceId, + fields[5], gameplayTag, + fields[6], 'OPEN', + fields[7], admissionEpoch, + fields[8], operationId, + fields[9], operationId, + fields[10], admissionEpoch, + fields[11], initializerDigest, + fields[12], payloadDigest, + fields[13], payload) +end + +local kind = redis.call('TYPE', KEYS[1]).ok +if kind == 'none' then + if redis.call('PTTL', KEYS[1]) ~= -2 then return -1 end + if createMode ~= 'CREATE_ONCE' then return -1 end + writeOpen() + return 1 +end +if kind ~= 'hash' or redis.call('PTTL', KEYS[1]) ~= -1 then return -1 end +local existing = redis.call('HGETALL', KEYS[1]) +if #existing ~= 2 * #fields then return -1 end +local values = {} +for index = 1, #existing, 2 do + local field = existing[index] + local value = existing[index + 1] + if values[field] ~= nil then return -1 end + local known = false + for fieldIndex = 1, #fields do + if field == fields[fieldIndex] then known = true break end + end + if not known then return -1 end + values[field] = value +end +for fieldIndex = 1, #fields do + if values[fields[fieldIndex]] == nil then return -1 end +end +if values.schema ~= schemaValue or values.issuerId ~= issuerId or values.tenantId ~= tenantId + or values.playableStateNamespaceId ~= namespaceId or values.tenantGameplayTag ~= gameplayTag + or values.state ~= 'OPEN' or values.admissionEpoch ~= admissionEpoch + or values.ownerOperationId ~= operationId or values.initializerOperationId ~= operationId + or values.initializerEpoch ~= admissionEpoch or values.initializerDigest ~= initializerDigest + or values.payloadDigest ~= payloadDigest or values.payload ~= payload then return -3 end +return 2 diff --git a/services/game-session-service/src/main/resources/redis/scripts/game-session-account-admission-barrier-initial-open.json b/services/game-session-service/src/main/resources/redis/scripts/game-session-account-admission-barrier-initial-open.json new file mode 100644 index 0000000000..7f68d252f8 --- /dev/null +++ b/services/game-session-service/src/main/resources/redis/scripts/game-session-account-admission-barrier-initial-open.json @@ -0,0 +1,41 @@ +{ + "scriptId": "game-session.account-admission-barrier-initial-open.v1", + "resourcePath": "redis/lua/game-session-account-admission-barrier-initial-open.lua", + "sha256": "472d1dc1097f67e35fedf7cd658694b29c9827604e3093c1426b5ed46bb8c20e", + "owner": "game-session-service", + "principal": "gamesession_coord_app", + "role": "COORDINATION", + "keys": [ + { + "name": "accountAdmissionBarrier", + "ownedPrefix": "session:game:account-admission:", + "hashTagDeclaration": "REQUIRED" + } + ], + "arguments": [ + {"name": "schema"}, + {"name": "accountId"}, + {"name": "tenantId"}, + {"name": "playableStateNamespaceId"}, + {"name": "tenantGameplayTag"}, + {"name": "initializerId"}, + {"name": "ownerFenceEpoch"}, + {"name": "incarnationDigest"}, + {"name": "state"} + ], + "category": "SESSION_CAS", + "outcomes": [ + {"code": "OPEN_CREATED", "category": "SUCCESS", "effect": "MUTATING"}, + {"code": "TARGET_ALREADY_PRESENT", "category": "STALE", "effect": "NON_MUTATING"}, + {"code": "TYPE_TTL_OR_FIELDS_REFUSED", "category": "VALIDATION_FAILURE", "effect": "NON_MUTATING"}, + {"code": "INVALID_ARGUMENTS", "category": "VALIDATION_FAILURE", "effect": "NON_MUTATING"} + ], + "resetSensitivity": "CLUSTER", + "lossClass": "EMPTY_REDIS_COLD_START_OR_RESET", + "tailLossBehavior": "The INITIAL OPEN barrier may be created once only for the persisted original request while the positive SQL account-control source remains at its exact captured NO_ACTIVE_ACCOUNT_WIDE_FLOW epoch. SQL records possible dispatch before the one-key call. Every retry after that point is read-only and requires exact original OPEN readback plus protected incarnation observation. A missing key after a possible dispatch is reset or unknown-outcome evidence and remains non-admitting; it is never a fresh OPEN source. Every existing key, including CLOSED, newer, malformed, expiring, or conflicting values, is refused without mutation. This local proof does not supply Account lease/currentness, issuer or region acknowledgements, final binding CAS, or gameplay admission.", + "compatibilityLevel": "REQUIRES_CLUSTER_RESET", + "supportedCoexistence": [ + {"callerVersion": "v1", "payloadVersion": "none"} + ], + "legacyPayloadShape": null +} diff --git a/services/game-session-service/src/main/resources/redis/scripts/game-session-issuer-admission-barrier-close.json b/services/game-session-service/src/main/resources/redis/scripts/game-session-issuer-admission-barrier-close.json new file mode 100644 index 0000000000..6b51240ef8 --- /dev/null +++ b/services/game-session-service/src/main/resources/redis/scripts/game-session-issuer-admission-barrier-close.json @@ -0,0 +1,48 @@ +{ + "scriptId": "game-session.issuer-admission-barrier-close.v1", + "resourcePath": "redis/lua/game-session-issuer-admission-barrier-close.lua", + "sha256": "ab75bdcc1f157af3c78e954a57512f3815fd81ccae1c4f7a9ace02beced15323", + "owner": "game-session-service", + "principal": "gamesession_coord_app", + "role": "COORDINATION", + "keys": [ + { + "name": "issuerAdmissionBarrier", + "ownedPrefix": "session:game:issuer-admission:", + "hashTagDeclaration": "REQUIRED" + } + ], + "arguments": [ + {"name": "issuerId"}, + {"name": "tenantId"}, + {"name": "playableStateNamespaceId"}, + {"name": "tenantGameplayTag"}, + {"name": "cutoffOperationId"}, + {"name": "cutoffAdmissionBarrierEpoch"}, + {"name": "exactClosedPayloadDigest"}, + {"name": "exactClosedPayload"}, + {"name": "capturedInitializerOperationIdOrNone"}, + {"name": "capturedInitializerAdmissionBarrierEpochOrZero"}, + {"name": "capturedInitializerTupleDigestOrNone"}, + {"name": "expectedOriginalOpenPayloadDigestOrNone"}, + {"name": "expectedOriginalOpenPayloadOrEmpty"}, + {"name": "state"} + ], + "category": "SESSION_CAS", + "outcomes": [ + {"code": "CLOSED_CREATED", "category": "SUCCESS", "effect": "MUTATING"}, + {"code": "CLOSED_REPLAY", "category": "REPLAY", "effect": "NON_MUTATING"}, + {"code": "CAPTURED_OPEN_CLOSED", "category": "SUCCESS", "effect": "MUTATING"}, + {"code": "TYPE_TTL_OR_FIELDSET_REFUSED", "category": "VALIDATION_FAILURE", "effect": "NON_MUTATING"}, + {"code": "INVALID_ARGUMENTS_OR_TARGET", "category": "VALIDATION_FAILURE", "effect": "NON_MUTATING"}, + {"code": "NEWER_CLOSED_OR_UNEXPECTED_STATE", "category": "STALE", "effect": "NON_MUTATING"} + ], + "resetSensitivity": "CLUSTER", + "tailLossBehavior": "A selected issuer cutoff closes only its exact tenant target under the captured cutoff epoch and tuple. It may create CLOSED from absence or replace the exact captured original OPEN payload with a higher cutoff epoch. Existing CLOSED, newer or conflicting state, malformed/reset state, or a different OPEN initializer remains unresolved and non-admitting. Exact CLOSED readback is required before the SQL cohort may become INSTALLED. This script never opens admission or touches the global issuer index/capacity key.", + "lossClass": "EMPTY_REDIS_COLD_START_OR_RESET", + "compatibilityLevel": "REQUIRES_CLUSTER_RESET", + "supportedCoexistence": [ + {"callerVersion": "v1", "payloadVersion": "none"} + ], + "legacyPayloadShape": null +} diff --git a/services/game-session-service/src/main/resources/redis/scripts/game-session-issuer-admission-barrier-open.json b/services/game-session-service/src/main/resources/redis/scripts/game-session-issuer-admission-barrier-open.json new file mode 100644 index 0000000000..39a007457e --- /dev/null +++ b/services/game-session-service/src/main/resources/redis/scripts/game-session-issuer-admission-barrier-open.json @@ -0,0 +1,44 @@ +{ + "scriptId": "game-session.issuer-admission-barrier-open.v1", + "resourcePath": "redis/lua/game-session-issuer-admission-barrier-open.lua", + "sha256": "93c6c553ed9a4c245982448f90b34c2c2b03dace8a7a78a58545375edd5888eb", + "owner": "game-session-service", + "principal": "gamesession_coord_app", + "role": "COORDINATION", + "keys": [ + { + "name": "issuerAdmissionBarrier", + "ownedPrefix": "session:game:issuer-admission:", + "hashTagDeclaration": "REQUIRED" + } + ], + "arguments": [ + {"name": "issuerId"}, + {"name": "tenantId"}, + {"name": "playableStateNamespaceId"}, + {"name": "tenantGameplayTag"}, + {"name": "initializerOperationId"}, + {"name": "admissionBarrierEpoch"}, + {"name": "initializerTupleDigest"}, + {"name": "exactBarrierPayloadDigest"}, + {"name": "exactBarrierPayload"}, + {"name": "state"}, + {"name": "createMode"} + ], + "category": "SESSION_CAS", + "outcomes": [ + {"code": "OPEN_CREATED", "category": "SUCCESS", "effect": "MUTATING"}, + {"code": "OPEN_REPLAY", "category": "REPLAY", "effect": "NON_MUTATING"}, + {"code": "TYPE_TTL_OR_FIELDSET_REFUSED", "category": "VALIDATION_FAILURE", "effect": "NON_MUTATING"}, + {"code": "INVALID_ARGUMENTS_OR_TARGET", "category": "VALIDATION_FAILURE", "effect": "NON_MUTATING"}, + {"code": "CLOSED_OR_CONFLICTING_STATE", "category": "STALE", "effect": "NON_MUTATING"} + ], + "resetSensitivity": "CLUSTER", + "tailLossBehavior": "An issuer tenant barrier opens from absent Redis only with the one-use SQL-issued CREATE_ONCE permit consumed by the first initializer attempt. Later retries use REPLAY_ONLY and can confirm only the complete exact original OPEN tuple already present; absent, reset, CLOSED, malformed, changed source, or conflicting target state is non-admitting. The initializer and physical result remain pending for controlled recovery; this script does not recreate, reopen, renew, acknowledge issuer-wide coverage, or touch a global issuer key.", + "lossClass": "EMPTY_REDIS_COLD_START_OR_RESET", + "compatibilityLevel": "REQUIRES_CLUSTER_RESET", + "supportedCoexistence": [ + {"callerVersion": "v1", "payloadVersion": "none"} + ], + "legacyPayloadShape": null +} diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountAdmissionBarrierRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountAdmissionBarrierRepositoryIntegrationTest.java index 784342800f..29ece781fb 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountAdmissionBarrierRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountAdmissionBarrierRepositoryIntegrationTest.java @@ -2,7 +2,10 @@ 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.when; +import com.google.protobuf.ByteString; import java.math.BigDecimal; import java.math.BigInteger; import java.nio.charset.StandardCharsets; @@ -211,6 +214,174 @@ void intentCapturesEveryExistingTenantNamespaceForTheAccountOnly() { } } + @Test + void pendingInitialAccountTargetIsFrozenIntoCutoffAndItsTargetSet() { + TestSchema testSchema = newTestSchema("gs_account_fence_initial_target_"); + try { + establishActualLegacyDisposition(testSchema.dsl()); + var inventory = new CanonicalGameplayBindingInventoryRepository(testSchema.dsl()); + prepare(inventory, ACCOUNT_ID, TENANT_ID, NAMESPACE_ID, 1); + var initial = + insertControlledInitialTarget( + testSchema.dsl(), ACCOUNT_ID, OTHER_TENANT_ID, OTHER_NAMESPACE_ID); + + var cutoff = + new CanonicalGameplayAccountAdmissionBarrierRepository(testSchema.dsl()) + .beginFenceIntent(ACCOUNT_ID, UUID.randomUUID()); + + assertThat(cutoff.cohortRows()) + .anySatisfy( + row -> { + assertThat(row.kind()) + .isEqualTo(CanonicalGameplayAccountAdmissionFenceIntent.CohortKind.INITIALIZER); + assertThat(row.sourceKey()).isEqualTo(initial.originalRequestId().toString()); + assertThat(row.sourceRecordJson()).contains(initial.initializerId().toString()); + }); + assertThat(cutoff.cohortRows()) + .anySatisfy( + row -> { + assertThat(row.kind()) + .isEqualTo(CanonicalGameplayAccountAdmissionFenceIntent.CohortKind.INITIAL_TARGET); + assertThat(row.sourceKey()).isEqualTo(initial.initializerId() + ":0"); + assertThat(row.tenantId()).isEqualTo(OTHER_TENANT_ID); + assertThat(row.playableStateNamespaceId()).isEqualTo(OTHER_NAMESPACE_ID); + }); + assertThat(cutoff.barrierTargets()) + .extracting( + CanonicalGameplayAccountAdmissionFenceIntent.BarrierTarget::tenantId, + CanonicalGameplayAccountAdmissionFenceIntent.BarrierTarget::playableStateNamespaceId) + .contains(org.assertj.core.groups.Tuple.tuple(OTHER_TENANT_ID, OTHER_NAMESPACE_ID)); + assertThatThrownBy( + () -> + insertControlledInitialTarget( + testSchema.dsl(), ACCOUNT_ID, TENANT_ID, OTHER_NAMESPACE_ID)) + .isInstanceOfSatisfying( + org.jooq.exception.DataAccessException.class, + failure -> assertThat(failure.sqlState()).isEqualTo("23514")); + } finally { + dropSchema(testSchema.schema()); + } + } + + @Test + void accountCutoffThatWinsInventoryClockOrderBlocksAnInitialTargetInsert() { + TestSchema testSchema = newTestSchema("gs_account_fence_initial_cutoff_wins_"); + try { + establishActualLegacyDisposition(testSchema.dsl()); + var inventory = new CanonicalGameplayBindingInventoryRepository(testSchema.dsl()); + prepare(inventory, ACCOUNT_ID, TENANT_ID, NAMESPACE_ID, 1); + var cutoff = + new CanonicalGameplayAccountAdmissionBarrierRepository(testSchema.dsl()) + .beginFenceIntent(ACCOUNT_ID, UUID.randomUUID()); + + assertThat(cutoff.cohortRows()) + .noneSatisfy( + row -> + assertThat(row.kind()) + .isIn( + CanonicalGameplayAccountAdmissionFenceIntent.CohortKind.INITIALIZER, + CanonicalGameplayAccountAdmissionFenceIntent.CohortKind.INITIAL_TARGET)); + assertThatThrownBy( + () -> insertControlledInitialTarget(testSchema.dsl(), ACCOUNT_ID, OTHER_TENANT_ID, OTHER_NAMESPACE_ID)) + .isInstanceOfSatisfying( + org.jooq.exception.DataAccessException.class, + failure -> assertThat(failure.sqlState()).isEqualTo("23514")); + assertThat( + testSchema + .dsl() + .fetchSingle( + "SELECT count(*) AS row_count FROM" + + " game_session_canonical_initial_account_barrier_initializer" + + " WHERE account_id = ?", + ACCOUNT_ID) + .get("row_count", Long.class)) + .isZero(); + } finally { + dropSchema(testSchema.schema()); + } + } + + @Test + void initialSourceRequiresPresentNoActiveControlAndPreservesItsActualEpochIncludingZero() { + TestSchema missingControlSchema = newTestSchema("gs_account_initial_missing_control_"); + try { + establishActualLegacyDisposition(missingControlSchema.dsl()); + missingControlSchema + .dsl() + .execute( + "UPDATE game_session_canonical_binding_inventory_clock" + + " SET inventory_revision = 1 WHERE singleton_id = 1"); + var original = new net.firedevops.firemud.gamesession.dto.InitialGameplayLoginAttemptCoordinates( + UUID.randomUUID(), UUID.randomUUID(), 17L); + var login = mockLoginResult(original, UUID.randomUUID(), UUID.randomUUID()); + + assertThatThrownBy( + () -> + new CanonicalGameplayAccountInitialBarrierInitializerRepository( + missingControlSchema.dsl()) + .beginOrRead(original, login, OTHER_TENANT_ID, OTHER_NAMESPACE_ID)) + .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) + .hasMessageContaining("Account coverage control row is missing"); + } finally { + dropSchema(missingControlSchema.schema()); + } + + TestSchema nonzeroEpochSchema = newTestSchema("gs_account_initial_nonzero_epoch_"); + try { + establishActualLegacyDisposition(nonzeroEpochSchema.dsl()); + var inventory = new CanonicalGameplayBindingInventoryRepository(nonzeroEpochSchema.dsl()); + prepare(inventory, ACCOUNT_ID, TENANT_ID, NAMESPACE_ID, 1); + var original = + new net.firedevops.firemud.gamesession.dto.InitialGameplayLoginAttemptCoordinates( + UUID.randomUUID(), UUID.randomUUID(), 17L); + var login = mockLoginResult(original, ACCOUNT_ID, UUID.randomUUID()); + insertCommittedOriginalLogin(nonzeroEpochSchema.dsl(), original, login.evidence()); + nonzeroEpochSchema + .dsl() + .execute( + "UPDATE game_session_canonical_account_coverage_control" + + " SET last_operation_fence = 8 WHERE account_id = ?", + ACCOUNT_ID); + + var initializer = + new CanonicalGameplayAccountInitialBarrierInitializerRepository(nonzeroEpochSchema.dsl()) + .beginOrRead(original, login, OTHER_TENANT_ID, OTHER_NAMESPACE_ID); + + assertThat(initializer.sourceControlState()).isEqualTo("NO_ACTIVE_ACCOUNT_WIDE_FLOW"); + assertThat(initializer.sourceControlEpoch()).isEqualTo(BigInteger.valueOf(8)); + assertThat(initializer.state()) + .isEqualTo( + CanonicalGameplayAccountInitialBarrierInitializerRepository.State.NEVER_DISPATCHED); + } finally { + dropSchema(nonzeroEpochSchema.schema()); + } + + TestSchema zeroEpochSchema = newTestSchema("gs_account_initial_zero_epoch_"); + try { + establishActualLegacyDisposition(zeroEpochSchema.dsl()); + prepare( + new CanonicalGameplayBindingInventoryRepository(zeroEpochSchema.dsl()), + ACCOUNT_ID, + TENANT_ID, + NAMESPACE_ID, + 1); + var original = + new net.firedevops.firemud.gamesession.dto.InitialGameplayLoginAttemptCoordinates( + UUID.randomUUID(), UUID.randomUUID(), 17L); + var login = mockLoginResult(original, ACCOUNT_ID, UUID.randomUUID()); + insertCommittedOriginalLogin(zeroEpochSchema.dsl(), original, login.evidence()); + + var initializer = + new CanonicalGameplayAccountInitialBarrierInitializerRepository(zeroEpochSchema.dsl()) + .beginOrRead(original, login, OTHER_TENANT_ID, OTHER_NAMESPACE_ID); + + assertThat(initializer.sourceControlState()).isEqualTo("NO_ACTIVE_ACCOUNT_WIDE_FLOW"); + assertThat(initializer.sourceControlEpoch()).isEqualTo(BigInteger.ZERO); + } finally { + dropSchema(zeroEpochSchema.schema()); + } + } + @Test void preparationRacingIntentIsEitherCapturedOrRefused() throws Exception { TestSchema testSchema = newTestSchema("gs_account_fence_race_"); @@ -405,6 +576,119 @@ private static CanonicalGameplayBindingTransitionSnapshot prepare( transitionId, UUID.randomUUID(), candidate, reservation, null, null)); } + /** Controlled durable SQL source used only to exercise the existing inventory/control lock order. */ + private static ControlledInitialTarget insertControlledInitialTarget( + DSLContext dsl, UUID accountId, UUID tenantId, UUID namespaceId) { + UUID originalRequestId = UUID.randomUUID(); + UUID callerContextId = UUID.randomUUID(); + UUID initializerId = UUID.randomUUID(); + UUID tokenJti = UUID.randomUUID(); + String accountEvidenceDigest = "sha256:" + "a".repeat(64); + String sourceControlDigest = "sha256:" + "b".repeat(64); + dsl.transaction( + configuration -> { + var transaction = org.jooq.impl.DSL.using(configuration); + var inventoryClock = + transaction.fetchOne( + "SELECT inventory_revision FROM game_session_canonical_binding_inventory_clock" + + " WHERE singleton_id = 1 FOR UPDATE"); + var control = + transaction.fetchOne( + "SELECT state, last_operation_fence FROM" + + " game_session_canonical_account_coverage_control" + + " WHERE account_id = ? FOR UPDATE", + accountId); + if (inventoryClock == null || control == null) { + throw new IllegalStateException("Controlled source lacks positive SQL owners"); + } + transaction.execute( + "INSERT INTO game_session_initial_gameplay_login_journal" + + " (request_id, caller_context_id, expected_attempt_fence) VALUES (?, ?, 7)", + originalRequestId, + callerContextId); + transaction.execute( + "UPDATE game_session_initial_gameplay_login_journal" + + " SET verified_token_jti = ?, verified_token_sha256 = ?," + + " verified_token_generation = 1, verified_issuance_fence = 1" + + " WHERE request_id = ?", + tokenJti, + "c".repeat(64), + originalRequestId); + transaction.execute( + "INSERT INTO game_session_canonical_initial_account_barrier_initializer" + + " (initializer_id, original_request_id, original_caller_context_id," + + " original_attempt_fence, account_id, account_login_evidence_digest," + + " source_control_state, source_control_epoch, inventory_snapshot_revision," + + " source_control_digest) VALUES (?, ?, ?, 7, ?, ?, ?, 0, ?, ?)", + initializerId, + originalRequestId, + callerContextId, + accountId, + accountEvidenceDigest, + "NO_ACTIVE_ACCOUNT_WIDE_FLOW", + inventoryClock.get("inventory_revision"), + sourceControlDigest); + transaction.execute( + "INSERT INTO game_session_canonical_initial_account_barrier_target" + + " (initializer_id, original_request_id, account_id, target_ordinal, tenant_id," + + " playable_state_namespace_id, target_state)" + + " VALUES (?, ?, ?, 0, ?, ?, 'NEVER_DISPATCHED')", + initializerId, + originalRequestId, + accountId, + tenantId, + namespaceId); + }); + return new ControlledInitialTarget(initializerId, originalRequestId); + } + + private static net.firedevops.firemud.gamesession.dto.CanonicalGameplayLoginResult mockLoginResult( + net.firedevops.firemud.gamesession.dto.InitialGameplayLoginAttemptCoordinates coordinates, + UUID accountId, + UUID tokenJti) { + var evidence = + new net.firedevops.firemud.gamesession.dto.CanonicalGameplayLoginResult.NonSecretEvidence( + accountId, + coordinates.requestId(), + coordinates.callerContextId(), + tokenJti, + "d".repeat(64), + GameSessionAccountDelegationProfile.PROFILE, + 1_000L, + 1_000L, + 2_000L, + "1", + "1", + ByteString.copyFromUtf8("{}"), + ByteString.copyFromUtf8("[]"), + ByteString.copyFromUtf8("[]")); + var result = mock(net.firedevops.firemud.gamesession.dto.CanonicalGameplayLoginResult.class); + when(result.evidence()).thenReturn(evidence); + return result; + } + + private static void insertCommittedOriginalLogin( + DSLContext dsl, + net.firedevops.firemud.gamesession.dto.InitialGameplayLoginAttemptCoordinates original, + net.firedevops.firemud.gamesession.dto.CanonicalGameplayLoginResult.NonSecretEvidence evidence) { + dsl.execute( + "INSERT INTO game_session_initial_gameplay_login_journal" + + " (request_id, caller_context_id, expected_attempt_fence) VALUES (?, ?, ?)", + original.requestId(), + original.callerContextId(), + original.expectedAttemptFence()); + dsl.execute( + "UPDATE game_session_initial_gameplay_login_journal" + + " SET verified_token_jti = ?, verified_token_sha256 = ?," + + " verified_token_generation = ?, verified_issuance_fence = ?" + + " WHERE request_id = ?", + evidence.tokenJti(), + evidence.tokenSha256(), + Long.parseLong(evidence.tokenGeneration()), + Long.parseLong(evidence.issuanceFence()), + original.requestId()); + } + private static void establishActualLegacyDisposition(DSLContext dsl) { var inventory = new CanonicalGameplayBindingInventoryRepository(dsl); var migration = new CanonicalGameplayLegacyMigrationRepository(dsl, inventory); @@ -538,4 +822,6 @@ private static void assertCheckConstraintViolation( } private record TestSchema(String schema, DSLContext dsl) {} + + private record ControlledInitialTarget(UUID initializerId, UUID originalRequestId) {} } diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierRedisScriptIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierRedisScriptIntegrationTest.java new file mode 100644 index 0000000000..78ae8a98e1 --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierRedisScriptIntegrationTest.java @@ -0,0 +1,225 @@ +package integration.net.firedevops.firemud.gamesession.repository; + +import static org.assertj.core.api.Assertions.assertThat; + +import io.lettuce.core.AclSetuserArgs; +import io.lettuce.core.ClientOptions; +import io.lettuce.core.RedisClient; +import io.lettuce.core.RedisURI; +import io.lettuce.core.ScriptOutputType; +import io.lettuce.core.api.StatefulRedisConnection; +import io.lettuce.core.api.sync.RedisCommands; +import io.lettuce.core.codec.ByteArrayCodec; +import io.lettuce.core.protocol.CommandKeyword; +import io.lettuce.core.protocol.CommandType; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.time.Duration; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor; +import net.firedevops.firemud.gamesession.service.CanonicalGameplayAccountInitialBarrierRedisScriptContribution; +import net.firedevops.firemud.test.TestContainerImages; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** Native Redis proof of create-only OPEN, exact physical readback, and CLOSED precedence. */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class CanonicalGameplayAccountInitialBarrierRedisScriptIntegrationTest { + private static final String PRINCIPAL = "gamesession_coord_app"; + private static final String SCHEMA = "gs_account_admission_barrier/v1"; + private static final String INCARNATION = "sha256:" + "a".repeat(64); + + @Container + private static final GenericContainer REDIS = + new GenericContainer<>(TestContainerImages.redis()).withExposedPorts(6379); + + private RedisClient administrator; + private StatefulRedisConnection administratorConnection; + private RedisCommands administratorCommands; + private RedisClient ownerClient; + + @BeforeEach + void configureOwnerPrincipal() { + String password = UUID.randomUUID().toString(); + administrator = createClient(null, null); + administratorConnection = administrator.connect(ByteArrayCodec.INSTANCE); + administratorCommands = administratorConnection.sync(); + administratorCommands.flushdb(); + administratorCommands.aclSetuser( + PRINCIPAL, + new AclSetuserArgs() + .reset() + .on() + .addPassword(password) + .keyPattern("session:game:*") + .addCommand(CommandType.HELLO) + .addCommand(CommandType.PING) + .addCommand(CommandType.CLIENT, CommandKeyword.SETINFO) + .addCommand(CommandType.ACL, CommandKeyword.WHOAMI) + .addCommand(CommandType.SCRIPT, CommandKeyword.LOAD) + .addCommand(CommandType.EVALSHA) + .addCommand(CommandType.TYPE) + .addCommand(CommandType.PTTL) + .addCommand(CommandType.HLEN) + .addCommand(CommandType.HGETALL) + .addCommand(CommandType.HSET)); + ownerClient = createClient(PRINCIPAL, password); + } + + @AfterEach + void closeOwnedClients() { + if (administratorConnection != null) administratorConnection.close(); + if (ownerClient != null) ownerClient.shutdown(Duration.ZERO, Duration.ofSeconds(2)); + if (administrator != null) administrator.shutdown(Duration.ZERO, Duration.ofSeconds(2)); + } + + @Test + void oneKeyOpenIsReadBackExactlyAndEveryExistingClosedTargetWins() throws Exception { + UUID accountId = UUID.randomUUID(); + UUID tenantId = UUID.randomUUID(); + UUID namespaceId = UUID.randomUUID(); + UUID initializerId = UUID.randomUUID(); + String gameplayTag = "g8-" + "b".repeat(32); + String key = + "session:game:account-admission:{" + + gameplayTag + + "}:" + accountId + ":" + namespaceId; + Map expectedOpen = + Map.of( + "schema", SCHEMA, + "accountId", accountId.toString(), + "tenantId", tenantId.toString(), + "playableStateNamespaceId", namespaceId.toString(), + "tenantGameplayTag", gameplayTag, + "ownerOperationId", initializerId.toString(), + "ownerFenceEpoch", "8", + "incarnationDigest", INCARNATION, + "state", "OPEN"); + RedisScriptDescriptor descriptor = + RedisScriptCatalog.fromContributions( + List.of(new CanonicalGameplayAccountInitialBarrierRedisScriptContribution())) + .require(CanonicalGameplayAccountInitialBarrierRedisScriptContribution.SCRIPT_ID); + byte[] script; + try (InputStream input = + getClass().getClassLoader().getResourceAsStream(descriptor.resourcePath())) { + assertThat(input).isNotNull(); + script = input.readAllBytes(); + } + assertThat(hexSha256(script)).isEqualTo(descriptor.sha256()); + + try (StatefulRedisConnection ownerConnection = + ownerClient.connect(ByteArrayCodec.INSTANCE)) { + RedisCommands commands = ownerConnection.sync(); + assertThat(commands.aclWhoami()).isEqualTo(PRINCIPAL); + String sha = commands.scriptLoad(script); + assertThat(sha).isEqualTo(hexSha1(script)); + byte[][] arguments = + openArguments(accountId, tenantId, namespaceId, gameplayTag, initializerId, "8"); + + assertThat( + commands.evalsha( + sha, ScriptOutputType.INTEGER, new byte[][] {ascii(key)}, arguments)) + .isEqualTo(1L); + assertThat(commands.type(ascii(key))).isEqualTo("hash"); + assertThat(commands.pttl(ascii(key))).isEqualTo(-1L); + assertThat(commands.hlen(ascii(key))).isEqualTo(9L); + assertThat(readFields(commands, key)).isEqualTo(expectedOpen); + + // A lost response cannot turn the key into a mutable replay; the SQL owner handles retries + // with exact readback and never executes this create script again after DISPATCH_POSSIBLE. + assertThat( + commands.evalsha( + sha, ScriptOutputType.INTEGER, new byte[][] {ascii(key)}, arguments)) + .isEqualTo(0L); + assertThat(readFields(commands, key)).isEqualTo(expectedOpen); + + administratorCommands.del(ascii(key)); + Map newerClosed = new HashMap<>(expectedOpen); + newerClosed.put("ownerFenceEpoch", "9"); + newerClosed.put("state", "CLOSED"); + writeFields(administratorCommands, key, newerClosed); + Map beforeRefusedOpen = readFields(administratorCommands, key); + assertThat( + commands.evalsha( + sha, ScriptOutputType.INTEGER, new byte[][] {ascii(key)}, arguments)) + .isEqualTo(0L); + assertThat(readFields(administratorCommands, key)).isEqualTo(beforeRefusedOpen); + assertThat(readFields(administratorCommands, key)).containsEntry("state", "CLOSED"); + assertThat(readFields(administratorCommands, key)).containsEntry("ownerFenceEpoch", "9"); + } + } + + private static byte[][] openArguments( + UUID accountId, + UUID tenantId, + UUID namespaceId, + String gameplayTag, + UUID initializerId, + String ownerFenceEpoch) { + return new byte[][] { + ascii(SCHEMA), + ascii(accountId.toString()), + ascii(tenantId.toString()), + ascii(namespaceId.toString()), + ascii(gameplayTag), + ascii(initializerId.toString()), + ascii(ownerFenceEpoch), + ascii(INCARNATION), + ascii("OPEN") + }; + } + + private static Map readFields( + RedisCommands commands, String key) { + Map fields = new HashMap<>(); + for (Map.Entry field : commands.hgetall(ascii(key)).entrySet()) { + fields.put(asciiString(field.getKey()), asciiString(field.getValue())); + } + return Map.copyOf(fields); + } + + private static void writeFields( + RedisCommands commands, String key, Map fields) { + for (Map.Entry field : fields.entrySet()) { + commands.hset(ascii(key), ascii(field.getKey()), ascii(field.getValue())); + } + } + + private static String hexSha256(byte[] value) throws Exception { + return java.util.HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value)); + } + + private static String hexSha1(byte[] value) throws Exception { + return java.util.HexFormat.of().formatHex(MessageDigest.getInstance("SHA-1").digest(value)); + } + + private static byte[] ascii(String value) { + return value.getBytes(StandardCharsets.US_ASCII); + } + + private static String asciiString(byte[] value) { + return new String(value, StandardCharsets.US_ASCII); + } + + private static RedisClient createClient(String username, String password) { + RedisURI.Builder builder = RedisURI.Builder.redis(REDIS.getHost(), REDIS.getMappedPort(6379)); + if (username != null) builder.withAuthentication(username, password); + RedisClient client = RedisClient.create(builder.build()); + client.setOptions( + ClientOptions.builder() + .autoReconnect(false) + .protocolVersion(io.lettuce.core.protocol.ProtocolVersion.RESP2) + .build()); + return client; + } +} diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionAbortCompositionFixture.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionAbortCompositionFixture.java index 1b50107631..41e807dce1 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionAbortCompositionFixture.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionAbortCompositionFixture.java @@ -215,8 +215,11 @@ public CanonicalGameplayAdmissionAbortCompositionFixture( var partitionOwner = new CanonicalGameplayIssuerBootstrapPartitionRedisOwner( issuerRedisClient, issuerCatalog, issuerSource); - new CanonicalGameplayIssuerBootstrapCoverageOwner(dsl, partitionOwner, issuerSource) - .completeInitialBootstrap(bootstrapIntent.operationId(), bootstrapRequestId); + CanonicalGameplayIssuerInstalledAnchor installedAnchor = + new CanonicalGameplayIssuerBootstrapCoverageOwner(dsl, partitionOwner, issuerSource) + .completeInitialBootstrap(bootstrapIntent.operationId(), bootstrapRequestId); + new CanonicalGameplayIssuerAdmissionControlRepository(dsl) + .installInitialOpen(installedAnchor, issuerSource); var request = new CanonicalGameplayIssuerBindingLocalOperation.Request( UUID.randomUUID(), transitionId, identity, null, null); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepositoryIntegrationTest.java new file mode 100644 index 0000000000..bea74d18ff --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepositoryIntegrationTest.java @@ -0,0 +1,863 @@ +package net.firedevops.firemud.gamesession.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.lettuce.core.AclSetuserArgs; +import io.lettuce.core.ClientOptions; +import io.lettuce.core.RedisClient; +import io.lettuce.core.RedisURI; +import io.lettuce.core.api.StatefulRedisConnection; +import io.lettuce.core.api.sync.RedisCommands; +import io.lettuce.core.codec.ByteArrayCodec; +import io.lettuce.core.protocol.CommandKeyword; +import io.lettuce.core.protocol.CommandType; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicReference; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.Candidate; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.Target; +import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAdmissionDecision; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingIdentity; +import net.firedevops.firemud.gamesession.service.CanonicalGameplayIssuerBindingLocalRedisScriptContribution; +import net.firedevops.firemud.gamesession.service.CanonicalGameplayIssuerAdmissionBarrierRedisScriptContribution; +import net.firedevops.firemud.test.TestContainerImages; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** Focused PostgreSQL/Redis proof for the first OPEN permit, replay-only retries, and cutoff. */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class CanonicalGameplayIssuerAdmissionBarrierRepositoryIntegrationTest { + private static final String ISSUER = GameSessionAccountDelegationProfile.ISSUER; + private static final String OWNER_PRINCIPAL = "gamesession_coord_app"; + private static final BigInteger ONE = BigInteger.ONE; + + @Container + private static final PostgreSQLContainer POSTGRES = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Container + private static final GenericContainer REDIS = + new GenericContainer<>(TestContainerImages.redis()).withExposedPorts(6379); + + private RedisClient administrator; + private RedisClient ownerClient; + private StatefulRedisConnection administratorConnection; + private RedisCommands administratorCommands; + private CanonicalGameplayAdmissionAbortCompositionFixture fixture; + + @BeforeEach + void setUp() { + String password = UUID.randomUUID().toString(); + administrator = createRedisClient(null, null); + administratorConnection = administrator.connect(ByteArrayCodec.INSTANCE); + administratorCommands = administratorConnection.sync(); + administratorCommands.flushdb(); + administratorCommands.aclSetuser( + OWNER_PRINCIPAL, + new AclSetuserArgs() + .reset() + .on() + .addPassword(password) + .keyPattern("session:game:*") + .addCommand(CommandType.HELLO) + .addCommand(CommandType.PING) + .addCommand(CommandType.CLIENT, CommandKeyword.SETINFO) + .addCommand(CommandType.ACL, CommandKeyword.WHOAMI) + .addCommand(CommandType.SCRIPT, CommandKeyword.LOAD) + .addCommand(CommandType.EVALSHA) + .addCommand(CommandType.TYPE) + .addCommand(CommandType.PTTL) + .addCommand(CommandType.HGET) + .addCommand(CommandType.HLEN) + .addCommand(CommandType.HGETALL) + .addCommand(CommandType.HSET)); + ownerClient = createRedisClient(OWNER_PRINCIPAL, password); + } + + @AfterEach + void tearDown() { + if (fixture != null) fixture.close(); + if (administratorConnection != null) administratorConnection.close(); + if (ownerClient != null) ownerClient.shutdown(Duration.ZERO, Duration.ofSeconds(2)); + if (administrator != null) administrator.shutdown(Duration.ZERO, Duration.ofSeconds(2)); + } + + @Test + void firstOpenIsPersistedExactRetryIsReplayOnlyAndCutoffPreservesNewerClosedState() { + FixtureState state = fixtureState(); + UUID operationId = state.fixture().originalOperationId(); + + var first = state.owner().initializeAndRead(operationId); + assertThat(first.scriptOutcome()).isEqualTo(1L); + assertThat(initializationState(state, operationId)).isEqualTo("OPEN_CONFIRMED"); + var replay = state.owner().initializeAndRead(operationId); + assertThat(replay.scriptOutcome()).isEqualTo(2L); + assertThat(replay.exactPhysicalPayload()).containsExactly(first.exactPhysicalPayload()); + + var prepared = state.repository().readPreparedInitializer(operationId); + administratorCommands.del(bytes(prepared.key())); + assertThatThrownBy(() -> state.owner().initializeAndRead(operationId)) + .isInstanceOf(IllegalStateException.class); + + UUID cutoffOperationId = UUID.randomUUID(); + state.repository().beginCutoff(cutoffOperationId, UUID.randomUUID()); + var cutoffTargets = state.repository().readPreparedCutoffTargets(cutoffOperationId); + assertThat(cutoffTargets).hasSize(1); + var target = cutoffTargets.getFirst(); + var closed = + state.owner().closeAndRead( + cutoffOperationId, target.closedValue().tenantId(), + target.closedValue().playableStateNamespaceId()); + assertThat(closed.scriptOutcome()).isEqualTo(1L); + + var newerClosed = + CanonicalGameplayIssuerAdmissionBarrierValue.closed( + ISSUER, + target.closedValue().tenantId(), + target.closedValue().playableStateNamespaceId(), + target.closedValue().tenantGameplayTag(), + target.closedValue().admissionEpoch().add(ONE), + UUID.randomUUID(), + target.closedValue().initializer()); + writePhysicalValue(target.key(), newerClosed); + byte[] newerBytes = newerClosed.exactBytes(); + assertThatThrownBy( + () -> + state.owner().closeAndRead( + cutoffOperationId, + target.closedValue().tenantId(), + target.closedValue().playableStateNamespaceId())) + .isInstanceOf(IllegalStateException.class); + assertThat(administratorCommands.hget(bytes(target.key()), bytes("payload"))) + .containsExactly(newerBytes); + } + + @Test + void lostReceiptReplaysTheExistingOpenWithoutMintingAnotherCreatePermit() { + FixtureState state = fixtureState(); + UUID operationId = state.fixture().originalOperationId(); + AtomicBoolean loseFirstReceipt = new AtomicBoolean(true); + var delegate = state.repository(); + var lostReplyRepository = + new CanonicalGameplayIssuerAdmissionBarrierRedisOwner.ProjectionRepository() { + @Override + public CanonicalGameplayIssuerAdmissionBarrierRedisOwner.PreparedInitializer + readPreparedInitializer(UUID id) { + return delegate.readPreparedInitializer(id); + } + + @Override + public CanonicalGameplayIssuerAdmissionBarrierRedisOwner.PreparedCutoffTarget + readPreparedCutoffTarget(UUID id, UUID tenantId, UUID namespaceId) { + return delegate.readPreparedCutoffTarget(id, tenantId, namespaceId); + } + + @Override + public void requireStillCurrent( + CanonicalGameplayIssuerAdmissionBarrierRedisOwner.PreparedInitializer prepared) { + delegate.requireStillCurrent(prepared); + } + + @Override + public void requireStillCurrent( + CanonicalGameplayIssuerAdmissionBarrierRedisOwner.PreparedCutoffTarget prepared) { + delegate.requireStillCurrent(prepared); + } + + @Override + public void recordOpenReadback( + CanonicalGameplayIssuerAdmissionBarrierRedisOwner.PreparedInitializer prepared, + CanonicalGameplayIssuerAdmissionBarrierRedisOwner.Readback readback) { + if (loseFirstReceipt.getAndSet(false)) { + throw new IllegalStateException("Controlled loss after physical OPEN readback"); + } + delegate.recordOpenReadback(prepared, readback); + } + + @Override + public void recordClosedReadback( + CanonicalGameplayIssuerAdmissionBarrierRedisOwner.PreparedCutoffTarget prepared, + CanonicalGameplayIssuerAdmissionBarrierRedisOwner.Readback readback) { + delegate.recordClosedReadback(prepared, readback); + } + }; + var lostReplyOwner = state.owner(lostReplyRepository); + + assertThatThrownBy(() -> lostReplyOwner.initializeAndRead(operationId)) + .isInstanceOf(IllegalStateException.class); + assertThat(initializationState(state, operationId)).isEqualTo("INITIALIZING"); + assertThat(countReceipt(state, operationId)).isZero(); + + var replay = state.owner().initializeAndRead(operationId); + assertThat(replay.scriptOutcome()).isEqualTo(2L); + assertThat(initializationState(state, operationId)).isEqualTo("OPEN_CONFIRMED"); + assertThat(countReceipt(state, operationId)).isEqualTo(1L); + } + + @Test + void missingOpenAfterUncertainFirstAttemptIsNeverRecreated() { + FixtureState state = fixtureState(); + UUID operationId = state.fixture().originalOperationId(); + AtomicBoolean loseFirstReceipt = new AtomicBoolean(true); + var delegate = state.repository(); + var lostReplyRepository = + new CanonicalGameplayIssuerAdmissionBarrierRedisOwner.ProjectionRepository() { + @Override + public CanonicalGameplayIssuerAdmissionBarrierRedisOwner.PreparedInitializer + readPreparedInitializer(UUID id) { + return delegate.readPreparedInitializer(id); + } + + @Override + public CanonicalGameplayIssuerAdmissionBarrierRedisOwner.PreparedCutoffTarget + readPreparedCutoffTarget(UUID id, UUID tenantId, UUID namespaceId) { + return delegate.readPreparedCutoffTarget(id, tenantId, namespaceId); + } + + @Override + public void requireStillCurrent( + CanonicalGameplayIssuerAdmissionBarrierRedisOwner.PreparedInitializer prepared) { + delegate.requireStillCurrent(prepared); + } + + @Override + public void requireStillCurrent( + CanonicalGameplayIssuerAdmissionBarrierRedisOwner.PreparedCutoffTarget prepared) { + delegate.requireStillCurrent(prepared); + } + + @Override + public void recordOpenReadback( + CanonicalGameplayIssuerAdmissionBarrierRedisOwner.PreparedInitializer prepared, + CanonicalGameplayIssuerAdmissionBarrierRedisOwner.Readback readback) { + if (loseFirstReceipt.getAndSet(false)) { + throw new IllegalStateException("Controlled loss after physical OPEN readback"); + } + delegate.recordOpenReadback(prepared, readback); + } + + @Override + public void recordClosedReadback( + CanonicalGameplayIssuerAdmissionBarrierRedisOwner.PreparedCutoffTarget prepared, + CanonicalGameplayIssuerAdmissionBarrierRedisOwner.Readback readback) { + delegate.recordClosedReadback(prepared, readback); + } + }; + assertThatThrownBy(() -> state.owner(lostReplyRepository).initializeAndRead(operationId)) + .isInstanceOf(IllegalStateException.class); + + var prepared = state.repository().readPreparedInitializer(operationId); + administratorCommands.del(bytes(prepared.key())); + assertThatThrownBy(() -> state.owner().initializeAndRead(operationId)) + .isInstanceOf(IllegalStateException.class); + assertThat(initializationState(state, operationId)).isEqualTo("INITIALIZING"); + assertThat(countReceipt(state, operationId)).isZero(); + assertThat(administratorCommands.exists(bytes(prepared.key()))).isZero(); + } + + @Test + void cutoffCapturesAnInitializerWhoseCreatePermitWasClaimedButNotYetAttempted() throws Exception { + FixtureState state = fixtureState(); + UUID operationId = state.fixture().originalOperationId(); + UUID cutoffOperationId = UUID.randomUUID(); + CountDownLatch preparedForRedis = new CountDownLatch(1); + CountDownLatch allowRedisOwnerToContinue = new CountDownLatch(1); + AtomicReference + observedInitializer = new AtomicReference<>(); + var delegate = state.repository(); + var gatedRepository = + new CanonicalGameplayIssuerAdmissionBarrierRedisOwner.ProjectionRepository() { + @Override + public CanonicalGameplayIssuerAdmissionBarrierRedisOwner.PreparedInitializer + readPreparedInitializer(UUID id) { + var prepared = delegate.readPreparedInitializer(id); + observedInitializer.set(prepared); + preparedForRedis.countDown(); + try { + if (!allowRedisOwnerToContinue.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("Controlled initializer gate timed out"); + } + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("Controlled initializer gate was interrupted", interrupted); + } + return prepared; + } + + @Override + public CanonicalGameplayIssuerAdmissionBarrierRedisOwner.PreparedCutoffTarget + readPreparedCutoffTarget(UUID id, UUID tenantId, UUID namespaceId) { + return delegate.readPreparedCutoffTarget(id, tenantId, namespaceId); + } + + @Override + public void requireStillCurrent( + CanonicalGameplayIssuerAdmissionBarrierRedisOwner.PreparedInitializer prepared) { + delegate.requireStillCurrent(prepared); + } + + @Override + public void requireStillCurrent( + CanonicalGameplayIssuerAdmissionBarrierRedisOwner.PreparedCutoffTarget prepared) { + delegate.requireStillCurrent(prepared); + } + + @Override + public void recordOpenReadback( + CanonicalGameplayIssuerAdmissionBarrierRedisOwner.PreparedInitializer prepared, + CanonicalGameplayIssuerAdmissionBarrierRedisOwner.Readback readback) { + delegate.recordOpenReadback(prepared, readback); + } + + @Override + public void recordClosedReadback( + CanonicalGameplayIssuerAdmissionBarrierRedisOwner.PreparedCutoffTarget prepared, + CanonicalGameplayIssuerAdmissionBarrierRedisOwner.Readback readback) { + delegate.recordClosedReadback(prepared, readback); + } + }; + ExecutorService executor = Executors.newSingleThreadExecutor(); + try { + var initializerAttempt = + executor.submit( + () -> state.owner(gatedRepository).initializeAndRead(operationId)); + assertThat(preparedForRedis.await(10, TimeUnit.SECONDS)).isTrue(); + assertThat(initializationState(state, operationId)).isEqualTo("INITIALIZING"); + + state.repository().beginCutoff(cutoffOperationId, UUID.randomUUID()); + allowRedisOwnerToContinue.countDown(); + assertThatThrownBy(() -> initializerAttempt.get(10, TimeUnit.SECONDS)) + .isInstanceOf(ExecutionException.class) + .hasCauseInstanceOf(IllegalStateException.class); + assertThat(administratorCommands.exists(bytes(observedInitializer.get().key()))).isZero(); + + var targets = state.repository().readPreparedCutoffTargets(cutoffOperationId); + assertThat(targets).hasSize(1); + var closed = + state.owner().closeAndRead( + cutoffOperationId, + targets.getFirst().closedValue().tenantId(), + targets.getFirst().closedValue().playableStateNamespaceId()); + assertThat(closed.scriptOutcome()).isEqualTo(1L); + assertThat(countReceipt(state, operationId)).isZero(); + } finally { + allowRedisOwnerToContinue.countDown(); + executor.shutdownNow(); + } + } + + @Test + void cutoffClosesAnAbortedOriginTargetAndRetainsItsFrozenInitializer() { + FixtureState state = fixtureState(); + UUID originalOperationId = state.fixture().originalOperationId(); + var opened = state.owner().initializeAndRead(originalOperationId); + + new CanonicalGameplayBindingInventoryRepository(state.fixture().dsl()) + .recordFirstNewAccountAbort(state.fixture().source(), UUID.randomUUID()); + assertThat( + state.fixture().dsl() + .fetchOne( + "SELECT status FROM game_session_canonical_binding_transition" + + " WHERE transition_id = ?", + state.fixture().transitionId()) + .get("status", String.class)) + .isEqualTo("ABORTED"); + + UUID cutoffOperationId = UUID.randomUUID(); + state.repository().beginCutoff(cutoffOperationId, UUID.randomUUID()); + var targets = state.repository().readPreparedCutoffTargets(cutoffOperationId); + assertThat(targets).hasSize(1); + var target = targets.getFirst(); + assertThat(target.expectedOpenValue()).isNotNull(); + assertThat(target.expectedOpenValue().exactBytes()).containsExactly(opened.exactPhysicalPayload()); + assertThat(target.closedValue().initializer().exactBytes()) + .containsExactly(opened.value().initializer().exactBytes()); + + var closed = + state.owner().closeAndRead( + cutoffOperationId, + target.closedValue().tenantId(), + target.closedValue().playableStateNamespaceId()); + assertThat(closed.scriptOutcome()).isEqualTo(1L); + var installed = state.repository().completeCutoff(cutoffOperationId); + assertThat(installed.state()) + .isEqualTo(CanonicalGameplayIssuerAdmissionControlValue.State.INSTALLED); + + var frozenInitializer = + state.fixture().dsl() + .fetchOne( + "SELECT operation_id, open_payload_bytes FROM" + + " game_session_canonical_issuer_admission_initializer" + + " WHERE operation_id = ?", + originalOperationId); + assertThat(frozenInitializer.get("operation_id", UUID.class)).isEqualTo(originalOperationId); + assertThat(frozenInitializer.get("open_payload_bytes", byte[].class)) + .containsExactly(opened.exactPhysicalPayload()); + assertThatThrownBy(() -> state.owner().initializeAndRead(originalOperationId)) + .isInstanceOf(IllegalStateException.class); + assertThat(administratorCommands.hget(bytes(target.key()), bytes("payload"))) + .containsExactly(closed.exactPhysicalPayload()); + } + + @Test + void reusesFrozenTargetInitializerAcrossOperationsRevisionProgressAndOriginAbort() { + FixtureState state = fixtureState(); + UUID originalOperationId = state.fixture().originalOperationId(); + var opened = state.owner().initializeAndRead(originalOperationId); + byte[] originalPayload = opened.exactPhysicalPayload(); + UUID secondAccountId = UUID.randomUUID(); + assertThat(secondAccountId).isNotEqualTo(state.candidate().accountId()); + + CanonicalGameplayIssuerBindingLocalOperation currentOperation = + prepareCurrentOperation( + state, "same-target-different-account", secondAccountId); + var originalRetry = state.owner().initializeAndRead(originalOperationId); + assertThat(originalRetry.scriptOutcome()).isEqualTo(2L); + assertThat(originalRetry.exactPhysicalPayload()).containsExactly(originalPayload); + + var abortSource = state.fixture().source(); + new CanonicalGameplayBindingInventoryRepository(state.fixture().dsl()) + .recordFirstNewAccountAbort(abortSource, UUID.randomUUID()); + assertThat( + state.fixture().dsl() + .fetchOne( + "SELECT status FROM game_session_canonical_binding_transition" + + " WHERE transition_id = ?", + state.fixture().transitionId()) + .get("status", String.class)) + .isEqualTo("ABORTED"); + + var abortedOriginRetry = state.owner().initializeAndRead(originalOperationId); + assertThat(abortedOriginRetry.scriptOutcome()).isEqualTo(2L); + assertThat(abortedOriginRetry.exactPhysicalPayload()).containsExactly(originalPayload); + + var currentCandidateReadback = + state.owner().initializeAndRead(currentOperation.operationId()); + assertThat(currentCandidateReadback.scriptOutcome()).isEqualTo(2L); + assertThat(currentCandidateReadback.exactPhysicalPayload()).containsExactly(originalPayload); + + var storedInitializer = + state.fixture().dsl() + .fetchOne( + "SELECT operation_id, open_payload_bytes FROM" + + " game_session_canonical_issuer_admission_initializer" + + " WHERE tenant_id = ? AND playable_state_namespace_id = ?", + state.candidate().tenantId(), + state.candidate().playableStateNamespaceId()); + assertThat(storedInitializer.get("operation_id", UUID.class)).isEqualTo(originalOperationId); + assertThat(storedInitializer.get("open_payload_bytes", byte[].class)) + .containsExactly(originalPayload); + + state.currentState().set(currentIssuerState(state.candidate(), "moved-source")); + assertThatThrownBy( + () -> state.owner().initializeAndRead(currentOperation.operationId())) + .isInstanceOf(IllegalStateException.class); + + state.currentState().set(currentIssuerState(state.candidate())); + var prepared = state.repository().readPreparedInitializer(currentOperation.operationId()); + administratorCommands.del(bytes(prepared.key())); + assertThatThrownBy( + () -> state.owner().initializeAndRead(currentOperation.operationId())) + .isInstanceOf(IllegalStateException.class); + assertThat(administratorCommands.exists(bytes(prepared.key()))).isZero(); + } + + @Test + void callerOwnedJooqTransactionRefusesBeforeSourceOrRemoteDispatch() { + FixtureState state = fixtureState(); + var dsl = state.fixture().dsl(); + var current = state.currentState().get(); + var anchor = dsl.transactionResult(configuration -> { + var transaction = org.jooq.impl.DSL.using(configuration); + CanonicalGameplayBindingInventoryRepository.lockInventoryRevision(transaction); + return CanonicalGameplayIssuerBootstrapCoverageRepository + .readInstalledAnchorForBindingPreparationInTransaction(transaction, current); + }); + AtomicBoolean sourceCalled = new AtomicBoolean(); + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerStateSource source = () -> { + sourceCalled.set(true); + return current; + }; + dsl.transaction(configuration -> { + var transaction = org.jooq.impl.DSL.using(configuration); + var repository = new CanonicalGameplayIssuerAdmissionBarrierRepository( + transaction, + new CanonicalGameplayTenantGameplayTagRepository( + transaction, state.fixture().target().targetNamespace(), 1), + source); + assertThatThrownBy(() -> repository.readPreparedInitializer(state.fixture().originalOperationId())) + .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) + .hasMessageContaining("jOOQ transaction"); + assertThatThrownBy(() -> new CanonicalGameplayIssuerAdmissionControlRepository(transaction) + .installInitialOpen(anchor, source)) + .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) + .hasMessageContaining("jOOQ transaction"); + }); + assertThat(sourceCalled).isFalse(); + assertThat(dsl.fetchCount(org.jooq.impl.DSL.table( + "game_session_canonical_issuer_admission_initializer"))).isZero(); + } + + private FixtureState fixtureState() { + Candidate candidate = candidate(); + DriverManagerDataSource accountDataSource = new DriverManagerDataSource(); + accountDataSource.setDriverClassName("org.postgresql.Driver"); + String jdbcUrl = POSTGRES.getJdbcUrl(); + accountDataSource.setUrl( + jdbcUrl + (jdbcUrl.contains("?") ? "&" : "?") + "currentSchema=public"); + accountDataSource.setUsername(POSTGRES.getUsername()); + accountDataSource.setPassword(POSTGRES.getPassword()); + fixture = + new CanonicalGameplayAdmissionAbortCompositionFixture( + accountDataSource, candidate, ownerClient); + Candidate actualCandidate = fixture.candidate(); + CanonicalGameplayBindingIdentity identity = identity(actualCandidate); + fixture.publish(controlledLeaseEvidence(identity, fixture.generation(), fixture.target())); + var currentState = new AtomicReference<>(currentIssuerState(actualCandidate)); + var sourceReader = + (CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerStateSource) + currentState::get; + var repository = + new CanonicalGameplayIssuerAdmissionBarrierRepository( + fixture.dsl(), + new CanonicalGameplayTenantGameplayTagRepository( + fixture.dsl(), fixture.target().targetNamespace(), 1), + sourceReader); + return new FixtureState( + fixture, + actualCandidate, + repository, + new CanonicalGameplayIssuerAdmissionBarrierRedisOwner( + ownerClient, + RedisScriptCatalog.fromContributions( + List.of(new CanonicalGameplayIssuerAdmissionBarrierRedisScriptContribution())), + repository, + sourceReader), + ownerClient, + currentState); + } + + private CanonicalGameplayIssuerBindingLocalOperation prepareCurrentOperation( + FixtureState state, String seed) { + return prepareCurrentOperation(state, seed, state.candidate().accountId()); + } + + private CanonicalGameplayIssuerBindingLocalOperation prepareCurrentOperation( + FixtureState state, String seed, UUID accountId) { + Candidate candidate = state.candidate(); + CanonicalGameplayBindingIdentity identity = + new CanonicalGameplayBindingIdentity( + accountId, + candidate.tenantId(), + candidate.playableStateNamespaceId(), + UUID.randomUUID(), + candidate.playableStateScope(), + candidate.gameInstanceId(), + candidate.runtimeGameInstanceId(), + UUID.randomUUID().toString(), + candidate.regionId(), + candidate.regionEpoch(), + candidate.issuerId(), + candidate.issuerAuthGeneration(), + candidate.issuerIndexLayoutVersion(), + candidate.issuerIndexPartitionCount(), + candidate.issuerIndexPartitionCapacity()); + UUID transitionId = UUID.randomUUID(); + var request = + new CanonicalGameplayIssuerBindingLocalOperation.Request( + UUID.randomUUID(), transitionId, identity, null, null); + var operation = + new CanonicalGameplayIssuerBindingLocalOperationRepository( + state.fixture().dsl(), state.sourceReader()) + .beginOrResumeOrdinaryNew(request); + var inventory = new CanonicalGameplayBindingInventoryRepository(state.fixture().dsl()); + var provisionalEvidence = inventory.readProvisionalCasEvidence(transitionId); + var lease = + controlledLeaseEvidence( + identity, operation.preparedTransition().bindingGeneration(), state.fixture().target()); + inventory.markProvisional( + provisionalEvidence, + new CanonicalGameplayAdmissionDecision( + transitionId, + lease, + identity, + operation.preparedTransition().bindingGeneration(), + null, + state.fixture().target())); + var localCatalog = + RedisScriptCatalog.fromContributions( + List.of(new CanonicalGameplayIssuerBindingLocalRedisScriptContribution())); + var localProjection = + new CanonicalGameplayIssuerBindingLocalProjectionRepository( + state.fixture().dsl(), state.sourceReader()); + new CanonicalGameplayIssuerBindingLocalRedisOwner( + ownerClient, localCatalog, localProjection, state.sourceReader()) + .projectAndRead(operation); + return operation; + } + + private static Candidate candidate() { + return new Candidate( + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + "controlled-scope", + UUID.randomUUID(), + 1L, + UUID.randomUUID(), + UUID.randomUUID(), + ONE, + ISSUER, + ONE, + BigInteger.valueOf(3), + ONE, + BigInteger.valueOf(2)); + } + + private static CanonicalGameplayBindingIdentity identity(Candidate candidate) { + return new CanonicalGameplayBindingIdentity( + candidate.accountId(), + candidate.tenantId(), + candidate.playableStateNamespaceId(), + candidate.characterId(), + candidate.playableStateScope(), + candidate.gameInstanceId(), + candidate.runtimeGameInstanceId(), + candidate.sessionId().toString(), + candidate.regionId(), + candidate.regionEpoch(), + candidate.issuerId(), + candidate.issuerAuthGeneration(), + candidate.issuerIndexLayoutVersion(), + candidate.issuerIndexPartitionCount(), + candidate.issuerIndexPartitionCapacity()); + } + + private static CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState + currentIssuerState(Candidate candidate) { + return currentIssuerState(candidate, "controlled-release-composition"); + } + + private static CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState + currentIssuerState(Candidate candidate, String seed) { + byte[] checkpoint = + ("controlled-initial-issuer-checkpoint/v1|" + candidate.issuerId() + "|1") + .getBytes(StandardCharsets.UTF_8); + var sourceCheckpoint = + new CanonicalGameplayIssuerLayoutBootstrapIntent.AccountIssuerSourceCheckpoint( + candidate.issuerId(), + candidate.issuerAuthGeneration(), + checkpoint, + CanonicalGameplayIssuerMemberV2Codec.sha256(checkpoint), + null, + null); + String digest = + CanonicalGameplayIssuerMemberV2Codec.sha256(seed.getBytes(StandardCharsets.UTF_8)); + var deployment = + new CanonicalGameplayProtectedIncarnationReceiver.ExpectedTargetDeploymentEvidence( + "controlled-release-deployment-" + seed, + "controlled-release-generation-" + seed, + List.of("controlled-release-node-" + seed), + "controlled-release-redis-build-" + seed, + "controlled-release-registry-" + seed, + digest, + "READY", + "controlled-release-boot-" + seed, + "controlled-release-startup-" + seed, + "controlled-release-storage-" + seed, + "controlled-release-aof-" + seed); + var incarnation = + new CanonicalGameplayIssuerMemberV2Value.Incarnation( + "controlled-release-attestor-" + seed, digest, deployment, digest, digest); + return new CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState( + sourceCheckpoint, incarnation); + } + + private static AccountGameplayAdmissionLeaseEvidence controlledLeaseEvidence( + CanonicalGameplayBindingIdentity candidate, BigInteger bindingGeneration, Target target) { + long now = System.currentTimeMillis(); + String nowSeconds = Long.toString(now / 1000L); + Map carrier = new LinkedHashMap<>(); + carrier.put("schema", AccountGameplayAdmissionLeaseEvidence.SCHEMA); + carrier.put("schemaVersion", "1"); + carrier.put("mode", "PUBLIC_PRODUCTION"); + carrier.put("leaseKind", AccountGameplayAdmissionLeaseEvidence.LeaseKind.NEW_BINDING.name()); + carrier.put("targetNamespace", target.targetNamespace()); + carrier.put( + "callerWorkload", + "spiffe://firemud/ns/" + target.targetNamespace() + "/sa/game-session-service"); + carrier.put("requestId", UUID.randomUUID().toString()); + carrier.put("leaseId", UUID.randomUUID().toString()); + carrier.put("leaseFence", "1"); + Map scope = new LinkedHashMap<>(); + scope.put("accountId", candidate.accountId().toString()); + scope.put("tenantId", candidate.tenantId().toString()); + scope.put("realmId", target.realmId().toString()); + scope.put("worldSlug", target.worldSlug()); + scope.put("realmSlug", target.realmSlug()); + scope.put("playableStateNamespaceId", target.playableStateNamespaceId().toString()); + scope.put("playableStateScope", target.playableStateScope()); + scope.put("gameInstanceId", target.canonicalGameInstanceId().toString()); + scope.put("characterId", candidate.characterId().toString()); + scope.put("sessionId", candidate.sessionId().toString()); + scope.put("bindingGeneration", bindingGeneration.toString()); + scope.put("catalogRevision", Long.toString(target.catalogRevision())); + scope.put("pointerVersion", Long.toString(target.pointerVersion())); + scope.put("regionId", candidate.regionId().toString()); + scope.put("regionEpoch", candidate.regionEpoch().toString()); + carrier.put("bindingScope", scope); + Map authority = new LinkedHashMap<>(); + authority.put("issuerAuthGeneration", candidate.issuerAuthGeneration().toString()); + authority.put("accountAuthorityGeneration", "1"); + authority.put("tenantAuthorityGeneration", Map.of(candidate.tenantId().toString(), "1")); + authority.put("membershipAuthorityGeneration", Map.of(candidate.tenantId().toString(), "1")); + authority.put("privateRealmGrantVersions", List.of()); + carrier.put("authorityTuple", authority); + carrier.put("issuanceFence", "1"); + carrier.put( + "membershipBaseline", + new LinkedHashMap<>( + Map.of( + "membershipLifecycleState", "ACTIVE", + "membershipVersion", Map.of(candidate.tenantId().toString(), "1"), + "membershipAuthorityGeneration", "1"))); + String prefix = "account:auth-authority:v1:"; + carrier.put( + "outboxCheckpoints", + List.of( + checkpoint(prefix + "account/" + candidate.accountId(), "0"), + checkpoint(prefix + "issuer/" + ISSUER, "0"), + checkpoint( + prefix + "membership/" + candidate.accountId() + "/" + candidate.tenantId(), "1"), + checkpoint(prefix + "tenant/" + candidate.tenantId(), "1"))); + Map tokenIdentity = new LinkedHashMap<>(); + tokenIdentity.put("accountId", candidate.accountId().toString()); + tokenIdentity.put("operationId", UUID.randomUUID().toString()); + tokenIdentity.put("issuanceRequestId", UUID.randomUUID().toString()); + tokenIdentity.put("tokenJti", UUID.randomUUID().toString()); + tokenIdentity.put("tokenSHA256", "a".repeat(64)); + tokenIdentity.put("tokenProfile", "game-session-account-delegation"); + tokenIdentity.put("tokenGeneration", "1"); + tokenIdentity.put("issuanceFence", "1"); + tokenIdentity.put("tokenIdentityFence", "1"); + tokenIdentity.put("issuedAt", nowSeconds); + tokenIdentity.put("notBefore", nowSeconds); + tokenIdentity.put("expiresAt", Long.toString(now / 1000L + 60L)); + carrier.put("tokenIdentityEvidence", tokenIdentity); + carrier.put("evaluatedAt", Long.toString(now)); + carrier.put( + "expiresAt", + Long.toString(now + AccountGameplayAdmissionLeaseEvidence.MAX_DURATION_MILLIS)); + return AccountGameplayAdmissionLeaseEvidence.fromCarrier(carrier); + } + + private static Map checkpoint(String key, String sequence) { + return new LinkedHashMap<>(Map.of("outboxStreamKey", key, "outboxSequence", sequence)); + } + + private static String initializationState(FixtureState state, UUID operationId) { + return state.fixture().dsl() + .fetchOne( + "SELECT initialization_state FROM game_session_canonical_issuer_admission_initializer" + + " WHERE operation_id = ?", + operationId) + .get("initialization_state", String.class); + } + + private static long countReceipt(FixtureState state, UUID operationId) { + return state.fixture().dsl() + .fetchOne( + "SELECT count(*) AS receipt_count" + + " FROM game_session_canonical_issuer_admission_initializer_receipt" + + " WHERE operation_id = ?", + operationId) + .get("receipt_count", Long.class); + } + + private void writePhysicalValue( + String key, CanonicalGameplayIssuerAdmissionBarrierValue value) { + var initializer = value.initializer(); + Map fields = new LinkedHashMap<>(); + fields.put("schema", CanonicalGameplayIssuerAdmissionBarrierValue.SCHEMA); + fields.put("issuerId", value.issuerId()); + fields.put("tenantId", value.tenantId().toString()); + fields.put("playableStateNamespaceId", value.playableStateNamespaceId().toString()); + fields.put("tenantGameplayTag", value.tenantGameplayTag()); + fields.put("state", value.state().name()); + fields.put("admissionEpoch", value.admissionEpoch().toString()); + fields.put("ownerOperationId", value.ownerOperationId().toString()); + fields.put("initializerOperationId", initializer == null ? "none" : initializer.operationId().toString()); + fields.put("initializerEpoch", initializer == null ? "0" : initializer.admissionEpoch().toString()); + fields.put("initializerDigest", initializer == null ? "none" : initializer.exactDigest()); + fields.put("payloadDigest", value.exactDigest()); + for (Map.Entry field : fields.entrySet()) { + administratorCommands.hset(bytes(key), bytes(field.getKey()), bytes(field.getValue())); + } + administratorCommands.hset(bytes(key), bytes("payload"), value.exactBytes()); + } + + private static RedisClient createRedisClient(String username, String password) { + RedisURI.Builder builder = RedisURI.Builder.redis(REDIS.getHost(), REDIS.getMappedPort(6379)); + if (username != null) builder.withAuthentication(username, password); + RedisURI uri = builder.build(); + uri.setTimeout(Duration.ofSeconds(5)); + RedisClient client = RedisClient.create(uri); + client.setOptions( + ClientOptions.builder() + .autoReconnect(false) + .protocolVersion(io.lettuce.core.protocol.ProtocolVersion.RESP2) + .build()); + return client; + } + + private static byte[] bytes(String value) { + return value.getBytes(StandardCharsets.US_ASCII); + } + + private record FixtureState( + CanonicalGameplayAdmissionAbortCompositionFixture fixture, + Candidate candidate, + CanonicalGameplayIssuerAdmissionBarrierRepository repository, + CanonicalGameplayIssuerAdmissionBarrierRedisOwner owner, + RedisClient ownerClient, + AtomicReference + currentState) { + private CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerStateSource + sourceReader() { + return currentState::get; + } + + private CanonicalGameplayIssuerAdmissionBarrierRedisOwner owner( + CanonicalGameplayIssuerAdmissionBarrierRedisOwner.ProjectionRepository projectionRepository) { + return new CanonicalGameplayIssuerAdmissionBarrierRedisOwner( + ownerClient, + RedisScriptCatalog.fromContributions( + List.of(new CanonicalGameplayIssuerAdmissionBarrierRedisScriptContribution())), + projectionRepository, + sourceReader()); + } + } +} diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalOperationRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalOperationRepositoryIntegrationTest.java index bdc5c5792c..270e43a101 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalOperationRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalOperationRepositoryIntegrationTest.java @@ -149,6 +149,12 @@ void registersOrdinaryNewAgainstInstalledAnchorAndReusesExactPendingOperation() CanonicalGameplayIssuerInstalledAnchor anchor = initialCoverageOwner(dsl, currentState::get) .completeInitialBootstrap(intent.operationId(), bootstrapRequestId); + assertThatThrownBy(() -> operationRepository.beginOrResumeOrdinaryNew(firstRequest)) + .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) + .hasMessageContaining("positive live admission-control row"); + assertThat(count(dsl, "game_session_canonical_issuer_binding_local_operation")).isZero(); + new CanonicalGameplayIssuerAdmissionControlRepository(dsl) + .installInitialOpen(anchor, currentState::get); String installedAnchorImage = anchorImage(dsl); String installedProofImage = proofImage(dsl); String initialReservationImage = reservationImage(dsl); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java index 3dd65d7ebb..95c8d1d6b5 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java @@ -171,6 +171,8 @@ void projectsOrdinaryNewAgainstInstalledAnchorAndReusesExactPendingOperation() t CanonicalGameplayIssuerInstalledAnchor anchor = initialCoverageOwner(dsl, currentState::get) .completeInitialBootstrap(intent.operationId(), bootstrapRequestId); + new CanonicalGameplayIssuerAdmissionControlRepository(dsl) + .installInitialOpen(anchor, currentState::get); String installedAnchorImage = anchorImage(dsl); String installedProofImage = proofImage(dsl); String initialReservationImage = reservationImage(dsl); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayProtectedIncarnationReceiverPostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayProtectedIncarnationReceiverPostgresIntegrationTest.java index 15c90f3a9a..bb4e781b5f 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayProtectedIncarnationReceiverPostgresIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayProtectedIncarnationReceiverPostgresIntegrationTest.java @@ -2,7 +2,10 @@ 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.when; +import com.google.protobuf.ByteString; import java.math.BigInteger; import java.nio.ByteBuffer; import java.nio.file.Path; @@ -22,6 +25,8 @@ import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingIdentity; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingTransitionRequest; import net.firedevops.firemud.gamesession.binding.CanonicalIssuerReservationFenceEvidence; +import net.firedevops.firemud.gamesession.dto.CanonicalGameplayLoginResult; +import net.firedevops.firemud.gamesession.dto.InitialGameplayLoginAttemptCoordinates; import net.firedevops.firemud.test.TestContainerImages; import org.flywaydb.core.Flyway; import org.jooq.DSLContext; @@ -210,11 +215,66 @@ void changedCurrentSqlContextAfterSourceCallCannotProduceVerifiedEvidence() thro } } + @Test + void initialArmVerifiesExactOriginalAndNonzeroNoActiveEpochWithSameTrustedVerifier() + throws Exception { + try (InitialFixture fixture = InitialFixture.open()) { + ControlledSigner channel = new ControlledSigner(fixture.keyPair()); + var receiver = fixture.receiver(channel); + + var verified = receiver.observeForInitialAccountBarrier(fixture.original().requestId()); + + assertThat(verified.ownerKind()) + .isEqualTo( + CanonicalGameplayProtectedIncarnationReceiver.OwnerKind.INITIAL_ACCOUNT_BARRIER); + assertThat(verified.requestId()).isEqualTo(fixture.original().requestId()); + assertThat(verified.originalCallerContextId()).isEqualTo(fixture.original().callerContextId()); + assertThat(verified.originalAttemptFence()).isEqualTo(17L); + assertThat(verified.accountId()).isEqualTo(fixture.accountId()); + assertThat(verified.sourceControlState()).isEqualTo("NO_ACTIVE_ACCOUNT_WIDE_FLOW"); + assertThat(verified.sourceControlEpoch()).isEqualTo("8"); + assertThat(verified.acceptedAttestationDigest()).isEqualTo(ACCEPTED_ATTESTATION_DIGEST); + assertThat(verified.evidence()).isEqualTo(fixture.expectedEvidence()); + + var repeated = receiver.observeForInitialAccountBarrier(fixture.original().requestId()); + assertThat(repeated.observationNonce()).isNotEqualTo(verified.observationNonce()); + assertThat(repeated.incarnationDigest()).isEqualTo(verified.incarnationDigest()); + + for (Mutation mutation : List.of(Mutation.WRONG_INITIAL_SOURCE_EPOCH, Mutation.WRONG_INITIAL_ATTEMPT)) { + assertThatThrownBy( + () -> + fixture + .receiver(new ControlledSigner(fixture.keyPair(), mutation, null)) + .observeForInitialAccountBarrier(fixture.original().requestId())) + .isInstanceOf( + CanonicalGameplayProtectedIncarnationReceiver.ObservationRejectedException.class); + } + } + } + + @Test + void changedNoActiveEpochAfterInitialObservationCannotProduceVerifiedEvidence() throws Exception { + try (InitialFixture fixture = InitialFixture.open()) { + ControlledSigner channel = + new ControlledSigner(fixture.keyPair(), Mutation.NONE, fixture.dsl()); + + assertThatThrownBy( + () -> + fixture + .receiver(channel) + .observeForInitialAccountBarrier(fixture.original().requestId())) + .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class); + assertThat(channel.lastSigned()).isNotNull(); + } + } + private enum Mutation { NONE, WRONG_NONCE, WRONG_OPERATION_ID, WRONG_OPERATION_FENCE, + WRONG_INITIAL_SOURCE_EPOCH, + WRONG_INITIAL_ATTEMPT, WRONG_STORAGE_GENERATION, FOREIGN_ACCOUNT, FOREIGN_TENANT, @@ -251,18 +311,43 @@ private ControlledSigner(KeyPair keyPair, Mutation mutation, DSLContext contextM public CanonicalGameplayProtectedIncarnationReceiver.SignedObservation observe( CanonicalGameplayProtectedIncarnationReceiver.ObservationRequest request) { if (contextMutationDsl != null) { - contextMutationDsl.execute( - "UPDATE game_session_canonical_account_admission_fence_intent" - + " SET cohort_digest = ? WHERE operation_id = ?", - "sha256:" + "f".repeat(64), - request.context().operationId()); + if (request.context().ownerKind() + == CanonicalGameplayProtectedIncarnationReceiver.OwnerKind.INITIAL_ACCOUNT_BARRIER) { + contextMutationDsl.execute( + "UPDATE game_session_canonical_account_coverage_control" + + " SET last_operation_fence = 9 WHERE account_id = ?", + request.context().accountId()); + } else { + contextMutationDsl.execute( + "UPDATE game_session_canonical_account_admission_fence_intent" + + " SET cohort_digest = ? WHERE operation_id = ?", + "sha256:" + "f".repeat(64), + request.context().operationId()); + } } Map root = payload(request); switch (mutation) { case WRONG_NONCE -> root.put("observationNonce", "A".repeat(43)); - case WRONG_OPERATION_ID -> - asMap(root.get("owner")).put("operationId", UUID.randomUUID().toString()); - case WRONG_OPERATION_FENCE -> asMap(root.get("owner")).put("operationFence", "999999"); + case WRONG_OPERATION_ID -> { + String field = + request.context().ownerKind() + == CanonicalGameplayProtectedIncarnationReceiver.OwnerKind.INITIAL_ACCOUNT_BARRIER + ? "initializerId" + : "operationId"; + asMap(root.get("owner")).put(field, UUID.randomUUID().toString()); + } + case WRONG_OPERATION_FENCE -> { + String field = + request.context().ownerKind() + == CanonicalGameplayProtectedIncarnationReceiver.OwnerKind.INITIAL_ACCOUNT_BARRIER + ? "sourceControlEpoch" + : "operationFence"; + asMap(root.get("owner")).put(field, "999999"); + } + case WRONG_INITIAL_SOURCE_EPOCH -> + asMap(root.get("owner")).put("sourceControlEpoch", "9"); + case WRONG_INITIAL_ATTEMPT -> + asMap(root.get("owner")).put("originalAttemptFence", 18L); case WRONG_STORAGE_GENERATION -> asMap(root.get("targetDeploymentEvidence")) .put("storageGeneration", "storage-untrusted-response"); @@ -332,14 +417,32 @@ private static Map payload( var context = request.context(); var evidence = request.expectedEvidence(); Map owner = new LinkedHashMap<>(); - owner.put("operationId", context.operationId().toString()); - owner.put("requestId", context.requestId().toString()); - owner.put("accountId", context.accountId().toString()); - owner.put("operationFence", context.operationFence()); - owner.put("plannedAccountAdmissionFence", context.plannedAccountAdmissionFence().toString()); - owner.put("inventorySnapshotRevision", context.inventorySnapshotRevision()); - owner.put("cohortDigest", context.cohortDigest()); - owner.put("barrierTargetDigest", context.barrierTargetDigest()); + boolean initial = + context.ownerKind() + == CanonicalGameplayProtectedIncarnationReceiver.OwnerKind.INITIAL_ACCOUNT_BARRIER; + if (initial) { + owner.put("ownerKind", context.ownerKind().name()); + owner.put("initializerId", context.operationId().toString()); + owner.put("originalRequestId", context.requestId().toString()); + owner.put("originalCallerContextId", context.originalCallerContextId().toString()); + owner.put("originalAttemptFence", context.originalAttemptFence()); + owner.put("accountId", context.accountId().toString()); + owner.put("sourceControlState", context.sourceControlState()); + owner.put("sourceControlEpoch", context.sourceControlEpoch()); + owner.put("inventorySnapshotRevision", context.inventorySnapshotRevision()); + owner.put("accountLoginEvidenceDigest", context.accountLoginEvidenceDigest()); + owner.put("sourceControlDigest", context.sourceControlDigest()); + owner.put("targetDigest", context.barrierTargetDigest()); + } else { + owner.put("operationId", context.operationId().toString()); + owner.put("requestId", context.requestId().toString()); + owner.put("accountId", context.accountId().toString()); + owner.put("operationFence", context.operationFence()); + owner.put("plannedAccountAdmissionFence", context.plannedAccountAdmissionFence().toString()); + owner.put("inventorySnapshotRevision", context.inventorySnapshotRevision()); + owner.put("cohortDigest", context.cohortDigest()); + owner.put("barrierTargetDigest", context.barrierTargetDigest()); + } Map target = new LinkedHashMap<>(); target.put("targetOrdinal", context.targetOrdinal()); @@ -363,7 +466,11 @@ private static Map payload( targetEvidence.put("aofGeneration", evidence.aofGeneration()); Map root = new LinkedHashMap<>(); - root.put("schema", "firemud.gs.protected-incarnation-read/v1"); + root.put( + "schema", + initial + ? "firemud.gs.protected-initial-account-barrier-read/v1" + : "firemud.gs.protected-incarnation-read/v1"); root.put("attestorBinding", request.attestorBinding()); root.put("attestorKeyId", KEY_ID); root.put("acceptedAttestationDigest", request.acceptedAttestationDigest()); @@ -562,6 +669,243 @@ public void close() { dropSchema(schema); } + private static final class InitialFixture implements AutoCloseable { + private final String schema; + private final DSLContext dsl; + private final InitialGameplayLoginAttemptCoordinates original; + private final UUID accountId; + private final UUID tenantId; + private final UUID namespaceId; + private final String targetWorkloadNamespace; + private final KeyPair keyPair; + private final CanonicalGameplayProtectedIncarnationReceiver.ExpectedTargetDeploymentEvidence + expectedEvidence; + private final CanonicalGameplayAccountInitialBarrierInitializerRepository initialRepository; + private final CanonicalGameplayTenantGameplayTagRepository tenantTags; + + private InitialFixture( + String schema, + DSLContext dsl, + InitialGameplayLoginAttemptCoordinates original, + UUID accountId, + UUID tenantId, + UUID namespaceId, + String targetWorkloadNamespace, + KeyPair keyPair, + CanonicalGameplayProtectedIncarnationReceiver.ExpectedTargetDeploymentEvidence + expectedEvidence, + CanonicalGameplayAccountInitialBarrierInitializerRepository initialRepository, + CanonicalGameplayTenantGameplayTagRepository tenantTags) { + this.schema = schema; + this.dsl = dsl; + this.original = original; + this.accountId = accountId; + this.tenantId = tenantId; + this.namespaceId = namespaceId; + this.targetWorkloadNamespace = targetWorkloadNamespace; + this.keyPair = keyPair; + this.expectedEvidence = expectedEvidence; + this.initialRepository = initialRepository; + this.tenantTags = tenantTags; + } + + private static InitialFixture open() throws Exception { + String schema = "gs_initial_incarnation_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName("org.postgresql.Driver"); + String jdbcUrl = postgres.getJdbcUrl(); + String separator = jdbcUrl.contains("?") ? "&" : "?"; + dataSource.setUrl(jdbcUrl + separator + "currentSchema=" + schema); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history") + .locations(MIGRATION_LOCATION) + .load() + .migrate(); + DSLContext dsl = DSL.using(dataSource, SQLDialect.POSTGRES); + UUID tenantId = UUID.randomUUID(); + var runtime = + CanonicalGameplayBindingRuntimeTestFixtures.seedRunningLaunch(dataSource, tenantId); + CanonicalGameplayBindingInventoryRepositoryIntegrationTest + .seedSyntheticVerifiedLegacyDisposition(dsl); + + UUID accountId = UUID.randomUUID(); + UUID transitionId = UUID.randomUUID(); + UUID characterId = UUID.randomUUID(); + var identity = + new CanonicalGameplayBindingIdentity( + accountId, + runtime.canonicalTenantId(), + runtime.playableStateNamespaceId(), + characterId, + "SHARED", + runtime.gameInstanceUuid(), + runtime.gameInstanceId(), + UUID.randomUUID().toString(), + UUID.randomUUID(), + BigInteger.ONE, + GameSessionAccountDelegationProfile.ISSUER, + BigInteger.ONE, + BigInteger.ONE, + BigInteger.valueOf(16), + BigInteger.valueOf(32)); + var reservation = + new CanonicalIssuerReservationFenceEvidence( + UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID(), BigInteger.ONE, BigInteger.ONE, BigInteger.ONE); + new CanonicalGameplayBindingInventoryRepository(dsl) + .prepare( + new CanonicalGameplayBindingTransitionRequest( + transitionId, UUID.randomUUID(), identity, reservation, null, null)); + dsl.execute( + "UPDATE game_session_canonical_account_coverage_control" + + " SET last_operation_fence = 8 WHERE account_id = ?", + accountId); + + InitialGameplayLoginAttemptCoordinates original = + new InitialGameplayLoginAttemptCoordinates(UUID.randomUUID(), UUID.randomUUID(), 17L); + var accountLogin = mockInitialLoginResult(original, accountId, UUID.randomUUID()); + dsl.execute( + "INSERT INTO game_session_initial_gameplay_login_journal" + + " (request_id, caller_context_id, expected_attempt_fence) VALUES (?, ?, ?)", + original.requestId(), + original.callerContextId(), + original.expectedAttemptFence()); + dsl.execute( + "UPDATE game_session_initial_gameplay_login_journal" + + " SET verified_token_jti = ?, verified_token_sha256 = ?," + + " verified_token_generation = 1, verified_issuance_fence = 1" + + " WHERE request_id = ?", + accountLogin.evidence().tokenJti(), + accountLogin.evidence().tokenSha256(), + original.requestId()); + CanonicalGameplayAccountInitialBarrierInitializerRepository initialRepository = + new CanonicalGameplayAccountInitialBarrierInitializerRepository(dsl); + initialRepository.beginOrRead( + original, accountLogin, runtime.canonicalTenantId(), runtime.playableStateNamespaceId()); + accountLogin.close(); + + KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); + generator.initialize(2048); + KeyPair keyPair = generator.generateKeyPair(); + var expectedEvidence = controlledExpectedEvidence(); + var tenantTags = + new CanonicalGameplayTenantGameplayTagRepository( + dsl, runtime.targetNamespace(), 1); + return new InitialFixture( + schema, + dsl, + original, + accountId, + runtime.canonicalTenantId(), + runtime.playableStateNamespaceId(), + runtime.targetNamespace(), + keyPair, + expectedEvidence, + initialRepository, + tenantTags); + } + + private CanonicalGameplayProtectedIncarnationReceiver receiver( + CanonicalGameplayProtectedIncarnationReceiver.ProtectedObservationChannel channel) { + return receiver( + channel, + new CanonicalGameplayProtectedIncarnationReceiver.TrustedConfiguration( + ATTESTOR_BINDING, + ACCEPTED_ATTESTATION_DIGEST, + Map.of(KEY_ID, (java.security.interfaces.RSAPublicKey) keyPair.getPublic()), + expectedEvidence, + ACL_DIGEST, + CONFIG_DIGEST, + 16 * 1024, + 1, + Duration.ofSeconds(30))); + } + + private CanonicalGameplayProtectedIncarnationReceiver receiver( + CanonicalGameplayProtectedIncarnationReceiver.ProtectedObservationChannel channel, + CanonicalGameplayProtectedIncarnationReceiver.TrustedConfiguration configuration) { + return new CanonicalGameplayProtectedIncarnationReceiver( + initialRepository, tenantTags, channel, configuration, Clock.fixed(NOW, ZoneOffset.UTC)); + } + + private InitialGameplayLoginAttemptCoordinates original() { + return original; + } + + private UUID accountId() { + return accountId; + } + + private KeyPair keyPair() { + return keyPair; + } + + private DSLContext dsl() { + return dsl; + } + + private CanonicalGameplayProtectedIncarnationReceiver.ExpectedTargetDeploymentEvidence + expectedEvidence() { + return expectedEvidence; + } + + @Override + public void close() { + try (var connection = + java.sql.DriverManager.getConnection( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); + var statement = connection.createStatement()) { + statement.execute("DROP SCHEMA IF EXISTS " + schema + " CASCADE"); + } catch (Exception failure) { + throw new IllegalStateException("Could not dispose INITIAL observation schema", failure); + } + } + } + + private static CanonicalGameplayLoginResult mockInitialLoginResult( + InitialGameplayLoginAttemptCoordinates original, UUID accountId, UUID tokenJti) { + var evidence = + new CanonicalGameplayLoginResult.NonSecretEvidence( + accountId, + original.requestId(), + original.callerContextId(), + tokenJti, + "e".repeat(64), + GameSessionAccountDelegationProfile.PROFILE, + NOW.getEpochSecond(), + NOW.getEpochSecond(), + NOW.plusSeconds(120).getEpochSecond(), + "1", + "1", + ByteString.copyFromUtf8("{}"), + ByteString.copyFromUtf8("[]"), + ByteString.copyFromUtf8("[]")); + CanonicalGameplayLoginResult result = mock(CanonicalGameplayLoginResult.class); + when(result.evidence()).thenReturn(evidence); + return result; + } + + private static + CanonicalGameplayProtectedIncarnationReceiver.ExpectedTargetDeploymentEvidence + controlledExpectedEvidence() { + return new CanonicalGameplayProtectedIncarnationReceiver.ExpectedTargetDeploymentEvidence( + "controlled-target-deployment", + "generation-7", + List.of("redis-node-a"), + "redis-test-build", + "registry-test-v1", + "sha256:" + "d".repeat(64), + "READY", + "boot-7", + "startup-7", + "storage-7", + "aof-7"); + } + private static DriverManagerDataSource dataSource(String schema) { DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName("org.postgresql.Driver"); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierRedisOwnerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierRedisOwnerTest.java new file mode 100644 index 0000000000..6f02d96df2 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierRedisOwnerTest.java @@ -0,0 +1,495 @@ +package net.firedevops.firemud.gamesession.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.lettuce.core.RedisClient; +import io.lettuce.core.RedisFuture; +import io.lettuce.core.api.StatefulRedisConnection; +import io.lettuce.core.api.async.RedisAsyncCommands; +import io.lettuce.core.codec.ByteArrayCodec; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; +import net.firedevops.firemud.gamesession.dto.CanonicalGameplayLoginResult; +import net.firedevops.firemud.gamesession.dto.InitialGameplayLoginAttemptCoordinates; +import net.firedevops.firemud.gamesession.service.CanonicalGameplayAccountInitialBarrierRedisScriptContribution; +import org.junit.jupiter.api.Test; + +class CanonicalGameplayAccountInitialBarrierRedisOwnerTest { + private static final String DIGEST = "sha256:" + "a".repeat(64); + + @Test + @SuppressWarnings({"unchecked", "rawtypes"}) + void missingPhysicalValueAfterPossibleDispatchRefusesWithoutFreshScriptAttempt() throws Exception { + UUID requestId = UUID.randomUUID(); + UUID callerContextId = UUID.randomUUID(); + UUID initializerId = UUID.randomUUID(); + UUID accountId = UUID.randomUUID(); + UUID tenantId = UUID.randomUUID(); + UUID namespaceId = UUID.randomUUID(); + var original = new InitialGameplayLoginAttemptCoordinates(requestId, callerContextId, 17L); + var snapshot = + new CanonicalGameplayAccountInitialBarrierInitializerRepository.InitializerSnapshot( + initializerId, + requestId, + callerContextId, + 17L, + accountId, + tenantId, + namespaceId, + DIGEST, + "NO_ACTIVE_ACCOUNT_WIDE_FLOW", + BigInteger.valueOf(8), + BigInteger.valueOf(4), + DIGEST, + CanonicalGameplayAccountInitialBarrierInitializerRepository.State.DISPATCH_POSSIBLE, + DIGEST, + DIGEST, + DIGEST, + 1_000L, + 1_100L, + 31_000L, + null, + DIGEST); + + var repository = mock(CanonicalGameplayAccountInitialBarrierInitializerRepository.class); + when(repository.beginOrRead(any(), any(), any(), any())).thenReturn(snapshot); + when(repository.readCurrent(requestId)).thenReturn(snapshot); + var tenantTags = mock(CanonicalGameplayTenantGameplayTagRepository.class); + var assignment = mock(CanonicalGameplayTenantGameplayTagRepository.Assignment.class); + when(tenantTags.assignmentForInitialBarrierTarget(requestId)).thenReturn(assignment); + when(assignment.isInitialBarrierTarget()).thenReturn(true); + when(assignment.initialBarrierInitializerId()).thenReturn(initializerId); + when(assignment.initialBarrierOriginalRequestId()).thenReturn(requestId); + when(assignment.accountId()).thenReturn(accountId); + when(assignment.tenantId()).thenReturn(tenantId); + when(assignment.playableStateNamespaceId()).thenReturn(namespaceId); + when(assignment.tenantGameplayTag()).thenReturn("g8-" + "b".repeat(32)); + + var observation = mock(CanonicalGameplayProtectedIncarnationReceiver.VerifiedIncarnation.class); + when(observation.ownerKind()) + .thenReturn(CanonicalGameplayProtectedIncarnationReceiver.OwnerKind.INITIAL_ACCOUNT_BARRIER); + when(observation.operationId()).thenReturn(initializerId); + when(observation.requestId()).thenReturn(requestId); + when(observation.originalCallerContextId()).thenReturn(callerContextId); + when(observation.originalAttemptFence()).thenReturn(17L); + when(observation.accountId()).thenReturn(accountId); + when(observation.tenantId()).thenReturn(tenantId); + when(observation.playableStateNamespaceId()).thenReturn(namespaceId); + when(observation.sourceControlState()).thenReturn("NO_ACTIVE_ACCOUNT_WIDE_FLOW"); + when(observation.sourceControlEpoch()).thenReturn("8"); + when(observation.inventorySnapshotRevision()).thenReturn("4"); + when(observation.accountLoginEvidenceDigest()).thenReturn(DIGEST); + when(observation.sourceControlDigest()).thenReturn(DIGEST); + when(observation.barrierTargetDigest()).thenReturn(DIGEST); + when(observation.incarnationDigest()).thenReturn(DIGEST); + when(observation.acceptedAttestationDigest()).thenReturn(DIGEST); + var receiver = mock(CanonicalGameplayProtectedIncarnationReceiver.class); + when(receiver.observeForInitialAccountBarrier(requestId)).thenReturn(observation); + + RedisClient redis = mock(RedisClient.class); + StatefulRedisConnection connection = mock(StatefulRedisConnection.class); + RedisAsyncCommands commands = mock(RedisAsyncCommands.class); + when(redis.connect(any(ByteArrayCodec.class))).thenReturn(connection); + when(connection.isOpen()).thenReturn(true); + when(connection.async()).thenReturn(commands); + when(commands.aclWhoami()).thenReturn(future("gamesession_coord_app")); + when(commands.type(any(byte[].class))).thenReturn(future("none")); + RedisScriptCatalog catalog = mock(RedisScriptCatalog.class); + + var owner = + new CanonicalGameplayAccountInitialBarrierRedisOwner( + redis, catalog, repository, tenantTags, receiver); + var proof = + owner.initializeOnce( + original, + mock(CanonicalGameplayLoginResult.class), + tenantId, + namespaceId); + + assertThat(proof) + .isEqualTo( + new CanonicalGameplayAccountInitialOpenProof.Refused( + CanonicalGameplayAccountInitialOpenProof.Reason.REMOTE_OUTCOME_UNCERTAIN)); + verify(repository).beginOrRead(original, org.mockito.ArgumentMatchers.any(), tenantId, namespaceId); + verify(commands).type(any(byte[].class)); + verifyNoInteractions(catalog); + } + + @Test + void possibleDispatchIsPersistedBeforeRedisAndMissingAfterwardNeverGetsAFreshCreate() { + UUID requestId = UUID.randomUUID(); + UUID callerContextId = UUID.randomUUID(); + UUID initializerId = UUID.randomUUID(); + UUID accountId = UUID.randomUUID(); + UUID tenantId = UUID.randomUUID(); + UUID namespaceId = UUID.randomUUID(); + var original = new InitialGameplayLoginAttemptCoordinates(requestId, callerContextId, 17L); + var never = + snapshot( + initializerId, + original, + accountId, + tenantId, + namespaceId, + CanonicalGameplayAccountInitialBarrierInitializerRepository.State.NEVER_DISPATCHED); + var possible = + new CanonicalGameplayAccountInitialBarrierInitializerRepository.InitializerSnapshot( + initializerId, + requestId, + callerContextId, + 17L, + accountId, + tenantId, + namespaceId, + DIGEST, + "NO_ACTIVE_ACCOUNT_WIDE_FLOW", + BigInteger.valueOf(8), + BigInteger.valueOf(4), + DIGEST, + CanonicalGameplayAccountInitialBarrierInitializerRepository.State.DISPATCH_POSSIBLE, + DIGEST, + DIGEST, + DIGEST, + 1_000L, + 1_100L, + 31_000L, + null, + DIGEST); + var before = initialObservation(possible); + + var repository = mock(CanonicalGameplayAccountInitialBarrierInitializerRepository.class); + when(repository.beginOrRead(any(), any(), any(), any())).thenReturn(never); + when(repository.recordDispatchPossible(requestId, before)).thenReturn(possible); + when(repository.readCurrent(requestId)).thenReturn(possible); + var tenantTags = mock(CanonicalGameplayTenantGameplayTagRepository.class); + var assignment = mock(CanonicalGameplayTenantGameplayTagRepository.Assignment.class); + when(tenantTags.assignmentForInitialBarrierTarget(requestId)).thenReturn(assignment); + when(assignment.isInitialBarrierTarget()).thenReturn(true); + when(assignment.initialBarrierInitializerId()).thenReturn(initializerId); + when(assignment.initialBarrierOriginalRequestId()).thenReturn(requestId); + when(assignment.accountId()).thenReturn(accountId); + when(assignment.tenantId()).thenReturn(tenantId); + when(assignment.playableStateNamespaceId()).thenReturn(namespaceId); + when(assignment.tenantGameplayTag()).thenReturn("g8-" + "b".repeat(32)); + var receiver = mock(CanonicalGameplayProtectedIncarnationReceiver.class); + when(receiver.observeForInitialAccountBarrier(requestId)).thenReturn(before); + + RedisClient redis = mock(RedisClient.class); + AtomicInteger connectionAttempts = new AtomicInteger(); + when(redis.connect(any(ByteArrayCodec.class))) + .thenAnswer( + ignored -> { + if (connectionAttempts.getAndIncrement() == 0) { + verify(repository).recordDispatchPossible(requestId, before); + } + throw new IllegalStateException("controlled lost connection"); + }); + RedisScriptCatalog catalog = + RedisScriptCatalog.fromContributions( + List.of(new CanonicalGameplayAccountInitialBarrierRedisScriptContribution())); + var owner = + new CanonicalGameplayAccountInitialBarrierRedisOwner( + redis, catalog, repository, tenantTags, receiver); + + var proof = + owner.initializeOnce( + original, + mock(CanonicalGameplayLoginResult.class), + tenantId, + namespaceId); + + assertThat(proof) + .isEqualTo( + new CanonicalGameplayAccountInitialOpenProof.Refused( + CanonicalGameplayAccountInitialOpenProof.Reason.REMOTE_OUTCOME_UNCERTAIN)); + assertThat(connectionAttempts.get()).isEqualTo(2); + verify(repository).recordDispatchPossible(requestId, before); + } + + @Test + @SuppressWarnings({"unchecked", "rawtypes"}) + void exactSameOriginalOpenReplayIsReadOnlyAndReturnsCurrentTypedProof() throws Exception { + UUID requestId = UUID.randomUUID(); + UUID callerContextId = UUID.randomUUID(); + UUID initializerId = UUID.randomUUID(); + UUID accountId = UUID.randomUUID(); + UUID tenantId = UUID.randomUUID(); + UUID namespaceId = UUID.randomUUID(); + String tag = "g8-" + "b".repeat(32); + var original = new InitialGameplayLoginAttemptCoordinates(requestId, callerContextId, 17L); + var snapshot = + new CanonicalGameplayAccountInitialBarrierInitializerRepository.InitializerSnapshot( + initializerId, + requestId, + callerContextId, + 17L, + accountId, + tenantId, + namespaceId, + DIGEST, + "NO_ACTIVE_ACCOUNT_WIDE_FLOW", + BigInteger.valueOf(8), + BigInteger.valueOf(4), + DIGEST, + CanonicalGameplayAccountInitialBarrierInitializerRepository.State.OPEN_INSTALLED, + DIGEST, + DIGEST, + DIGEST, + 1_000L, + 1_100L, + 31_000L, + DIGEST, + DIGEST); + var assignment = mock(CanonicalGameplayTenantGameplayTagRepository.Assignment.class); + when(assignment.isInitialBarrierTarget()).thenReturn(true); + when(assignment.initialBarrierInitializerId()).thenReturn(initializerId); + when(assignment.initialBarrierOriginalRequestId()).thenReturn(requestId); + when(assignment.accountId()).thenReturn(accountId); + when(assignment.tenantId()).thenReturn(tenantId); + when(assignment.playableStateNamespaceId()).thenReturn(namespaceId); + when(assignment.tenantGameplayTag()).thenReturn(tag); + var repository = mock(CanonicalGameplayAccountInitialBarrierInitializerRepository.class); + when(repository.beginOrRead(any(), any(), any(), any())).thenReturn(snapshot); + when(repository.readCurrent(requestId)).thenReturn(snapshot); + var tenantTags = mock(CanonicalGameplayTenantGameplayTagRepository.class); + when(tenantTags.assignmentForInitialBarrierTarget(requestId)).thenReturn(assignment); + var observation = initialObservation(snapshot); + var receiver = mock(CanonicalGameplayProtectedIncarnationReceiver.class); + when(receiver.observeForInitialAccountBarrier(requestId)).thenReturn(observation); + + var expected = + CanonicalGameplayAccountInitialBarrierValue.open( + accountId, tenantId, namespaceId, tag, initializerId, BigInteger.valueOf(8), DIGEST); + Map raw = new HashMap<>(); + expected.fields().forEach( + (field, value) -> + raw.put( + field.getBytes(StandardCharsets.US_ASCII), + value.getBytes(StandardCharsets.US_ASCII))); + RedisClient redis = mock(RedisClient.class); + StatefulRedisConnection connection = mock(StatefulRedisConnection.class); + RedisAsyncCommands commands = mock(RedisAsyncCommands.class); + when(redis.connect(any(ByteArrayCodec.class))).thenReturn(connection); + when(connection.isOpen()).thenReturn(true); + when(connection.async()).thenReturn(commands); + when(commands.aclWhoami()).thenReturn(future("gamesession_coord_app")); + when(commands.type(any(byte[].class))).thenReturn(future("hash")); + when(commands.pttl(any(byte[].class))).thenReturn(future(-1L)); + when(commands.hlen(any(byte[].class))).thenReturn(future(9L)); + when(commands.hgetall(any(byte[].class))).thenReturn(future(raw)); + RedisScriptCatalog catalog = mock(RedisScriptCatalog.class); + var owner = + new CanonicalGameplayAccountInitialBarrierRedisOwner( + redis, catalog, repository, tenantTags, receiver); + + var proof = owner.initializeOnce(original, mock(CanonicalGameplayLoginResult.class), tenantId, namespaceId); + + assertThat(proof).isInstanceOf(CanonicalGameplayAccountInitialOpenProof.CurrentOpen.class); + var current = (CanonicalGameplayAccountInitialOpenProof.CurrentOpen) proof; + assertThat(current.originalRequestId()).isEqualTo(requestId); + assertThat(current.sourceControlEpoch()).isEqualTo(BigInteger.valueOf(8)); + assertThat(current.exactFields()).isEqualTo(expected.fields()); + verify(repository, org.mockito.Mockito.times(2)).readCurrent(requestId); + verify(repository).beginOrRead(original, org.mockito.ArgumentMatchers.any(), tenantId, namespaceId); + verify(repository, org.mockito.Mockito.times(3)).requireNoAmbientTransaction(); + verify(receiver, org.mockito.Mockito.times(2)).observeForInitialAccountBarrier(requestId); + verifyNoInteractions(catalog); + verify(commands).hgetall(any(byte[].class)); + verify(commands, org.mockito.Mockito.never()).evalsha(any(), any(), any(), any()); + } + + @Test + @SuppressWarnings({"unchecked", "rawtypes"}) + void ambiguousDispatchRetryRequiresExactOpenReadbackBeforeCompletingOriginalReceipt() + throws Exception { + UUID requestId = UUID.randomUUID(); + UUID callerContextId = UUID.randomUUID(); + UUID initializerId = UUID.randomUUID(); + UUID accountId = UUID.randomUUID(); + UUID tenantId = UUID.randomUUID(); + UUID namespaceId = UUID.randomUUID(); + String tag = "g8-" + "b".repeat(32); + var original = new InitialGameplayLoginAttemptCoordinates(requestId, callerContextId, 17L); + var pending = + new CanonicalGameplayAccountInitialBarrierInitializerRepository.InitializerSnapshot( + initializerId, + requestId, + callerContextId, + 17L, + accountId, + tenantId, + namespaceId, + DIGEST, + "NO_ACTIVE_ACCOUNT_WIDE_FLOW", + BigInteger.valueOf(8), + BigInteger.valueOf(4), + DIGEST, + CanonicalGameplayAccountInitialBarrierInitializerRepository.State.DISPATCH_POSSIBLE, + DIGEST, + DIGEST, + DIGEST, + 1_000L, + 1_100L, + 31_000L, + null, + DIGEST); + var installed = + new CanonicalGameplayAccountInitialBarrierInitializerRepository.InitializerSnapshot( + initializerId, + requestId, + callerContextId, + 17L, + accountId, + tenantId, + namespaceId, + DIGEST, + "NO_ACTIVE_ACCOUNT_WIDE_FLOW", + BigInteger.valueOf(8), + BigInteger.valueOf(4), + DIGEST, + CanonicalGameplayAccountInitialBarrierInitializerRepository.State.OPEN_INSTALLED, + DIGEST, + DIGEST, + DIGEST, + 1_000L, + 1_100L, + 31_000L, + DIGEST, + DIGEST); + var assignment = mock(CanonicalGameplayTenantGameplayTagRepository.Assignment.class); + when(assignment.isInitialBarrierTarget()).thenReturn(true); + when(assignment.initialBarrierInitializerId()).thenReturn(initializerId); + when(assignment.initialBarrierOriginalRequestId()).thenReturn(requestId); + when(assignment.accountId()).thenReturn(accountId); + when(assignment.tenantId()).thenReturn(tenantId); + when(assignment.playableStateNamespaceId()).thenReturn(namespaceId); + when(assignment.tenantGameplayTag()).thenReturn(tag); + var repository = mock(CanonicalGameplayAccountInitialBarrierInitializerRepository.class); + when(repository.beginOrRead(any(), any(), any(), any())).thenReturn(pending); + when(repository.readCurrent(requestId)).thenReturn(pending); + when(repository.acceptOpenReadback(any(), any())).thenReturn(installed); + var tenantTags = mock(CanonicalGameplayTenantGameplayTagRepository.class); + when(tenantTags.assignmentForInitialBarrierTarget(requestId)).thenReturn(assignment); + var observation = initialObservation(pending); + var receiver = mock(CanonicalGameplayProtectedIncarnationReceiver.class); + when(receiver.observeForInitialAccountBarrier(requestId)).thenReturn(observation); + + var expected = + CanonicalGameplayAccountInitialBarrierValue.open( + accountId, tenantId, namespaceId, tag, initializerId, BigInteger.valueOf(8), DIGEST); + Map raw = new HashMap<>(); + expected.fields().forEach( + (field, value) -> + raw.put( + field.getBytes(StandardCharsets.US_ASCII), + value.getBytes(StandardCharsets.US_ASCII))); + RedisClient redis = mock(RedisClient.class); + StatefulRedisConnection connection = mock(StatefulRedisConnection.class); + RedisAsyncCommands commands = mock(RedisAsyncCommands.class); + when(redis.connect(any(ByteArrayCodec.class))).thenReturn(connection); + when(connection.isOpen()).thenReturn(true); + when(connection.async()).thenReturn(commands); + when(commands.aclWhoami()).thenReturn(future("gamesession_coord_app")); + when(commands.type(any(byte[].class))).thenReturn(future("hash")); + when(commands.pttl(any(byte[].class))).thenReturn(future(-1L)); + when(commands.hlen(any(byte[].class))).thenReturn(future(9L)); + when(commands.hgetall(any(byte[].class))).thenReturn(future(raw)); + RedisScriptCatalog catalog = mock(RedisScriptCatalog.class); + var owner = + new CanonicalGameplayAccountInitialBarrierRedisOwner( + redis, catalog, repository, tenantTags, receiver); + + var proof = owner.initializeOnce(original, mock(CanonicalGameplayLoginResult.class), tenantId, namespaceId); + + assertThat(proof).isInstanceOf(CanonicalGameplayAccountInitialOpenProof.CurrentOpen.class); + var current = (CanonicalGameplayAccountInitialOpenProof.CurrentOpen) proof; + assertThat(current.originalRequestId()).isEqualTo(requestId); + assertThat(current.exactFields()).isEqualTo(expected.fields()); + verify(repository).acceptOpenReadback(requestId, org.mockito.ArgumentMatchers.any()); + verify(repository).readCurrent(requestId); + verify(receiver, org.mockito.Mockito.times(2)).observeForInitialAccountBarrier(requestId); + verifyNoInteractions(catalog); + verify(commands).hgetall(any(byte[].class)); + verify(commands, org.mockito.Mockito.never()).evalsha(any(), any(), any(), any()); + } + + private static CanonicalGameplayAccountInitialBarrierInitializerRepository.InitializerSnapshot + snapshot( + UUID initializerId, + InitialGameplayLoginAttemptCoordinates original, + UUID accountId, + UUID tenantId, + UUID namespaceId, + CanonicalGameplayAccountInitialBarrierInitializerRepository.State state) { + return new CanonicalGameplayAccountInitialBarrierInitializerRepository.InitializerSnapshot( + initializerId, + original.requestId(), + original.callerContextId(), + original.expectedAttemptFence(), + accountId, + tenantId, + namespaceId, + DIGEST, + "NO_ACTIVE_ACCOUNT_WIDE_FLOW", + BigInteger.valueOf(8), + BigInteger.valueOf(4), + DIGEST, + state, + null, + null, + null, + 0L, + 0L, + 0L, + null, + DIGEST); + } + + private static CanonicalGameplayProtectedIncarnationReceiver.VerifiedIncarnation + initialObservation( + CanonicalGameplayAccountInitialBarrierInitializerRepository.InitializerSnapshot snapshot) { + var observation = mock(CanonicalGameplayProtectedIncarnationReceiver.VerifiedIncarnation.class); + when(observation.ownerKind()) + .thenReturn(CanonicalGameplayProtectedIncarnationReceiver.OwnerKind.INITIAL_ACCOUNT_BARRIER); + when(observation.operationId()).thenReturn(snapshot.initializerId()); + when(observation.requestId()).thenReturn(snapshot.originalRequestId()); + when(observation.originalCallerContextId()).thenReturn(snapshot.originalCallerContextId()); + when(observation.originalAttemptFence()).thenReturn(snapshot.originalAttemptFence()); + when(observation.accountId()).thenReturn(snapshot.accountId()); + when(observation.tenantId()).thenReturn(snapshot.tenantId()); + when(observation.playableStateNamespaceId()).thenReturn(snapshot.playableStateNamespaceId()); + when(observation.sourceControlState()).thenReturn(snapshot.sourceControlState()); + when(observation.sourceControlEpoch()).thenReturn(snapshot.sourceControlEpoch().toString()); + when(observation.inventorySnapshotRevision()) + .thenReturn(snapshot.inventorySnapshotRevision().toString()); + when(observation.accountLoginEvidenceDigest()).thenReturn(snapshot.accountLoginEvidenceDigest()); + when(observation.sourceControlDigest()).thenReturn(snapshot.sourceControlDigest()); + when(observation.barrierTargetDigest()).thenReturn(snapshot.targetDigest()); + when(observation.incarnationDigest()).thenReturn(DIGEST); + when(observation.acceptedAttestationDigest()).thenReturn(DIGEST); + when(observation.payloadDigest()).thenReturn(DIGEST); + when(observation.issuedAtEpochMillis()).thenReturn(1_000L); + when(observation.observedAtEpochMillis()).thenReturn(1_100L); + when(observation.expiresAtEpochMillis()).thenReturn(31_000L); + return observation; + } + + private static RedisFuture future(T value) throws Exception { + RedisFuture future = mock(RedisFuture.class); + when(future.get(anyLong(), any(TimeUnit.class))).thenReturn(value); + return future; + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierValueTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierValueTest.java new file mode 100644 index 0000000000..e72605e73d --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierValueTest.java @@ -0,0 +1,180 @@ +package net.firedevops.firemud.gamesession.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.when; + +import java.math.BigInteger; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.UUID; +import org.junit.jupiter.api.Test; + +class CanonicalGameplayAccountInitialBarrierValueTest { + private static final String DIGEST = "sha256:" + "a".repeat(64); + + @Test + void initialBarrierValueRetainsTheExactPositivelyReadEpochIncludingZero() { + UUID accountId = UUID.randomUUID(); + UUID tenantId = UUID.randomUUID(); + UUID namespaceId = UUID.randomUUID(); + UUID initializerId = UUID.randomUUID(); + + var value = + CanonicalGameplayAccountInitialBarrierValue.open( + accountId, + tenantId, + namespaceId, + "g7-" + "b".repeat(32), + initializerId, + BigInteger.ZERO, + DIGEST); + + assertThat(value.fields()) + .containsExactlyInAnyOrderEntriesOf( + Map.of( + "schema", CanonicalGameplayAccountInitialBarrierValue.SCHEMA, + "accountId", accountId.toString(), + "tenantId", tenantId.toString(), + "playableStateNamespaceId", namespaceId.toString(), + "tenantGameplayTag", "g7-" + "b".repeat(32), + "ownerOperationId", initializerId.toString(), + "ownerFenceEpoch", "0", + "incarnationDigest", DIGEST, + "state", "OPEN")); + assertThat(value.fields().keySet()) + .containsExactlyInAnyOrderElementsOf(CanonicalGameplayAccountInitialBarrierValue.FIELDS); + } + + @Test + void currentOpenProofRequiresExactCapturedEpochOriginalAttemptAndNineFields() { + UUID initializerId = UUID.randomUUID(); + UUID requestId = UUID.randomUUID(); + UUID callerContextId = UUID.randomUUID(); + UUID accountId = UUID.randomUUID(); + UUID tenantId = UUID.randomUUID(); + UUID namespaceId = UUID.randomUUID(); + var value = + CanonicalGameplayAccountInitialBarrierValue.open( + accountId, + tenantId, + namespaceId, + "g8-" + "c".repeat(32), + initializerId, + BigInteger.valueOf(9), + DIGEST); + + var proof = + new CanonicalGameplayAccountInitialOpenProof.CurrentOpen( + initializerId, + requestId, + callerContextId, + 9, + accountId, + tenantId, + namespaceId, + "session:game:account-admission:{g8-" + "c".repeat(32) + "}:" + accountId + ":" + namespaceId, + BigInteger.valueOf(9), + BigInteger.ONE, + DIGEST, + DIGEST, + DIGEST, + 1_000L, + 31_000L, + value.fields()); + + assertThat(proof.originalAttemptFence()).isEqualTo(9L); + assertThat(proof.sourceControlEpoch()).isEqualTo(BigInteger.valueOf(9)); + assertThat(proof.exactFields()).containsEntry("ownerFenceEpoch", "9"); + assertThatThrownBy( + () -> + new CanonicalGameplayAccountInitialOpenProof.CurrentOpen( + initializerId, + requestId, + callerContextId, + 9, + accountId, + tenantId, + namespaceId, + proof.key(), + BigInteger.ONE, + BigInteger.ONE, + DIGEST, + DIGEST, + DIGEST, + 1_000L, + 31_000L, + value.fields())) + .isInstanceOf(IllegalArgumentException.class); + Map changed = new LinkedHashMap<>(value.fields()); + changed.put("ownerFenceEpoch", "1"); + assertThatThrownBy( + () -> + new CanonicalGameplayAccountInitialOpenProof.CurrentOpen( + initializerId, + requestId, + callerContextId, + 9, + accountId, + tenantId, + namespaceId, + proof.key(), + BigInteger.ZERO, + BigInteger.ONE, + DIGEST, + DIGEST, + DIGEST, + 1_000L, + 31_000L, + changed)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void unavailableSourcesHaveTypedNonAdmittingRefusals() { + assertThat( + new CanonicalGameplayAccountInitialOpenProof.Refused( + CanonicalGameplayAccountInitialOpenProof.Reason.REMOTE_OUTCOME_UNCERTAIN)) + .isInstanceOf(CanonicalGameplayAccountInitialOpenProof.Refused.class) + .extracting(CanonicalGameplayAccountInitialOpenProof.Refused::reason) + .isEqualTo(CanonicalGameplayAccountInitialOpenProof.Reason.REMOTE_OUTCOME_UNCERTAIN); + } + + @Test + void initialKeyUsesCanonicalBarrierSerializationOnlyForItsPersistedOriginalTarget() { + UUID initializerId = UUID.randomUUID(); + UUID requestId = UUID.randomUUID(); + UUID accountId = UUID.randomUUID(); + UUID tenantId = UUID.randomUUID(); + UUID namespaceId = UUID.randomUUID(); + var assignment = mock(CanonicalGameplayTenantGameplayTagRepository.Assignment.class); + when(assignment.isInitialBarrierTarget()).thenReturn(true); + when(assignment.initialBarrierInitializerId()).thenReturn(initializerId); + when(assignment.initialBarrierOriginalRequestId()).thenReturn(requestId); + when(assignment.tenantGameplayTag()) + .thenReturn("g7-" + tenantId.toString().replace("-", "")); + when(assignment.accountId()).thenReturn(accountId); + when(assignment.playableStateNamespaceId()).thenReturn(namespaceId); + + String key = + CanonicalGameplayAccountInitialBarrierKey.forTarget(assignment, initializerId, requestId); + + assertThat(key) + .isEqualTo( + "session:game:account-admission:{g7-" + + tenantId.toString().replace("-", "") + + "]:" + + accountId + + ":" + + namespaceId); + assertThatThrownBy( + () -> + CanonicalGameplayAccountInitialBarrierKey.forTarget( + assignment, UUID.randomUUID(), requestId)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> CanonicalGameplaySessionRedisKeys.accountAdmissionBarrier(assignment)) + .isInstanceOf(IllegalArgumentException.class); + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCandidateTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCandidateTest.java new file mode 100644 index 0000000000..39848d20a9 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCandidateTest.java @@ -0,0 +1,511 @@ +package net.firedevops.firemud.gamesession.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Comparator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAccountCoverageEvidence; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAdmissionDecision; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingIdentity; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingInventoryEntry; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingProvisionalCasEvidence; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingTransitionSnapshot; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationDisposition; +import net.firedevops.firemud.gamesession.binding.CanonicalIssuerPartitionReservation; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionOwnerProof; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionRequest; +import net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget; +import org.junit.jupiter.api.Test; + +class CanonicalGameplayOriginalNewCandidateTest { + private static final UUID ACCOUNT = id(1); + private static final UUID TENANT = id(2); + private static final UUID REALM = id(3); + private static final UUID NAMESPACE = id(4); + private static final UUID GAME_INSTANCE = id(5); + private static final UUID CHARACTER = id(6); + private static final UUID SESSION = id(7); + private static final UUID REGION = id(8); + private static final UUID VERSION = id(9); + + @Test + void retainsExactNonAdmittingCandidateAndStableRetryBytes() { + Bundle prepared = bundle(CHARACTER, BigInteger.valueOf(7), "World", false); + CanonicalGameplayOriginalNewCandidate first = + CanonicalGameplayOriginalNewCandidate.fromOriginalSources( + provisionalEvidence( + prepared.identity(), prepared.bindingGeneration(), BigInteger.valueOf(20), false), + prepared.decision()); + CanonicalGameplayOriginalNewCandidate retry = + CanonicalGameplayOriginalNewCandidate.fromOriginalSources( + provisionalEvidence( + prepared.identity(), prepared.bindingGeneration(), BigInteger.valueOf(28), true), + prepared.decision()); + + assertThat(retry.canonicalBytes()).isEqualTo(first.canonicalBytes()); + assertThat(first.exactlyMatches(first.canonicalBytes())).isTrue(); + assertThat(first.matchesOriginalDecision(prepared.decision())).isTrue(); + assertThat(first.matchesProvisionalSources(preparedEvidence(prepared))).isTrue(); + assertThat( + first.matchesProvisionalSources( + provisionalEvidence( + prepared.identity(), prepared.bindingGeneration(), BigInteger.valueOf(28), true))) + .isTrue(); + + CanonicalGameplayOriginalNewCandidate decoded = + CanonicalGameplayOriginalNewCandidate.parseCanonical(first.canonicalBytes()); + assertThat(decoded).isEqualTo(first); + assertThat(decoded.canonicalJson()).isEqualTo(first.canonicalJson()); + assertThat(decoded.bindingIdentity()).isEqualTo(prepared.identity()); + assertThat(decoded.leaseEvidence().hasSameIdentity(prepared.leaseEvidence())).isTrue(); + assertThat(decoded.targetEvidence()).isEqualTo(prepared.target()); + assertThat(decoded.transition().transitionId()).isEqualTo(prepared.decision().transitionId()); + assertThat(decoded.reservation().bindingGeneration()).isEqualTo(BigInteger.valueOf(7)); + assertThat(decoded.reservation().inventorySnapshotRevision()).isEqualTo(BigInteger.valueOf(19)); + assertThat(first.matchesProvisionalSources(provisionalEvidence( + prepared.identity(), prepared.bindingGeneration(), BigInteger.valueOf(28), true, + BigInteger.valueOf(20)))).isFalse(); + + String encoded = first.canonicalJson(); + assertThat(encoded) + .contains("\"purpose\":\"" + CanonicalGameplayOriginalNewCandidate.PURPOSE + "\"") + .contains("\"membershipBaseline\"") + .contains("\"authorityTuple\"") + .contains("\"outboxCheckpoints\"") + .doesNotContain( + "\"schemaVersion\":2", + "authTokenHash", + "rebindHandle", + "admissionAt", + "continuityBindingExpiresAt", + "raw-original-jwt", + "private-rebind-handle"); + assertThat(first.toString()) + .doesNotContain(prepared.leaseEvidence().sha256(), "raw-original-jwt", "private-rebind-handle"); + } + + @Test + void rejectsWrongLeaseBindingGenerationAndTargetWhenMatchingTheOriginalDecision() { + Bundle original = bundle(CHARACTER, BigInteger.valueOf(7), "World", false); + CanonicalGameplayOriginalNewCandidate candidate = + CanonicalGameplayOriginalNewCandidate.fromOriginalSources( + preparedEvidence(original), original.decision()); + + Bundle otherLease = bundle(CHARACTER, BigInteger.valueOf(7), "World", true); + Bundle otherBinding = bundle(id(60), BigInteger.valueOf(7), "World", false); + Bundle otherGeneration = bundle(CHARACTER, BigInteger.valueOf(8), "World", false); + Bundle otherTarget = bundle(CHARACTER, BigInteger.valueOf(7), "Changed World", false); + + assertThat(candidate.matchesOriginalDecision(otherLease.decision())).isFalse(); + assertThat(candidate.matchesOriginalDecision(otherBinding.decision())).isFalse(); + assertThat(candidate.matchesOriginalDecision(otherGeneration.decision())).isFalse(); + assertThat(candidate.matchesOriginalDecision(otherTarget.decision())).isFalse(); + assertThat(candidate.matchesProvisionalSources(preparedEvidence(otherBinding))).isFalse(); + assertThat(candidate.matchesProvisionalSources(preparedEvidence(otherGeneration))).isFalse(); + + assertThatThrownBy( + () -> + CanonicalGameplayOriginalNewCandidate.fromOriginalSources( + preparedEvidence(original), otherBinding.decision())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + CanonicalGameplayOriginalNewCandidate.fromOriginalSources( + preparedEvidence(original), otherGeneration.decision())) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void refusesResumeAndUnrecognizedTransitionStates() { + Bundle original = bundle(CHARACTER, BigInteger.valueOf(7), "World", false); + var resumeCarrier = + new LinkedHashMap<>( + leaseCarrier( + original.identity(), original.target(), false, original.bindingGeneration())); + resumeCarrier.put("leaseKind", "RESUME"); + resumeCarrier.put("resumeEpisodeId", id(90).toString()); + resumeCarrier.put("expectedOldBindingGeneration", "6"); + AccountGameplayAdmissionLeaseEvidence resumeLease = + AccountGameplayAdmissionLeaseEvidence.fromCarrier(resumeCarrier); + var resumeDecision = + new CanonicalGameplayAdmissionDecision( + original.decision().bindingDecisionId(), + resumeLease, + original.identity(), + BigInteger.valueOf(7), + BigInteger.valueOf(6), + original.target()); + assertThatThrownBy( + () -> + CanonicalGameplayOriginalNewCandidate.fromOriginalSources( + preparedEvidence(original), resumeDecision)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("public-production original NEW"); + + assertThatThrownBy(() -> evidenceWithStatus(original.identity(), "COMMITTED")) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void rejectsUnknownDuplicateMalformedOversizedNoncanonicalAndOutOfBoundInput() { + Bundle original = bundle(CHARACTER, BigInteger.valueOf(7), "World", false); + String canonical = + CanonicalGameplayOriginalNewCandidate.fromOriginalSources( + preparedEvidence(original), original.decision()) + .canonicalJson(); + + rejects(canonical.replace( + "\"purpose\":\"" + CanonicalGameplayOriginalNewCandidate.PURPOSE + "\"", + "\"purpose\":\"" + CanonicalGameplayOriginalNewCandidate.PURPOSE + "\",\"extra\":\"x\"")); + rejects(canonical.replace( + "\"purpose\":\"" + CanonicalGameplayOriginalNewCandidate.PURPOSE + "\"", + "\"purpose\":\"" + CanonicalGameplayOriginalNewCandidate.PURPOSE + "\",\"purpose\":\"" + + CanonicalGameplayOriginalNewCandidate.PURPOSE + "\"")); + rejects(canonical.replace( + "\"leaseKind\":\"NEW_BINDING\"", + "\"leaseKind\":\"NEW_BINDING\",\"leaseKind\":\"NEW_BINDING\"")); + rejects(" " + canonical); + rejects(canonical.replace("\"bindingGeneration\":\"7\"", "\"bindingGeneration\":\"07\"")); + rejects(canonical.replace("\"bindingDecisionId\":\"" + id(500) + "\"", "\"bindingDecisionId\":\"not-a-uuid\"")); + rejects("{"); + + byte[] canonicalBytes = canonical.getBytes(StandardCharsets.UTF_8); + byte[] malformedUtf8 = Arrays.copyOf(canonicalBytes, canonicalBytes.length + 1); + malformedUtf8[malformedUtf8.length - 1] = (byte) 0xff; + rejects(malformedUtf8); + rejects(new byte[CanonicalGameplayOriginalNewCandidateCodec.MAX_CANDIDATE_BYTES + 1]); + rejects( + canonical.replace( + "\"bindingGeneration\":\"7\"", "\"bindingGeneration\":\"" + "9".repeat(257) + "\"")); + } + + private static void rejects(String encoded) { + rejects(encoded.getBytes(StandardCharsets.UTF_8)); + } + + private static void rejects(byte[] encoded) { + assertThatThrownBy(() -> CanonicalGameplayOriginalNewCandidate.parseCanonical(encoded)) + .isInstanceOf(IllegalArgumentException.class); + } + + private static CanonicalGameplayBindingProvisionalCasEvidence preparedEvidence(Bundle bundle) { + return provisionalEvidence( + bundle.identity(), bundle.bindingGeneration(), BigInteger.valueOf(20), false); + } + + private static CanonicalGameplayBindingProvisionalCasEvidence provisionalEvidence( + CanonicalGameplayBindingIdentity identity, + BigInteger generation, + BigInteger inventoryRevision, + boolean provisional) { + return provisionalEvidence(identity, generation, inventoryRevision, provisional, BigInteger.valueOf(19)); + } + + private static CanonicalGameplayBindingProvisionalCasEvidence provisionalEvidence( + CanonicalGameplayBindingIdentity identity, + BigInteger generation, + BigInteger inventoryRevision, + boolean provisional, + BigInteger originalSnapshotRevision) { + UUID transitionId = id(500); + UUID reservationId = id(501); + UUID reservationFence = id(502); + UUID accountIndexFence = id(503); + CanonicalGameplayBindingInventoryEntry candidate = + new CanonicalGameplayBindingInventoryEntry( + identity, + identity.bindingRef(), + generation, + accountIndexFence, + reservationId, + transitionId, + provisional + ? CanonicalGameplayBindingInventoryEntry.Lifecycle.PROVISIONAL + : CanonicalGameplayBindingInventoryEntry.Lifecycle.CANDIDATE_PREPARED, + provisional + ? CanonicalGameplayBindingInventoryEntry.IndexState.ACKNOWLEDGED + : CanonicalGameplayBindingInventoryEntry.IndexState.REPAIR_REQUIRED, + CanonicalGameplayBindingInventoryEntry.IndexState.REPAIR_REQUIRED, + inventoryRevision); + CanonicalIssuerPartitionReservation reservation = + new CanonicalIssuerPartitionReservation( + reservationId, + identity, + generation, + transitionId, + identity.bindingRef().partitionId(identity.issuerIndexPartitionCount()), + CanonicalIssuerPartitionReservation.Lifecycle.RESERVED, + reservationFence, + id(504), + BigInteger.valueOf(2), + BigInteger.valueOf(3), + originalSnapshotRevision, + inventoryRevision); + CanonicalGameplayBindingTransitionSnapshot transition = + new CanonicalGameplayBindingTransitionSnapshot( + transitionId, + identity, + generation, + identity.bindingRef(), + inventoryRevision, + reservationId, + reservationFence, + accountIndexFence, + null, + null, + provisional + ? CanonicalGameplayBindingTransitionSnapshot.Status.PROVISIONAL + : CanonicalGameplayBindingTransitionSnapshot.Status.PREPARED, + CanonicalGameplayAccountCoverageEvidence.noActiveFlow()); + return new CanonicalGameplayBindingProvisionalCasEvidence( + transition, + candidate, + reservation, + null, + null, + new CanonicalGameplayLegacyMigrationDisposition( + id(505), + id(506), + id(507), + BigInteger.ONE, + BigInteger.TWO, + BigInteger.valueOf(3), + "sha256:" + "f".repeat(64))); + } + + private static CanonicalGameplayBindingProvisionalCasEvidence evidenceWithStatus( + CanonicalGameplayBindingIdentity identity, String status) { + UUID transitionId = id(500); + UUID reservationId = id(501); + UUID reservationFence = id(502); + UUID accountIndexFence = id(503); + var candidate = + new CanonicalGameplayBindingInventoryEntry( + identity, + identity.bindingRef(), + BigInteger.valueOf(7), + accountIndexFence, + reservationId, + transitionId, + CanonicalGameplayBindingInventoryEntry.Lifecycle.CANDIDATE_PREPARED, + CanonicalGameplayBindingInventoryEntry.IndexState.REPAIR_REQUIRED, + CanonicalGameplayBindingInventoryEntry.IndexState.REPAIR_REQUIRED, + BigInteger.valueOf(20)); + var reservation = + new CanonicalIssuerPartitionReservation( + reservationId, + identity, + BigInteger.valueOf(7), + transitionId, + identity.bindingRef().partitionId(identity.issuerIndexPartitionCount()), + CanonicalIssuerPartitionReservation.Lifecycle.RESERVED, + reservationFence, + id(504), + BigInteger.TWO, + BigInteger.valueOf(3), + BigInteger.valueOf(19), + BigInteger.valueOf(20)); + return new CanonicalGameplayBindingProvisionalCasEvidence( + new CanonicalGameplayBindingTransitionSnapshot( + transitionId, + identity, + BigInteger.valueOf(7), + identity.bindingRef(), + BigInteger.valueOf(20), + reservationId, + reservationFence, + accountIndexFence, + null, + null, + CanonicalGameplayBindingTransitionSnapshot.Status.valueOf(status), + CanonicalGameplayAccountCoverageEvidence.noActiveFlow()), + candidate, + reservation, + null, + null, + new CanonicalGameplayLegacyMigrationDisposition( + id(505), id(506), id(507), BigInteger.ONE, BigInteger.TWO, BigInteger.valueOf(3), + "sha256:" + "f".repeat(64))); + } + + private static Bundle bundle( + UUID characterId, BigInteger generation, String worldDisplayName, boolean alternateLease) { + CanonicalGameplayBindingIdentity identity = identity(characterId); + CanonicalPlayableTarget target = target(worldDisplayName); + AccountGameplayAdmissionLeaseEvidence lease = + AccountGameplayAdmissionLeaseEvidence.fromCarrier( + leaseCarrier(identity, target, alternateLease, generation)); + var decision = + new CanonicalGameplayAdmissionDecision( + id(500), lease, identity, generation, null, target); + return new Bundle(identity, generation, target, lease, decision); + } + + private static CanonicalGameplayBindingIdentity identity(UUID characterId) { + return new CanonicalGameplayBindingIdentity( + ACCOUNT, + TENANT, + NAMESPACE, + characterId, + "SHARED", + GAME_INSTANCE, + 41L, + SESSION.toString(), + REGION, + BigInteger.valueOf(5), + GameSessionAccountDelegationProfile.ISSUER, + BigInteger.ONE, + BigInteger.ONE, + BigInteger.valueOf(16), + BigInteger.valueOf(100)); + } + + private static CanonicalPlayableTarget target(String worldDisplayName) { + return new CanonicalPlayableTarget( + "test", + "tenant", + TENANT, + "world", + worldDisplayName, + REALM, + "production", + "Production", + 22L, + 41L, + NAMESPACE, + "SHARED", + GAME_INSTANCE, + VERSION, + 7L, + 3L, + 17L, + "d".repeat(64), + 1L, + "initial-request", + "a".repeat(64), + CanonicalInitialAdmissionRequest.OriginKind.NO_PRIOR_POINTER, + null, + id(30), + id(31), + "sha256:" + "b".repeat(64), + 9L, + "sha256:" + "c".repeat(64), + CanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED, + false, + Instant.parse("2026-10-26T12:00:00Z"), + "PRESEEDED"); + } + + private static Map leaseCarrier( + CanonicalGameplayBindingIdentity identity, + CanonicalPlayableTarget target, + boolean alternateLease, + BigInteger generation) { + Map carrier = new LinkedHashMap<>(); + carrier.put("schema", AccountGameplayAdmissionLeaseEvidence.SCHEMA); + carrier.put("schemaVersion", "1"); + carrier.put("mode", "PUBLIC_PRODUCTION"); + carrier.put("targetNamespace", "test"); + carrier.put("callerWorkload", "spiffe://firemud/ns/test/sa/game-session-service"); + carrier.put("requestId", id(alternateLease ? 701 : 700).toString()); + carrier.put("leaseId", id(alternateLease ? 703 : 702).toString()); + carrier.put("leaseFence", "11"); + carrier.put("leaseKind", "NEW_BINDING"); + carrier.put( + "bindingScope", + Map.ofEntries( + Map.entry("accountId", identity.accountId().toString()), + Map.entry("tenantId", identity.tenantId().toString()), + Map.entry("realmId", REALM.toString()), + Map.entry("worldSlug", "world"), + Map.entry("realmSlug", "production"), + Map.entry("playableStateNamespaceId", identity.playableStateNamespaceId().toString()), + Map.entry("playableStateScope", identity.playableStateScope()), + Map.entry("gameInstanceId", identity.gameInstanceId().toString()), + Map.entry("characterId", identity.characterId().toString()), + Map.entry("sessionId", identity.sessionId()), + Map.entry("bindingGeneration", generation.toString()), + Map.entry("catalogRevision", Long.toString(target.catalogRevision())), + Map.entry("pointerVersion", Long.toString(target.pointerVersion())), + Map.entry("regionId", identity.regionId().toString()), + Map.entry("regionEpoch", identity.regionEpoch().toString()))); + carrier.put( + "authorityTuple", + Map.of( + "issuerAuthGeneration", "1", + "accountAuthorityGeneration", "1", + "tenantAuthorityGeneration", Map.of(TENANT.toString(), "2"), + "membershipAuthorityGeneration", Map.of(TENANT.toString(), "3"), + "privateRealmGrantVersions", List.of())); + carrier.put("issuanceFence", "9"); + carrier.put( + "membershipBaseline", + Map.of( + "membershipLifecycleState", + "ACTIVE", + "membershipVersion", + Map.of(TENANT.toString(), "4"), + "membershipAuthorityGeneration", + "3")); + List streams = + new ArrayList<>( + List.of( + "account:auth-authority:v1:account/" + ACCOUNT, + "account:auth-authority:v1:issuer/" + GameSessionAccountDelegationProfile.ISSUER, + "account:auth-authority:v1:membership/" + ACCOUNT + "/" + TENANT, + "account:auth-authority:v1:tenant/" + TENANT)); + streams.sort(Comparator.naturalOrder()); + carrier.put( + "outboxCheckpoints", + streams.stream() + .map( + stream -> + Map.of( + "outboxStreamKey", stream, + "outboxSequence", + stream.contains("tenant/") || stream.contains("membership/") + ? "4" + : "0")) + .toList()); + carrier.put( + "tokenIdentityEvidence", + Map.ofEntries( + Map.entry("accountId", identity.accountId().toString()), + Map.entry("operationId", id(710).toString()), + Map.entry("issuanceRequestId", id(711).toString()), + Map.entry("tokenJti", id(712).toString()), + Map.entry("tokenSHA256", "a".repeat(64)), + Map.entry("tokenGeneration", "1"), + Map.entry("issuanceFence", "9"), + Map.entry("tokenIdentityFence", "1"), + Map.entry("tokenProfile", GameSessionAccountDelegationProfile.PROFILE), + Map.entry("issuedAt", "999"), + Map.entry("notBefore", "999"), + Map.entry("expiresAt", "1300"))); + carrier.put("evaluatedAt", "1000000"); + carrier.put("expiresAt", "1010000"); + return carrier; + } + + private static UUID id(long value) { + return new UUID(0L, value); + } + + private record Bundle( + CanonicalGameplayBindingIdentity identity, + BigInteger bindingGeneration, + CanonicalPlayableTarget target, + AccountGameplayAdmissionLeaseEvidence leaseEvidence, + CanonicalGameplayAdmissionDecision decision) {} +} From ddbe5a2d6617a90f1b2c4c1ac5be334f53769be9 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 27 Oct 2026 11:03:41 +1300 Subject: [PATCH 04/26] Repair local NEW owner compilation and proof fixtures --- ...ntInitialBarrierInitializerRepository.java | 74 ++- ...meplayAccountInitialBarrierRedisOwner.java | 36 +- ...calGameplayAccountInitialBarrierValue.java | 6 +- ...onicalGameplayAccountInitialOpenProof.java | 11 +- ...icalGameplayIssuerAdmissionBarrierKey.java | 7 +- ...eplayIssuerAdmissionBarrierRedisOwner.java | 125 +++-- ...suerAdmissionBarrierRedisOwnerFactory.java | 3 +- ...eplayIssuerAdmissionBarrierRepository.java | 137 ++--- ...alGameplayIssuerAdmissionBarrierValue.java | 185 +++++-- ...eplayIssuerAdmissionControlRepository.java | 252 +++++---- ...alGameplayIssuerAdmissionControlValue.java | 150 ++++-- ...CanonicalGameplayOriginalNewCandidate.java | 12 +- ...icalGameplayOriginalNewCandidateCodec.java | 40 +- ...lGameplayProtectedIncarnationReceiver.java | 13 +- ...alGameplayTenantGameplayTagRepository.java | 6 +- ...missionBarrierRedisScriptContribution.java | 3 +- ...anonical_issuer_live_admission_control.sql | 4 +- ...ssionBarrierRepositoryIntegrationTest.java | 28 +- ...tialBarrierRedisScriptIntegrationTest.java | 52 +- ...ssionBarrierRepositoryIntegrationTest.java | 169 ++++--- ...nationReceiverPostgresIntegrationTest.java | 478 +++++++++--------- ...ayAccountInitialBarrierRedisOwnerTest.java | 93 ++-- ...ameplayAccountInitialBarrierValueTest.java | 42 +- ...nicalGameplayOriginalNewCandidateTest.java | 74 ++- 24 files changed, 1232 insertions(+), 768 deletions(-) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierInitializerRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierInitializerRepository.java index 278456cd22..d446efc9f7 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierInitializerRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierInitializerRepository.java @@ -49,7 +49,8 @@ final class CanonicalGameplayAccountInitialBarrierInitializerRepository { /** * Captures one exact initial target under the same inventory-clock then account-control order - * used by account-wide acquisition. The Account account id is taken from the authenticated result. + * used by account-wide acquisition. The Account account id is taken from the authenticated + * result. */ InitializerSnapshot beginOrRead( InitialGameplayLoginAttemptCoordinates original, @@ -72,7 +73,8 @@ InitializerSnapshot beginOrRead( Record control = lockExistingControl(transaction, accountEvidence.accountId()); AccountControlSource source = readNoActiveControl(control, accountEvidence.accountId()); if (inventoryRevision.signum() <= 0) { - throw conflict("Initial account barrier requires positive canonical inventory revision"); + throw conflict( + "Initial account barrier requires positive canonical inventory revision"); } requireExactOriginalLogin(transaction, original, accountEvidence); @@ -150,7 +152,8 @@ InitialObservationContext readCurrentObservationContext(UUID originalRequestId) Record row = readInitializer(transaction, originalRequestId, false); if (row == null) throw conflict("Exact original INITIAL account target is missing"); InitializerSnapshot snapshot = toSnapshot(row); - AccountControlSource current = readCurrentNoActiveControl(transaction, snapshot.accountId()); + AccountControlSource current = + readCurrentNoActiveControl(transaction, snapshot.accountId()); requireSameCurrentSource(snapshot, current); requireOriginalJournalStillCurrent(transaction, snapshot); return InitialObservationContext.from(snapshot); @@ -165,7 +168,8 @@ InitializerSnapshot readCurrent(UUID originalRequestId) { DSLContext transaction = DSL.using(configuration); transaction.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY"); InitializerSnapshot snapshot = readRequiredCurrent(transaction, originalRequestId, false); - AccountControlSource current = readCurrentNoActiveControl(transaction, snapshot.accountId()); + AccountControlSource current = + readCurrentNoActiveControl(transaction, snapshot.accountId()); requireSameCurrentSource(snapshot, current); requireOriginalJournalStillCurrent(transaction, snapshot); return snapshot; @@ -235,8 +239,7 @@ InitializerSnapshot recordDispatchPossible( * admission decision. */ InitializerSnapshot acceptOpenReadback( - UUID originalRequestId, - CanonicalGameplayAccountInitialBarrierRedisOwner.Readback readback) { + UUID originalRequestId, CanonicalGameplayAccountInitialBarrierRedisOwner.Readback readback) { requireNonNil(originalRequestId, "originalRequestId"); Objects.requireNonNull(readback, "readback"); requireNoAmbientTransaction(); @@ -320,7 +323,8 @@ void requireNoAmbientTransaction() { } } - private static void requireReadback(CanonicalGameplayAccountInitialBarrierRedisOwner.Readback readback) { + private static void requireReadback( + CanonicalGameplayAccountInitialBarrierRedisOwner.Readback readback) { CanonicalGameplayProtectedIncarnationReceiver.VerifiedIncarnation before = readback.beforeIncarnation(); CanonicalGameplayProtectedIncarnationReceiver.VerifiedIncarnation after = @@ -329,10 +333,12 @@ private static void requireReadback(CanonicalGameplayAccountInitialBarrierRedisO || !CanonicalGameplayAccountInitialBarrierValue.FIELDS.equals( readback.barrierFields().keySet()) || !"OPEN".equals(readback.barrierFields().get("state")) - || !readback.beforeIncarnation() + || !readback + .beforeIncarnation() .sourceControlEpoch() .equals(readback.barrierFields().get("ownerFenceEpoch")) - || !readback.afterIncarnation() + || !readback + .afterIncarnation() .sourceControlEpoch() .equals(readback.barrierFields().get("ownerFenceEpoch")) || !before.incarnationDigest().equals(after.incarnationDigest()) @@ -356,7 +362,8 @@ private static void requireSameReadbackContext( || !current.accountLoginEvidenceDigest().equals(readback.accountLoginEvidenceDigest()) || !current.sourceControlDigest().equals(readback.sourceControlDigest()) || !current.inventorySnapshotRevision().equals(readback.inventorySnapshotRevision()) - || !readback.key() + || !readback + .key() .equals( CanonicalGameplayAccountInitialBarrierKey.forTarget( readback.assignment(), current.initializerId(), current.originalRequestId()))) { @@ -367,7 +374,8 @@ private static void requireSameReadbackContext( || !current.accountId().toString().equals(fields.get("accountId")) || !current.sourceControlEpoch().toString().equals(fields.get("ownerFenceEpoch")) || !current.tenantId().toString().equals(fields.get("tenantId")) - || !current.playableStateNamespaceId() + || !current + .playableStateNamespaceId() .toString() .equals(fields.get("playableStateNamespaceId")) || !readback.assignment().tenantGameplayTag().equals(fields.get("tenantGameplayTag"))) { @@ -389,7 +397,9 @@ private static void requireInitialObservationMatches( || !snapshot.playableStateNamespaceId().equals(observation.playableStateNamespaceId()) || !NO_ACTIVE.equals(observation.sourceControlState()) || !snapshot.sourceControlEpoch().toString().equals(observation.sourceControlEpoch()) - || !snapshot.inventorySnapshotRevision().toString() + || !snapshot + .inventorySnapshotRevision() + .toString() .equals(observation.inventorySnapshotRevision()) || !snapshot.accountLoginEvidenceDigest().equals(observation.accountLoginEvidenceDigest()) || !snapshot.sourceControlDigest().equals(observation.sourceControlDigest()) @@ -498,10 +508,13 @@ private static InitialObservationContext context(InitializerSnapshot snapshot) { private static BigInteger lockInventoryRevision(DSLContext transaction) { Record row = transaction.fetchOne( - "SELECT inventory_revision FROM " + INVENTORY_CLOCK + " WHERE singleton_id = 1 FOR UPDATE"); + "SELECT inventory_revision FROM " + + INVENTORY_CLOCK + + " WHERE singleton_id = 1 FOR UPDATE"); if (row == null) throw conflict("Canonical binding inventory clock is missing"); BigInteger revision = readBigInteger(row, "inventory_revision"); - if (revision.signum() <= 0) throw conflict("Initial account barrier inventory revision is not positive"); + if (revision.signum() <= 0) + throw conflict("Initial account barrier inventory revision is not positive"); return revision; } @@ -509,14 +522,17 @@ private static Record lockExistingControl(DSLContext transaction, UUID accountId Record row = transaction.fetchOne( "SELECT * FROM " + CONTROL + " WHERE account_id = ? FOR UPDATE", accountId); - if (row == null) throw conflict("Account coverage control row is missing; absence is not source"); + if (row == null) + throw conflict("Account coverage control row is missing; absence is not source"); return row; } private static AccountControlSource readCurrentNoActiveControl( DSLContext transaction, UUID accountId) { - Record row = transaction.fetchOne("SELECT * FROM " + CONTROL + " WHERE account_id = ?", accountId); - if (row == null) throw conflict("Account coverage control row is missing; absence is not source"); + Record row = + transaction.fetchOne("SELECT * FROM " + CONTROL + " WHERE account_id = ?", accountId); + if (row == null) + throw conflict("Account coverage control row is missing; absence is not source"); return readNoActiveControl(row, accountId); } @@ -550,13 +566,15 @@ private static String digestControl(Record row) { fields.put("currentFenceIntentId", uuidText(row, "current_fence_intent_id")); fields.put("currentOperationFence", nullableInteger(row, "current_operation_fence")); fields.put("accountAdmissionFence", uuidText(row, "account_admission_fence")); - fields.put("historicalAccountAdmissionFence", uuidText(row, "historical_account_admission_fence")); + fields.put( + "historicalAccountAdmissionFence", uuidText(row, "historical_account_admission_fence")); fields.put("coverageFence", uuidText(row, "coverage_fence")); fields.put("inventorySnapshotRevision", nullableInteger(row, "inventory_snapshot_revision")); fields.put("coverageGeneration", nullableInteger(row, "coverage_generation")); try { - return digest(net.firedevops.firemud.common.json.Rfc8785CanonicalJson.canonicalizeUtf8( - JSON.writeValueAsString(fields))); + return digest( + net.firedevops.firemud.common.json.Rfc8785CanonicalJson.canonicalizeUtf8( + JSON.writeValueAsString(fields))); } catch (Exception invalid) { throw conflict("Account control source digest could not be computed"); } @@ -581,8 +599,9 @@ private static String digestAccountEvidence(CanonicalGameplayLoginResult.NonSecr "outboxSourceEventEvidenceCanonicalJson", e.outboxSourceEventEvidenceCanonicalJson().toStringUtf8()); try { - return digest(net.firedevops.firemud.common.json.Rfc8785CanonicalJson.canonicalizeUtf8( - JSON.writeValueAsString(fields))); + return digest( + net.firedevops.firemud.common.json.Rfc8785CanonicalJson.canonicalizeUtf8( + JSON.writeValueAsString(fields))); } catch (Exception invalid) { throw conflict("Authenticated Account response evidence digest could not be computed"); } @@ -611,8 +630,9 @@ private static String digestFields(Map fields) { private static String digestUnchecked(Object fields) { try { - return digest(net.firedevops.firemud.common.json.Rfc8785CanonicalJson.canonicalizeUtf8( - JSON.writeValueAsString(fields))); + return digest( + net.firedevops.firemud.common.json.Rfc8785CanonicalJson.canonicalizeUtf8( + JSON.writeValueAsString(fields))); } catch (Exception invalid) { throw conflict("Canonical INITIAL source digest could not be computed"); } @@ -620,7 +640,8 @@ private static String digestUnchecked(Object fields) { private static String digest(byte[] bytes) { try { - return "sha256:" + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); } catch (NoSuchAlgorithmException impossible) { throw new IllegalStateException("SHA-256 is unavailable", impossible); } @@ -748,7 +769,8 @@ private static UUID randomNonNilUuid() { private static void requireNonNil(UUID value, String name) { Objects.requireNonNull(value, name); - if (value.equals(new UUID(0L, 0L))) throw new IllegalArgumentException(name + " must not be nil"); + if (value.equals(new UUID(0L, 0L))) + throw new IllegalArgumentException(name + " must not be nil"); } private static void requireOne(int actual, String message) { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierRedisOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierRedisOwner.java index ede8711830..62efba8ed2 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierRedisOwner.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierRedisOwner.java @@ -94,7 +94,8 @@ final class CanonicalGameplayAccountInitialBarrierRedisOwner { /** * Starts one original-attempt target or performs read-only same-original verification. The SQL - * DISPATCH_POSSIBLE state commits before the only Redis write call; every later path is read-only. + * DISPATCH_POSSIBLE state commits before the only Redis write call; every later path is + * read-only. */ CanonicalGameplayAccountInitialOpenProof initializeOnce( InitialGameplayLoginAttemptCoordinates original, @@ -148,7 +149,7 @@ CanonicalGameplayAccountInitialOpenProof verifyCurrentOpen(UUID originalRequestI return refused(CanonicalGameplayAccountInitialOpenProof.Reason.TARGET_NEVER_DISPATCHED); } if (snapshot.state() - == CanonicalGameplayAccountInitialBarrierInitializerRepository.State.DISPATCH_POSSIBLE + == CanonicalGameplayAccountInitialBarrierInitializerRepository.State.DISPATCH_POSSIBLE && snapshot.beforeIncarnationDigest() == null) { return refused(CanonicalGameplayAccountInitialOpenProof.Reason.REMOTE_OUTCOME_UNCERTAIN); } @@ -160,8 +161,11 @@ CanonicalGameplayAccountInitialOpenProof verifyCurrentOpen(UUID originalRequestI incarnationReceiver.observeForInitialAccountBarrier(originalRequestId); requireObservation(snapshot, before); if (!before.incarnationDigest().equals(snapshot.beforeIncarnationDigest()) - || !before.acceptedAttestationDigest().equals(snapshot.beforeAcceptedAttestationDigest())) { - return refused(CanonicalGameplayAccountInitialOpenProof.Reason.PROTECTED_OBSERVATION_UNAVAILABLE); + || !before + .acceptedAttestationDigest() + .equals(snapshot.beforeAcceptedAttestationDigest())) { + return refused( + CanonicalGameplayAccountInitialOpenProof.Reason.PROTECTED_OBSERVATION_UNAVAILABLE); } CanonicalGameplayAccountInitialBarrierValue value = CanonicalGameplayAccountInitialBarrierValue.open( @@ -183,19 +187,12 @@ CanonicalGameplayAccountInitialOpenProof verifyCurrentOpen(UUID originalRequestI || !before.acceptedAttestationDigest().equals(after.acceptedAttestationDigest()) || after.issuedAtEpochMillis() < before.issuedAtEpochMillis() || after.observedAtEpochMillis() < before.observedAtEpochMillis()) { - return refused(CanonicalGameplayAccountInitialOpenProof.Reason.PROTECTED_OBSERVATION_UNAVAILABLE); + return refused( + CanonicalGameplayAccountInitialOpenProof.Reason.PROTECTED_OBSERVATION_UNAVAILABLE); } Readback readback = - new Readback( - snapshot, - assignment, - key, - value, - physical, - before, - after, - 0L); + new Readback(snapshot, assignment, key, value, physical, before, after, 0L); if (snapshot.state() == CanonicalGameplayAccountInitialBarrierInitializerRepository.State.OPEN_INSTALLED) { var current = repository.readCurrent(originalRequestId); @@ -281,7 +278,9 @@ private static void requireObservation( || !snapshot.playableStateNamespaceId().equals(observation.playableStateNamespaceId()) || !"NO_ACTIVE_ACCOUNT_WIDE_FLOW".equals(observation.sourceControlState()) || !snapshot.sourceControlEpoch().toString().equals(observation.sourceControlEpoch()) - || !snapshot.inventorySnapshotRevision().toString() + || !snapshot + .inventorySnapshotRevision() + .toString() .equals(observation.inventorySnapshotRevision()) || !snapshot.accountLoginEvidenceDigest().equals(observation.accountLoginEvidenceDigest()) || !snapshot.sourceControlDigest().equals(observation.sourceControlDigest()) @@ -308,7 +307,8 @@ private Map readExactPhysicalState( for (Map.Entry entry : raw.entrySet()) { String field = asciiString(entry.getKey()); String value = asciiString(Objects.requireNonNull(entry.getValue())); - if (!FIELDS.contains(field) || actual.putIfAbsent(field, value) != null) throw unavailable(); + if (!FIELDS.contains(field) || actual.putIfAbsent(field, value) != null) + throw unavailable(); } if (!expected.fields().equals(actual)) throw unavailable(); return Map.copyOf(actual); @@ -326,7 +326,9 @@ private long writeOneKey(byte[] script, String key, byte[]... arguments) { String sha = await(commands.scriptLoad(script)); if (!digest("SHA-1", script).equals(sha)) throw unavailable(); Long reply = - await(commands.evalsha(sha, ScriptOutputType.INTEGER, new byte[][] {ascii(key)}, arguments)); + await( + commands.evalsha( + sha, ScriptOutputType.INTEGER, new byte[][] {ascii(key)}, arguments)); if (reply == null) throw unavailable(); return reply; } catch (RuntimeException failure) { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierValue.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierValue.java index 67ecd3714a..e387d9bdfd 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierValue.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierValue.java @@ -1,13 +1,15 @@ package net.firedevops.firemud.gamesession.repository; +import java.math.BigInteger; import java.util.LinkedHashMap; import java.util.Map; import java.util.Objects; import java.util.Set; -import java.math.BigInteger; import java.util.UUID; -/** Exact nine-field physical INITIAL OPEN value; it carries no later Account or issuer authority. */ +/** + * Exact nine-field physical INITIAL OPEN value; it carries no later Account or issuer authority. + */ final class CanonicalGameplayAccountInitialBarrierValue { static final String SCHEMA = "gs_account_admission_barrier/v1"; static final String OPEN = "OPEN"; diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialOpenProof.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialOpenProof.java index 3a7f270eeb..91366a7cdc 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialOpenProof.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialOpenProof.java @@ -5,7 +5,9 @@ import java.util.Objects; import java.util.UUID; -/** Owner-issued current OPEN proof, or a typed refusal that cannot be used as admission evidence. */ +/** + * Owner-issued current OPEN proof, or a typed refusal that cannot be used as admission evidence. + */ sealed interface CanonicalGameplayAccountInitialOpenProof permits CanonicalGameplayAccountInitialOpenProof.CurrentOpen, CanonicalGameplayAccountInitialOpenProof.Refused { @@ -27,7 +29,7 @@ record CurrentOpen( long expiresAtEpochMillis, Map exactFields) implements CanonicalGameplayAccountInitialOpenProof { - CurrentOpen { + public CurrentOpen { Objects.requireNonNull(initializerId, "initializerId"); Objects.requireNonNull(originalRequestId, "originalRequestId"); Objects.requireNonNull(originalCallerContextId, "originalCallerContextId"); @@ -53,7 +55,8 @@ record CurrentOpen( || !initializerId.toString().equals(exactFields.get("ownerOperationId")) || !accountId.toString().equals(exactFields.get("accountId")) || !tenantId.toString().equals(exactFields.get("tenantId")) - || !playableStateNamespaceId.toString() + || !playableStateNamespaceId + .toString() .equals(exactFields.get("playableStateNamespaceId")) || !incarnationDigest.equals(exactFields.get("incarnationDigest"))) { throw new IllegalArgumentException("Current INITIAL OPEN proof is malformed"); @@ -62,7 +65,7 @@ record CurrentOpen( } record Refused(Reason reason) implements CanonicalGameplayAccountInitialOpenProof { - Refused { + public Refused { Objects.requireNonNull(reason, "reason"); } } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierKey.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierKey.java index afbf82071a..9a0a8c66a5 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierKey.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierKey.java @@ -21,10 +21,11 @@ static String forTarget(String issuerId, UUID tenantId, UUID namespaceId, String Objects.requireNonNull(tenantId, "tenantId"); Objects.requireNonNull(namespaceId, "playableStateNamespaceId"); Objects.requireNonNull(tag, "tenantGameplayTag"); - if (!net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile.ISSUER - .equals(issuerId) + if (!net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile.ISSUER.equals( + issuerId) || !tag.matches("g[1-9][0-9]{0,9}-[0-9a-f]{32}")) { - throw new IllegalArgumentException("Issuer barrier key requires exact Account issuer placement"); + throw new IllegalArgumentException( + "Issuer barrier key requires exact Account issuer placement"); } return "session:game:issuer-admission:{" + tag diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRedisOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRedisOwner.java index 248c302bb0..6efd37cd84 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRedisOwner.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRedisOwner.java @@ -7,7 +7,6 @@ import io.lettuce.core.codec.ByteArrayCodec; import java.io.IOException; import java.io.InputStream; -import java.math.BigInteger; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.util.Arrays; @@ -61,7 +60,8 @@ final class CanonicalGameplayIssuerAdmissionBarrierRedisOwner { currentStateSource) { this.redisClient = Objects.requireNonNull(redisClient, "Configured Redis client is required"); this.catalog = Objects.requireNonNull(catalog, "Manual Redis script catalog is required"); - this.repository = Objects.requireNonNull(repository, "Actual SQL projection repository is required"); + this.repository = + Objects.requireNonNull(repository, "Actual SQL projection repository is required"); this.currentStateSource = Objects.requireNonNull(currentStateSource, "Fresh issuer source is required"); } @@ -75,11 +75,12 @@ Readback initializeAndRead(UUID operationId) { requireCurrentState(prepared.value().initializer()); repository.requireStillCurrent(prepared); String createMode = prepared.consumeCreatePermit() ? "CREATE_ONCE" : "REPLAY_ONLY"; - RedisScriptDescriptor descriptor = requireDescriptor( - CanonicalGameplayIssuerAdmissionBarrierRedisScriptContribution.OPEN_SCRIPT_ID, - CanonicalGameplayIssuerAdmissionBarrierRedisScriptContribution.OPEN_RESOURCE_PATH, - OPEN_ARGUMENTS, - OPEN_OUTCOMES); + RedisScriptDescriptor descriptor = + requireDescriptor( + CanonicalGameplayIssuerAdmissionBarrierRedisScriptContribution.OPEN_SCRIPT_ID, + CanonicalGameplayIssuerAdmissionBarrierRedisScriptContribution.OPEN_RESOURCE_PATH, + OPEN_ARGUMENTS, + OPEN_OUTCOMES); byte[] script = scriptSource(descriptor); CanonicalGameplayIssuerAdmissionBarrierValue value = prepared.value(); byte[] payload = value.exactBytes(); @@ -121,11 +122,12 @@ Readback closeAndRead(UUID operationId, UUID tenantId, UUID namespaceId) { PreparedCutoffTarget prepared = repository.readPreparedCutoffTarget(operationId, tenantId, namespaceId); repository.requireStillCurrent(prepared); - RedisScriptDescriptor descriptor = requireDescriptor( - CanonicalGameplayIssuerAdmissionBarrierRedisScriptContribution.CLOSE_SCRIPT_ID, - CanonicalGameplayIssuerAdmissionBarrierRedisScriptContribution.CLOSE_RESOURCE_PATH, - CLOSE_ARGUMENTS, - CLOSE_OUTCOMES); + RedisScriptDescriptor descriptor = + requireDescriptor( + CanonicalGameplayIssuerAdmissionBarrierRedisScriptContribution.CLOSE_SCRIPT_ID, + CanonicalGameplayIssuerAdmissionBarrierRedisScriptContribution.CLOSE_RESOURCE_PATH, + CLOSE_ARGUMENTS, + CLOSE_OUTCOMES); byte[] script = scriptSource(descriptor); CanonicalGameplayIssuerAdmissionBarrierValue closed = prepared.closedValue(); CanonicalGameplayIssuerAdmissionBarrierValue.Initializer initializer = closed.initializer(); @@ -191,7 +193,8 @@ private byte[] readExactPhysicalState( for (Map.Entry entry : raw.entrySet()) { String field = asciiString(entry.getKey()); if (!FIELDS.contains(field) - || actual.putIfAbsent(field, Objects.requireNonNull(entry.getValue()).clone()) != null) { + || actual.putIfAbsent(field, Objects.requireNonNull(entry.getValue()).clone()) + != null) { throw unavailable(); } } @@ -222,10 +225,7 @@ private long writeOneKey(byte[] script, String key, byte[]... arguments) { Long reply = await( commands.evalsha( - sha, - ScriptOutputType.INTEGER, - new byte[][] {ascii(key)}, - arguments)); + sha, ScriptOutputType.INTEGER, new byte[][] {ascii(key)}, arguments)); if (reply == null) throw unavailable(); return reply; } catch (RuntimeException failure) { @@ -297,9 +297,14 @@ private static Map physicalFields( fields.put("state", ascii(value.state().name())); fields.put("admissionEpoch", ascii(value.admissionEpoch().toString())); fields.put("ownerOperationId", ascii(value.ownerOperationId().toString())); - fields.put("initializerOperationId", ascii(initializer == null ? "none" : initializer.operationId().toString())); - fields.put("initializerEpoch", ascii(initializer == null ? "0" : initializer.admissionEpoch().toString())); - fields.put("initializerDigest", ascii(initializer == null ? "none" : initializer.exactDigest())); + fields.put( + "initializerOperationId", + ascii(initializer == null ? "none" : initializer.operationId().toString())); + fields.put( + "initializerEpoch", + ascii(initializer == null ? "0" : initializer.admissionEpoch().toString())); + fields.put( + "initializerDigest", ascii(initializer == null ? "none" : initializer.exactDigest())); fields.put("payloadDigest", ascii(value.exactDigest())); fields.put("payload", value.exactBytes()); return fields; @@ -384,15 +389,25 @@ private static IllegalStateException unavailable(Throwable cause) { new RedisScriptDescriptor.ArgumentSpec("createMode")); private static final List OPEN_OUTCOMES = List.of( - outcome("OPEN_CREATED", RedisScriptDescriptor.OutcomeCategory.SUCCESS, + outcome( + "OPEN_CREATED", + RedisScriptDescriptor.OutcomeCategory.SUCCESS, RedisScriptDescriptor.MutationEffect.MUTATING), - outcome("OPEN_REPLAY", RedisScriptDescriptor.OutcomeCategory.REPLAY, + outcome( + "OPEN_REPLAY", + RedisScriptDescriptor.OutcomeCategory.REPLAY, RedisScriptDescriptor.MutationEffect.NON_MUTATING), - outcome("TYPE_TTL_OR_FIELDSET_REFUSED", RedisScriptDescriptor.OutcomeCategory.VALIDATION_FAILURE, + outcome( + "TYPE_TTL_OR_FIELDSET_REFUSED", + RedisScriptDescriptor.OutcomeCategory.VALIDATION_FAILURE, RedisScriptDescriptor.MutationEffect.NON_MUTATING), - outcome("INVALID_ARGUMENTS_OR_TARGET", RedisScriptDescriptor.OutcomeCategory.VALIDATION_FAILURE, + outcome( + "INVALID_ARGUMENTS_OR_TARGET", + RedisScriptDescriptor.OutcomeCategory.VALIDATION_FAILURE, RedisScriptDescriptor.MutationEffect.NON_MUTATING), - outcome("CLOSED_OR_CONFLICTING_STATE", RedisScriptDescriptor.OutcomeCategory.STALE, + outcome( + "CLOSED_OR_CONFLICTING_STATE", + RedisScriptDescriptor.OutcomeCategory.STALE, RedisScriptDescriptor.MutationEffect.NON_MUTATING)); private static final List CLOSE_ARGUMENTS = List.of( @@ -412,17 +427,29 @@ private static IllegalStateException unavailable(Throwable cause) { new RedisScriptDescriptor.ArgumentSpec("state")); private static final List CLOSE_OUTCOMES = List.of( - outcome("CLOSED_CREATED", RedisScriptDescriptor.OutcomeCategory.SUCCESS, + outcome( + "CLOSED_CREATED", + RedisScriptDescriptor.OutcomeCategory.SUCCESS, RedisScriptDescriptor.MutationEffect.MUTATING), - outcome("CLOSED_REPLAY", RedisScriptDescriptor.OutcomeCategory.REPLAY, + outcome( + "CLOSED_REPLAY", + RedisScriptDescriptor.OutcomeCategory.REPLAY, RedisScriptDescriptor.MutationEffect.NON_MUTATING), - outcome("CAPTURED_OPEN_CLOSED", RedisScriptDescriptor.OutcomeCategory.SUCCESS, + outcome( + "CAPTURED_OPEN_CLOSED", + RedisScriptDescriptor.OutcomeCategory.SUCCESS, RedisScriptDescriptor.MutationEffect.MUTATING), - outcome("TYPE_TTL_OR_FIELDSET_REFUSED", RedisScriptDescriptor.OutcomeCategory.VALIDATION_FAILURE, + outcome( + "TYPE_TTL_OR_FIELDSET_REFUSED", + RedisScriptDescriptor.OutcomeCategory.VALIDATION_FAILURE, RedisScriptDescriptor.MutationEffect.NON_MUTATING), - outcome("INVALID_ARGUMENTS_OR_TARGET", RedisScriptDescriptor.OutcomeCategory.VALIDATION_FAILURE, + outcome( + "INVALID_ARGUMENTS_OR_TARGET", + RedisScriptDescriptor.OutcomeCategory.VALIDATION_FAILURE, RedisScriptDescriptor.MutationEffect.NON_MUTATING), - outcome("NEWER_CLOSED_OR_UNEXPECTED_STATE", RedisScriptDescriptor.OutcomeCategory.STALE, + outcome( + "NEWER_CLOSED_OR_UNEXPECTED_STATE", + RedisScriptDescriptor.OutcomeCategory.STALE, RedisScriptDescriptor.MutationEffect.NON_MUTATING)); private static RedisScriptDescriptor.OutcomeSpec outcome( @@ -482,10 +509,21 @@ static final class PreparedInitializer { } } - CanonicalGameplayIssuerAdmissionBarrierValue value() { return value; } - CanonicalGameplayTenantGameplayTagRepository.Assignment assignment() { return assignment; } - UUID requestOperationId() { return requestOperationId; } - String key() { return key; } + CanonicalGameplayIssuerAdmissionBarrierValue value() { + return value; + } + + CanonicalGameplayTenantGameplayTagRepository.Assignment assignment() { + return assignment; + } + + UUID requestOperationId() { + return requestOperationId; + } + + String key() { + return key; + } /** Consumes the SQL owner's first-attempt authority before any Redis command is attempted. */ boolean consumeCreatePermit() { @@ -502,7 +540,8 @@ record PreparedCutoffTarget( Objects.requireNonNull(key, "key"); if (closedValue.state() != CanonicalGameplayIssuerAdmissionBarrierValue.State.CLOSED || (expectedOpenValue != null - && (expectedOpenValue.state() != CanonicalGameplayIssuerAdmissionBarrierValue.State.OPEN + && (expectedOpenValue.state() + != CanonicalGameplayIssuerAdmissionBarrierValue.State.OPEN || closedValue.initializer() == null || !Arrays.equals( closedValue.initializer().exactBytes(), @@ -532,8 +571,16 @@ private Readback( if (!Arrays.equals(value.exactBytes(), this.exactPhysicalPayload)) throw unavailable(); } - CanonicalGameplayIssuerAdmissionBarrierValue value() { return value; } - long scriptOutcome() { return scriptOutcome; } - byte[] exactPhysicalPayload() { return exactPhysicalPayload.clone(); } + CanonicalGameplayIssuerAdmissionBarrierValue value() { + return value; + } + + long scriptOutcome() { + return scriptOutcome; + } + + byte[] exactPhysicalPayload() { + return exactPhysicalPayload.clone(); + } } } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRedisOwnerFactory.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRedisOwnerFactory.java index edc2ee96b2..3f9a3acfa3 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRedisOwnerFactory.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRedisOwnerFactory.java @@ -12,7 +12,8 @@ static CanonicalGameplayIssuerAdmissionBarrierRedisOwner create( RedisClient redisClient, RedisScriptCatalog catalog, CanonicalGameplayIssuerAdmissionBarrierRedisOwner.ProjectionRepository repository, - CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerStateSource currentStateSource) { + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerStateSource + currentStateSource) { return new CanonicalGameplayIssuerAdmissionBarrierRedisOwner( Objects.requireNonNull(redisClient, "redisClient"), Objects.requireNonNull(catalog, "catalog"), diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepository.java index 9202005e73..35c69a26d0 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepository.java @@ -50,8 +50,7 @@ final class CanonicalGameplayIssuerAdmissionBarrierRepository requireNoAmbientTransaction(); Record originalOperationInitializer = dsl.fetchOne( - "SELECT operation_id FROM " + INITIALIZER - + " WHERE operation_id = ? AND issuer_id = ?", + "SELECT operation_id FROM " + INITIALIZER + " WHERE operation_id = ? AND issuer_id = ?", operationId, ISSUER); CanonicalGameplayTenantGameplayTagRepository.Assignment requestAssignment = @@ -79,14 +78,14 @@ final class CanonicalGameplayIssuerAdmissionBarrierRepository transaction, anchor, before); Record byOperation = transaction.fetchOne( - "SELECT * FROM " + INITIALIZER + "SELECT * FROM " + + INITIALIZER + " WHERE operation_id = ? AND issuer_id = ? FOR UPDATE", operationId, ISSUER); if (byOperation != null) { CanonicalGameplayIssuerAdmissionBarrierValue frozen = - readFrozenInitializer( - transaction, byOperation, null, anchor, control, before); + readFrozenInitializer(transaction, byOperation, null, anchor, control, before); if (requestAssignment != null) { requireSameTargetAssignment(requestAssignment, frozen.initializer()); } @@ -97,11 +96,11 @@ final class CanonicalGameplayIssuerAdmissionBarrierRepository } CurrentRequestTarget requestTarget = - requireCurrentRequestTarget( - transaction, operationId, requestAssignment, before); + requireCurrentRequestTarget(transaction, operationId, requestAssignment, before); Record targetInitializer = transaction.fetchOne( - "SELECT * FROM " + INITIALIZER + "SELECT * FROM " + + INITIALIZER + " WHERE issuer_id = ? AND tenant_id = ?" + " AND playable_state_namespace_id = ? AND live_barrier_epoch = ?" + " FOR UPDATE", @@ -182,7 +181,8 @@ CanonicalGameplayIssuerAdmissionControlValue completeCutoff(UUID operationId) { requireNonNil(cutoffOperationId, "cutoffOperationId"); List targets = dsl.fetch( - "SELECT tenant_id, playable_state_namespace_id FROM " + CUTOFF_TARGET + "SELECT tenant_id, playable_state_namespace_id FROM " + + CUTOFF_TARGET + " WHERE operation_id = ? AND issuer_id = ? ORDER BY target_ordinal", cutoffOperationId, ISSUER); @@ -225,7 +225,8 @@ CanonicalGameplayIssuerAdmissionControlValue completeCutoff(UUID operationId) { .verifyCurrentCutoffTarget(transaction, control, tenantId, namespaceId, null); Record target = transaction.fetchOne( - "SELECT * FROM " + CUTOFF_TARGET + "SELECT * FROM " + + CUTOFF_TARGET + " WHERE operation_id = ? AND issuer_id = ? AND tenant_id = ?" + " AND playable_state_namespace_id = ? FOR UPDATE", cutoffOperationId, @@ -297,7 +298,8 @@ public void requireStillCurrent( } Record saved = transaction.fetchOne( - "SELECT * FROM " + INITIALIZER + "SELECT * FROM " + + INITIALIZER + " WHERE operation_id = ? AND issuer_id = ? FOR UPDATE", initializer.operationId(), ISSUER); @@ -336,8 +338,7 @@ public void requireStillCurrent( closed.tenantId(), closed.playableStateNamespaceId(), closed.exactBytes()); - requireCurrentTagMapping( - transaction, closed.tenantId(), closed.tenantGameplayTag()); + requireCurrentTagMapping(transaction, closed.tenantId(), closed.tenantGameplayTag()); return null; }); } @@ -369,7 +370,8 @@ public void recordOpenReadback( transaction, anchor, current); Record initializer = transaction.fetchOne( - "SELECT * FROM " + INITIALIZER + "SELECT * FROM " + + INITIALIZER + " WHERE operation_id = ? AND issuer_id = ? FOR UPDATE", value.initializer().operationId(), ISSUER); @@ -379,7 +381,8 @@ public void recordOpenReadback( throw conflict("OPEN readback has no durable first-attempt initializer state"); } transaction.execute( - "INSERT INTO " + INITIALIZER_RECEIPT + "INSERT INTO " + + INITIALIZER_RECEIPT + " (operation_id, issuer_id, exact_open_payload_bytes," + " exact_open_payload_digest, script_outcome) VALUES (?, ?, ?, ?, ?)" + " ON CONFLICT (operation_id) DO NOTHING", @@ -390,20 +393,25 @@ public void recordOpenReadback( (short) readback.scriptOutcome()); Record receipt = transaction.fetchOne( - "SELECT * FROM " + INITIALIZER_RECEIPT + "SELECT * FROM " + + INITIALIZER_RECEIPT + " WHERE operation_id = ? AND issuer_id = ? FOR UPDATE", value.initializer().operationId(), ISSUER); if (receipt == null - || !Arrays.equals(requireBytes(receipt, "exact_open_payload_bytes"), value.exactBytes()) + || !Arrays.equals( + requireBytes(receipt, "exact_open_payload_bytes"), value.exactBytes()) || !value.exactDigest().equals(receipt.get("exact_open_payload_digest", String.class)) - || !List.of((short) 1, (short) 2).contains(receipt.get("script_outcome", Short.class))) { - throw conflict("Original OPEN readback receipt conflicts with durable initializer bytes"); + || !List.of((short) 1, (short) 2) + .contains(receipt.get("script_outcome", Short.class))) { + throw conflict( + "Original OPEN readback receipt conflicts with durable initializer bytes"); } if ("INITIALIZING".equals(initializationState)) { int confirmed = transaction.execute( - "UPDATE " + INITIALIZER + "UPDATE " + + INITIALIZER + " SET initialization_state = 'OPEN_CONFIRMED'" + " WHERE operation_id = ? AND issuer_id = ?" + " AND initialization_state = 'INITIALIZING'", @@ -441,7 +449,8 @@ public void recordClosedReadback( CanonicalGameplayIssuerAdmissionControlValue control = readCurrentControl(transaction, anchor, current); if (!value.ownerOperationId().equals(control.currentOperationId()) - || control.state() != CanonicalGameplayIssuerAdmissionControlValue.State.CUTOFF_PENDING) { + || control.state() + != CanonicalGameplayIssuerAdmissionControlValue.State.CUTOFF_PENDING) { throw conflict("CLOSED readback is not owned by the current pending cutoff"); } new CanonicalGameplayIssuerAdmissionControlRepository(dsl) @@ -451,11 +460,11 @@ public void recordClosedReadback( value.tenantId(), value.playableStateNamespaceId(), value.exactBytes()); - requireCurrentTagMapping( - transaction, value.tenantId(), value.tenantGameplayTag()); + requireCurrentTagMapping(transaction, value.tenantId(), value.tenantGameplayTag()); Record target = transaction.fetchOne( - "SELECT * FROM " + CUTOFF_TARGET + "SELECT * FROM " + + CUTOFF_TARGET + " WHERE operation_id = ? AND issuer_id = ? AND tenant_id = ?" + " AND playable_state_namespace_id = ? FOR UPDATE", value.ownerOperationId(), @@ -471,7 +480,8 @@ public void recordClosedReadback( if ("REQUIRED".equals(state)) { int updated = transaction.execute( - "UPDATE " + CUTOFF_TARGET + "UPDATE " + + CUTOFF_TARGET + " SET exact_closed_readback_bytes = ?, exact_closed_readback_digest = ? ," + " script_outcome = ?, target_state = 'CLOSED'" + " WHERE operation_id = ? AND target_ordinal = ? AND target_state = 'REQUIRED'", @@ -482,8 +492,11 @@ public void recordClosedReadback( target.get("target_ordinal", Long.class)); if (updated != 1) throw conflict("CLOSED target changed during receipt persistence"); } else if (!"CLOSED".equals(state) - || !Arrays.equals(requireBytes(target, "exact_closed_readback_bytes"), value.exactBytes()) - || !value.exactDigest().equals(target.get("exact_closed_readback_digest", String.class)) + || !Arrays.equals( + requireBytes(target, "exact_closed_readback_bytes"), value.exactBytes()) + || !value + .exactDigest() + .equals(target.get("exact_closed_readback_digest", String.class)) || !List.of((short) 1, (short) 2, (short) 3) .contains(target.get("script_outcome", Short.class))) { throw conflict("CLOSED retry conflicts with its immutable durable readback"); @@ -508,7 +521,9 @@ private CurrentRequestTarget requireCurrentRequestTarget( + " t.admission_target_owner_proof_outcome, t.admission_target_positive_durable_abort," + " i.account_id, i.tenant_id, i.playable_state_namespace_id, i.lifecycle," + " i.binding_ref AS inventory_binding_ref, r.reservation_id" - + " FROM " + LOCAL_OPERATION + " op" + + " FROM " + + LOCAL_OPERATION + + " op" + " JOIN game_session_canonical_binding_transition t ON t.transition_id = op.transition_id" + " JOIN game_session_canonical_gameplay_binding_inventory i" + " ON i.binding_ref = op.binding_ref AND i.transition_id = op.transition_id" @@ -534,7 +549,8 @@ private CurrentRequestTarget requireCurrentRequestTarget( || !tenantId.equals(row.get("admission_target_tenant_id", UUID.class)) || !namespaceId.equals(row.get("admission_target_playable_state_namespace_id", UUID.class)) || !"COMMITTED".equals(row.get("admission_target_owner_proof_outcome", String.class)) - || !Boolean.FALSE.equals(row.get("admission_target_positive_durable_abort", Boolean.class))) { + || !Boolean.FALSE.equals( + row.get("admission_target_positive_durable_abort", Boolean.class))) { throw conflict("Current issuer NEW request is not the exact registered tenant target"); } byte[] memberBytes = requireBytes(row, "member_value_bytes"); @@ -552,7 +568,9 @@ private CurrentRequestTarget requireCurrentRequestTarget( || !member.owner().accountId().equals(assignment.accountId()) || !Arrays.equals(member.owner().bindingRef().bytes(), bindingRef) || !member.sourceCheckpoint().issuerId().equals(ISSUER) - || !member.sourceCheckpoint().issuerAuthGeneration() + || !member + .sourceCheckpoint() + .issuerAuthGeneration() .equals(current.accountCheckpoint().issuerAuthGeneration()) || !Arrays.equals( member.sourceCheckpoint().exactCheckpointBytes(), @@ -582,7 +600,9 @@ private CanonicalGameplayAdmissionBarrierTuple buildOriginalInitializer( transaction.fetchOne( "SELECT op.transition_id, op.binding_ref, to_jsonb(t)::text AS registered_target_json," + " to_jsonb(r)::text AS reservation_json" - + " FROM " + LOCAL_OPERATION + " op" + + " FROM " + + LOCAL_OPERATION + + " op" + " JOIN game_session_canonical_binding_transition t ON t.transition_id = op.transition_id" + " JOIN game_session_canonical_gameplay_binding_inventory i" + " ON i.binding_ref = op.binding_ref AND i.transition_id = op.transition_id" @@ -595,10 +615,10 @@ private CanonicalGameplayAdmissionBarrierTuple buildOriginalInitializer( if (row == null || !expected.transitionId().equals(requiredUuid(row, "transition_id")) || !Arrays.equals(expected.bindingRef(), requireBytes(row, "binding_ref"))) { - throw conflict("Current issuer NEW target changed before its original initializer was captured"); + throw conflict( + "Current issuer NEW target changed before its original initializer was captured"); } - byte[] reservationBytes = - requireText(row, "reservation_json").getBytes(StandardCharsets.UTF_8); + byte[] reservationBytes = requireText(row, "reservation_json").getBytes(StandardCharsets.UTF_8); byte[] targetBytes = requireText(row, "registered_target_json").getBytes(StandardCharsets.UTF_8); CanonicalGameplayIssuerAdmissionBarrierValue.Initializer initializer = @@ -654,8 +674,7 @@ private CanonicalGameplayIssuerAdmissionBarrierValue readFrozenInitializer( || !List.of("PREPARED", "INITIALIZING", "OPEN_CONFIRMED").contains(state)) { throw conflict("Frozen tenant initializer differs from current positive source and control"); } - requireCurrentTagMapping( - transaction, initializer.tenantId(), initializer.tenantGameplayTag()); + requireCurrentTagMapping(transaction, initializer.tenantId(), initializer.tenantGameplayTag()); if (expectedTarget != null) requireSameTargetAssignment(expectedTarget, initializer); return value; } @@ -664,7 +683,8 @@ private static void requireCurrentTagMapping( DSLContext transaction, UUID tenantId, String expectedTag) { Record mapping = transaction.fetchOne( - "SELECT allocation_version, tenant_gameplay_tag FROM " + TENANT_TAG + "SELECT allocation_version, tenant_gameplay_tag FROM " + + TENANT_TAG + " WHERE tenant_id = ? FOR SHARE", tenantId); Integer version = mapping == null ? null : mapping.get("allocation_version", Integer.class); @@ -692,7 +712,8 @@ private static void persistOriginalInitializer( } int inserted = transaction.execute( - "INSERT INTO " + INITIALIZER + "INSERT INTO " + + INITIALIZER + " (operation_id, issuer_id, tenant_id, playable_state_namespace_id," + " tenant_gameplay_tag, live_barrier_epoch, initialization_state," + " initializer_exact_bytes," @@ -722,8 +743,9 @@ private static void requirePersistedInitializer( if (row == null || !expected.issuerId().equals(row.get("issuer_id", String.class)) || !expected.tenantId().equals(row.get("tenant_id", UUID.class)) - || !expected.playableStateNamespaceId().equals( - row.get("playable_state_namespace_id", UUID.class)) + || !expected + .playableStateNamespaceId() + .equals(row.get("playable_state_namespace_id", UUID.class)) || !expected.tenantGameplayTag().equals(row.get("tenant_gameplay_tag", String.class)) || !expected.admissionEpoch().equals(readBigInteger(row, "live_barrier_epoch")) || !Arrays.equals( @@ -745,10 +767,7 @@ private CanonicalGameplayIssuerAdmissionBarrierRedisOwner.PreparedInitializer pr assignment, requestOperationId, CanonicalGameplayIssuerAdmissionBarrierKey.forTarget( - ISSUER, - value.tenantId(), - value.playableStateNamespaceId(), - value.tenantGameplayTag()), + ISSUER, value.tenantId(), value.playableStateNamespaceId(), value.tenantGameplayTag()), createPermit); } @@ -772,11 +791,13 @@ private boolean claimFirstCreatePermit( transaction, anchor, current); if (!control.liveBarrierEpoch().equals(value.admissionEpoch()) || !control.currentOperationId().equals(anchor.bootstrapOperationId())) { - throw conflict("Original initializer no longer belongs to the current OPEN live control"); + throw conflict( + "Original initializer no longer belongs to the current OPEN live control"); } Record saved = transaction.fetchOne( - "SELECT * FROM " + INITIALIZER + "SELECT * FROM " + + INITIALIZER + " WHERE operation_id = ? AND issuer_id = ? FOR UPDATE", operationId, ISSUER); @@ -785,7 +806,8 @@ private boolean claimFirstCreatePermit( if ("PREPARED".equals(state)) { Record origin = transaction.fetchOne( - "SELECT transition.status AS transition_status FROM " + LOCAL_OPERATION + "SELECT transition.status AS transition_status FROM " + + LOCAL_OPERATION + " operation JOIN game_session_canonical_binding_transition transition" + " ON transition.transition_id = operation.transition_id" + " WHERE operation.operation_id = ? AND operation.issuer_id = ?" @@ -804,7 +826,8 @@ private boolean claimFirstCreatePermit( } int claimed = transaction.execute( - "UPDATE " + INITIALIZER + "UPDATE " + + INITIALIZER + " SET initialization_state = 'INITIALIZING'" + " WHERE operation_id = ? AND issuer_id = ?" + " AND initialization_state = 'PREPARED'", @@ -823,7 +846,8 @@ private boolean claimFirstCreatePermit( private UUID transitionForLocalOperation(UUID operationId) { Record row = dsl.fetchOne( - "SELECT transition_id FROM " + LOCAL_OPERATION + "SELECT transition_id FROM " + + LOCAL_OPERATION + " WHERE operation_id = ? AND issuer_id = ?", operationId, ISSUER); @@ -851,19 +875,22 @@ private CanonicalGameplayIssuerAdmissionControlValue readCurrentControl( "SELECT * FROM " + CONTROL + " WHERE issuer_id = ? FOR UPDATE", ISSUER); if (row == null) throw conflict("The positive live issuer admission-control row is missing"); CanonicalGameplayIssuerAdmissionControlValue value = - CanonicalGameplayIssuerAdmissionControlValue.decode(requireBytes(row, "control_exact_bytes")); + CanonicalGameplayIssuerAdmissionControlValue.decode( + requireBytes(row, "control_exact_bytes")); if (!CanonicalGameplayIssuerAdmissionControlValue.sha256(value.exactBytes()) .equals(row.get("control_exact_digest", String.class)) || !value.issuerId().equals(row.get("issuer_id", String.class)) || !value.matchesCurrentIssuerState(current) || !Arrays.equals(value.anchorExactBytes(), anchor.exactAnchorBytes()) || !value.anchorExactDigest().equals(anchor.exactAnchorDigest())) { - throw conflict("Issuer control differs from its exact installed anchor and fresh current source"); + throw conflict( + "Issuer control differs from its exact installed anchor and fresh current source"); } return value; } - private CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState readCurrentState() { + private CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState + readCurrentState() { try { return Objects.requireNonNull( currentStateSource.readFreshCurrentState(), "Current issuer source returned null"); @@ -960,11 +987,7 @@ private record PreparedInitializerSource( CanonicalGameplayTenantGameplayTagRepository.Assignment requestAssignment) {} private record CurrentRequestTarget( - UUID transitionId, - UUID tenantId, - UUID namespaceId, - UUID accountId, - byte[] bindingRef) { + UUID transitionId, UUID tenantId, UUID namespaceId, UUID accountId, byte[] bindingRef) { private CurrentRequestTarget { Objects.requireNonNull(transitionId, "transitionId"); Objects.requireNonNull(tenantId, "tenantId"); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierValue.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierValue.java index c63c0cfa52..1c17f78e85 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierValue.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierValue.java @@ -120,8 +120,7 @@ static final class Initializer { this.incarnationDigest = requireDigest(incarnationDigest, "incarnationDigest"); requireDigestMatches(this.incarnationBytes, this.incarnationDigest, "incarnation"); this.registeredTargetBytes = nonEmpty(registeredTargetBytes, "registeredTargetBytes"); - this.registeredTargetDigest = - requireDigest(registeredTargetDigest, "registeredTargetDigest"); + this.registeredTargetDigest = requireDigest(registeredTargetDigest, "registeredTargetDigest"); requireDigestMatches( this.registeredTargetBytes, this.registeredTargetDigest, "registered target"); long boundedBytes = @@ -207,32 +206,101 @@ private static Initializer decode(byte[] bytes) { } } - String issuerId() { return issuerId; } - UUID tenantId() { return tenantId; } - UUID playableStateNamespaceId() { return playableStateNamespaceId; } - String tenantGameplayTag() { return tenantGameplayTag; } - UUID operationId() { return operationId; } - BigInteger admissionEpoch() { return admissionEpoch; } - UUID transitionId() { return transitionId; } - UUID accountId() { return accountId; } - byte[] bindingRefBytes() { return bindingRefBytes.clone(); } - byte[] reservationBytes() { return reservationBytes.clone(); } - String reservationDigest() { return reservationDigest; } - byte[] anchorBytes() { return anchorBytes.clone(); } - String anchorDigest() { return anchorDigest; } - BigInteger accountIssuerAuthGeneration() { return accountIssuerAuthGeneration; } - byte[] accountCheckpointBytes() { return accountCheckpointBytes.clone(); } - String accountCheckpointDigest() { return accountCheckpointDigest; } + String issuerId() { + return issuerId; + } + + UUID tenantId() { + return tenantId; + } + + UUID playableStateNamespaceId() { + return playableStateNamespaceId; + } + + String tenantGameplayTag() { + return tenantGameplayTag; + } + + UUID operationId() { + return operationId; + } + + BigInteger admissionEpoch() { + return admissionEpoch; + } + + UUID transitionId() { + return transitionId; + } + + UUID accountId() { + return accountId; + } + + byte[] bindingRefBytes() { + return bindingRefBytes.clone(); + } + + byte[] reservationBytes() { + return reservationBytes.clone(); + } + + String reservationDigest() { + return reservationDigest; + } + + byte[] anchorBytes() { + return anchorBytes.clone(); + } + + String anchorDigest() { + return anchorDigest; + } + + BigInteger accountIssuerAuthGeneration() { + return accountIssuerAuthGeneration; + } + + byte[] accountCheckpointBytes() { + return accountCheckpointBytes.clone(); + } + + String accountCheckpointDigest() { + return accountCheckpointDigest; + } + byte[] accountSourceEventBytes() { return accountSourceEventBytes == null ? null : accountSourceEventBytes.clone(); } - String accountSourceEventDigest() { return accountSourceEventDigest; } - byte[] incarnationBytes() { return incarnationBytes.clone(); } - String incarnationDigest() { return incarnationDigest; } - byte[] registeredTargetBytes() { return registeredTargetBytes.clone(); } - String registeredTargetDigest() { return registeredTargetDigest; } - byte[] exactBytes() { return exactBytes.clone(); } - String exactDigest() { return exactDigest; } + + String accountSourceEventDigest() { + return accountSourceEventDigest; + } + + byte[] incarnationBytes() { + return incarnationBytes.clone(); + } + + String incarnationDigest() { + return incarnationDigest; + } + + byte[] registeredTargetBytes() { + return registeredTargetBytes.clone(); + } + + String registeredTargetDigest() { + return registeredTargetDigest; + } + + byte[] exactBytes() { + return exactBytes.clone(); + } + + String exactDigest() { + return exactDigest; + } boolean matchesCurrentIssuerState( CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState current) { @@ -359,14 +427,7 @@ static CanonicalGameplayIssuerAdmissionBarrierValue decode(byte[] bytes) { } CanonicalGameplayIssuerAdmissionBarrierValue result = new CanonicalGameplayIssuerAdmissionBarrierValue( - issuerId, - tenantId, - namespaceId, - tag, - state, - epoch, - ownerOperationId, - initializer); + issuerId, tenantId, namespaceId, tag, state, epoch, ownerOperationId, initializer); if (in.available() != 0 || !Arrays.equals(bytes, result.exactBytes())) throw malformed(); return result; } catch (IOException | RuntimeException invalid) { @@ -390,20 +451,50 @@ private byte[] encodeValue() { }); } - String issuerId() { return issuerId; } - UUID tenantId() { return tenantId; } - UUID playableStateNamespaceId() { return playableStateNamespaceId; } - String tenantGameplayTag() { return tenantGameplayTag; } - State state() { return state; } - BigInteger admissionEpoch() { return admissionEpoch; } - UUID ownerOperationId() { return ownerOperationId; } - Initializer initializer() { return initializer; } - byte[] exactBytes() { return exactBytes.clone(); } - String exactDigest() { return exactDigest; } + String issuerId() { + return issuerId; + } + + UUID tenantId() { + return tenantId; + } + + UUID playableStateNamespaceId() { + return playableStateNamespaceId; + } + + String tenantGameplayTag() { + return tenantGameplayTag; + } + + State state() { + return state; + } + + BigInteger admissionEpoch() { + return admissionEpoch; + } + + UUID ownerOperationId() { + return ownerOperationId; + } + + Initializer initializer() { + return initializer; + } + + byte[] exactBytes() { + return exactBytes.clone(); + } + + String exactDigest() { + return exactDigest; + } static String sha256(byte[] bytes) { try { - return "sha256:" + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); } catch (Exception failure) { throw new IllegalStateException("Could not digest exact issuer admission bytes", failure); } @@ -488,7 +579,8 @@ private static BigInteger readPositive(DataInputStream in) throws IOException { private static String decodeUtf8(byte[] bytes) throws IOException { try { - return StandardCharsets.UTF_8.newDecoder() + return StandardCharsets.UTF_8 + .newDecoder() .onMalformedInput(CodingErrorAction.REPORT) .onUnmappableCharacter(CodingErrorAction.REPORT) .decode(java.nio.ByteBuffer.wrap(bytes)) @@ -512,7 +604,8 @@ private static byte[] nonEmpty(byte[] value, String name) { private static UUID requireNonNil(UUID value, String name) { Objects.requireNonNull(value, name); - if (value.equals(new UUID(0L, 0L))) throw new IllegalArgumentException(name + " must not be nil"); + if (value.equals(new UUID(0L, 0L))) + throw new IllegalArgumentException(name + " must not be nil"); return value; } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionControlRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionControlRepository.java index be4c6957d5..809f0ac613 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionControlRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionControlRepository.java @@ -5,14 +5,14 @@ import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; -import java.util.Arrays; import java.util.ArrayList; +import java.util.Arrays; import java.util.Comparator; import java.util.HexFormat; import java.util.List; import java.util.Map; -import java.util.TreeMap; import java.util.Objects; +import java.util.TreeMap; import java.util.UUID; import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; import org.jooq.DSLContext; @@ -26,7 +26,8 @@ final class CanonicalGameplayIssuerAdmissionControlRepository { private static final String CONTROL = "game_session_canonical_issuer_admission_control"; private static final String COUNTER = "game_session_canonical_issuer_admission_epoch_counter"; private static final String OPERATION = "game_session_canonical_issuer_admission_operation"; - private static final String LAYOUT_CONTROL = "game_session_canonical_issuer_layout_bootstrap_control"; + private static final String LAYOUT_CONTROL = + "game_session_canonical_issuer_layout_bootstrap_control"; private static final String ANCHOR = "game_session_canonical_issuer_installed_anchor"; private static final String LOCAL_OPERATION = "game_session_canonical_issuer_binding_local_operation"; @@ -52,27 +53,32 @@ final class CanonicalGameplayIssuerAdmissionControlRepository { */ CanonicalGameplayIssuerAdmissionControlValue installInitialOpen( CanonicalGameplayIssuerInstalledAnchor anchor, - CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerStateSource currentStateSource) { + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerStateSource + currentStateSource) { Objects.requireNonNull(anchor, "anchor"); Objects.requireNonNull(currentStateSource, "currentStateSource"); requireNoAmbientTransaction(); CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState before = - Objects.requireNonNull(currentStateSource.readFreshCurrentState(), "current state source returned null"); + Objects.requireNonNull( + currentStateSource.readFreshCurrentState(), "current state source returned null"); CanonicalGameplayIssuerAdmissionControlValue installed = dsl.transactionResult( configuration -> installInitialInTransaction(DSL.using(configuration), anchor, before)); CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState after = - Objects.requireNonNull(currentStateSource.readFreshCurrentState(), "current state source returned null after install"); + Objects.requireNonNull( + currentStateSource.readFreshCurrentState(), + "current state source returned null after install"); if (!installed.matchesCurrentIssuerState(after)) { - throw conflict("Current Account issuer source or stable incarnation moved during live-control installation"); + throw conflict( + "Current Account issuer source or stable incarnation moved during live-control installation"); } return installed; } /** * Freezes the complete current issuer cohort and advances the positive live-control epoch before - * any tenant-local CLOSED writes are attempted. Tenant keys come from the locked cohort and - * each key must have its exact positive current SQL tenant-tag mapping. + * any tenant-local CLOSED writes are attempted. Tenant keys come from the locked cohort and each + * key must have its exact positive current SQL tenant-tag mapping. */ CanonicalGameplayIssuerAdmissionControlValue beginCutoff( UUID cutoffOperationId, @@ -125,10 +131,12 @@ CanonicalGameplayIssuerAdmissionControlValue beginCutoff( } if (control.state() != CanonicalGameplayIssuerAdmissionControlValue.State.OPEN || control.currentOperationKind() - != CanonicalGameplayIssuerAdmissionControlValue.OperationKind.INITIAL_ANCHOR_INSTALL + != CanonicalGameplayIssuerAdmissionControlValue.OperationKind + .INITIAL_ANCHOR_INSTALL || !control.currentOperationId().equals(anchor.bootstrapOperationId()) || priorOperation != null) { - throw conflict("Issuer live control cannot be reset, reopened, or replaced by this cutoff"); + throw conflict( + "Issuer live control cannot be reset, reopened, or replaced by this cutoff"); } requireInitialOperationCurrent(transaction, control); @@ -142,7 +150,8 @@ CanonicalGameplayIssuerAdmissionControlValue beginCutoff( BigInteger priorEpoch = control.liveBarrierEpoch(); Record allocated = transaction.fetchOne( - "UPDATE " + COUNTER + "UPDATE " + + COUNTER + " SET last_live_barrier_epoch = last_live_barrier_epoch + 1," + " updated_at = CURRENT_TIMESTAMP" + " WHERE issuer_id = ? AND last_live_barrier_epoch = ?" @@ -156,19 +165,11 @@ CanonicalGameplayIssuerAdmissionControlValue beginCutoff( String cohortDigest = digestCohort(rows); CanonicalGameplayIssuerAdmissionControlValue pending = control.cutoffPending( - cutoffOperationId, - cutoffEpoch, - snapshotRevision, - rows.size(), - cohortDigest); + cutoffOperationId, cutoffEpoch, snapshotRevision, rows.size(), cohortDigest); insertCutoffOperation(transaction, pending, requestId, priorEpoch); updateControl(transaction, pending, control.liveBarrierEpoch()); insertCohortRows(transaction, pending.currentOperationId(), rows); - insertCutoffTargets( - transaction, - pending, - targets, - tagByTarget); + insertCutoffTargets(transaction, pending, targets, tagByTarget); verifyFrozenCohort(transaction, pending); verifyCutoffTargets(transaction, pending); return pending; @@ -197,11 +198,13 @@ CanonicalGameplayIssuerAdmissionControlValue completeCutoff( requireExactAnchorAndCurrentSource(control, anchor, currentState); requireCounterMatchesCurrent(transaction, control.liveBarrierEpoch()); if (!control.currentOperationId().equals(cutoffOperationId) - || control.state() != CanonicalGameplayIssuerAdmissionControlValue.State.CUTOFF_PENDING + || control.state() + != CanonicalGameplayIssuerAdmissionControlValue.State.CUTOFF_PENDING || control.currentOperationKind() != CanonicalGameplayIssuerAdmissionControlValue.OperationKind.CUTOFF) { if (control.currentOperationId().equals(cutoffOperationId) - && control.state() == CanonicalGameplayIssuerAdmissionControlValue.State.INSTALLED) { + && control.state() + == CanonicalGameplayIssuerAdmissionControlValue.State.INSTALLED) { requireCutoffOperationCurrent(transaction, control); verifyFrozenCohort(transaction, control); verifyCutoffTargets(transaction, control); @@ -214,18 +217,22 @@ CanonicalGameplayIssuerAdmissionControlValue completeCutoff( verifyCutoffTargets(transaction, control); Record remaining = transaction.fetchOne( - "SELECT EXISTS (SELECT 1 FROM " + CUTOFF_TARGET + "SELECT EXISTS (SELECT 1 FROM " + + CUTOFF_TARGET + " WHERE operation_id = ? AND issuer_id = ? AND target_state <> 'CLOSED')" + " AS has_open_target", cutoffOperationId, ISSUER); - if (remaining == null || Boolean.TRUE.equals(remaining.get("has_open_target", Boolean.class))) { - throw conflict("Every frozen issuer tenant target must read back CLOSED before installation"); + if (remaining == null + || Boolean.TRUE.equals(remaining.get("has_open_target", Boolean.class))) { + throw conflict( + "Every frozen issuer tenant target must read back CLOSED before installation"); } CanonicalGameplayIssuerAdmissionControlValue installed = control.installed(); int updatedOperation = transaction.execute( - "UPDATE " + OPERATION + "UPDATE " + + OPERATION + " SET operation_state = 'INSTALLED', installed_at = CURRENT_TIMESTAMP" + " WHERE operation_id = ? AND issuer_id = ? AND operation_kind = 'CUTOFF'" + " AND operation_state = 'CUTOFF_PENDING' AND live_barrier_epoch = ?" @@ -234,12 +241,14 @@ CanonicalGameplayIssuerAdmissionControlValue completeCutoff( ISSUER, control.liveBarrierEpoch(), control.liveBarrierEpoch().subtract(BigInteger.ONE)); - if (updatedOperation != 1) throw conflict("Issuer cutoff operation changed before installation"); + if (updatedOperation != 1) + throw conflict("Issuer cutoff operation changed before installation"); updateControl(transaction, installed, control.liveBarrierEpoch()); Record saved = transaction.fetchOne( "SELECT * FROM " + CONTROL + " WHERE issuer_id = ? FOR UPDATE", ISSUER); - if (saved == null || !Arrays.equals(loadControl(saved).exactBytes(), installed.exactBytes())) { + if (saved == null + || !Arrays.equals(loadControl(saved).exactBytes(), installed.exactBytes())) { throw conflict("Installed issuer cutoff did not read back exactly"); } return installed; @@ -267,7 +276,8 @@ void verifyCurrentCutoffTarget( verifyCutoffTargets(transaction, control); Record target = transaction.fetchOne( - "SELECT * FROM " + CUTOFF_TARGET + "SELECT * FROM " + + CUTOFF_TARGET + " WHERE operation_id = ? AND issuer_id = ? AND tenant_id = ?" + " AND playable_state_namespace_id = ? FOR UPDATE", control.currentOperationId(), @@ -359,11 +369,13 @@ private static List captureCutoffCohort( .map( row -> { String json = text(row, "source_row_json"); - String digest = CanonicalGameplayIssuerAdmissionControlValue.sha256( - json.getBytes(StandardCharsets.UTF_8)); + String digest = + CanonicalGameplayIssuerAdmissionControlValue.sha256( + json.getBytes(StandardCharsets.UTF_8)); BigInteger revision = integer(row, "source_revision"); if (revision.signum() <= 0 || revision.compareTo(snapshotRevision) > 0) { - throw conflict("Issuer cutoff cohort contains a source outside its locked snapshot"); + throw conflict( + "Issuer cutoff cohort contains a source outside its locked snapshot"); } return new CohortRow( text(row, "source_kind"), @@ -416,7 +428,8 @@ private static void requireNoFutureCutoffRows( } Record future = transaction.fetchOne(sql, binds.toArray()); if (future == null || Boolean.TRUE.equals(future.get("has_future_rows", Boolean.class))) { - throw conflict("Issuer cutoff found source rows newer than its serialized inventory snapshot"); + throw conflict( + "Issuer cutoff found source rows newer than its serialized inventory snapshot"); } } @@ -436,7 +449,8 @@ private static void insertCutoffOperation( BigInteger priorEpoch) { int inserted = transaction.execute( - "INSERT INTO " + OPERATION + "INSERT INTO " + + OPERATION + " (operation_id, request_id, issuer_id, operation_kind, operation_state," + " live_barrier_epoch, prior_live_barrier_epoch, bootstrap_operation_id," + " bootstrap_request_id, bootstrap_control_epoch, anchor_exact_bytes," @@ -474,7 +488,8 @@ private static void insertCohortRows( CohortRow row = rows.get(index); int inserted = transaction.execute( - "INSERT INTO " + COHORT + "INSERT INTO " + + COHORT + " (operation_id, issuer_id, row_ordinal, source_kind, source_key," + " source_inventory_revision, source_row_json, source_row_digest)" + " VALUES (?, ?, ?, ?, ?, ?, ?, ?)", @@ -502,7 +517,8 @@ private static void insertCutoffTargets( if (tenantTag == null) throw conflict("Issuer cutoff target has no current SQL tenant tag"); Record initializerRow = transaction.fetchOne( - "SELECT * FROM " + INITIALIZER + "SELECT * FROM " + + INITIALIZER + " WHERE issuer_id = ? AND tenant_id = ? AND playable_state_namespace_id = ?" + " AND live_barrier_epoch <= ? ORDER BY live_barrier_epoch DESC LIMIT 1 FOR UPDATE", ISSUER, @@ -524,7 +540,8 @@ private static void insertCutoffTargets( openDigest = text(initializerRow, "open_payload_digest"); if (!CanonicalGameplayIssuerAdmissionControlValue.sha256(initializerBytes) .equals(initializerDigest) - || !CanonicalGameplayIssuerAdmissionControlValue.sha256(openPayload).equals(openDigest)) { + || !CanonicalGameplayIssuerAdmissionControlValue.sha256(openPayload) + .equals(openDigest)) { throw conflict("Persisted original issuer initializer digest is invalid"); } CanonicalGameplayIssuerAdmissionBarrierValue decoded = @@ -544,14 +561,20 @@ private static void insertCutoffTargets( || !initializer.tenantGameplayTag().equals(tenantTag) || !Arrays.equals(initializer.anchorBytes(), control.anchorExactBytes()) || !initializer.anchorDigest().equals(control.anchorExactDigest()) - || !initializer.accountIssuerAuthGeneration().equals(control.accountIssuerAuthGeneration()) - || !Arrays.equals(initializer.accountCheckpointBytes(), control.accountCheckpointBytes()) + || !initializer + .accountIssuerAuthGeneration() + .equals(control.accountIssuerAuthGeneration()) + || !Arrays.equals( + initializer.accountCheckpointBytes(), control.accountCheckpointBytes()) || !initializer.accountCheckpointDigest().equals(control.accountCheckpointDigest()) - || !Arrays.equals(initializer.accountSourceEventBytes(), control.accountSourceEventBytes()) - || !Objects.equals(initializer.accountSourceEventDigest(), control.accountSourceEventDigest()) + || !Arrays.equals( + initializer.accountSourceEventBytes(), control.accountSourceEventBytes()) + || !Objects.equals( + initializer.accountSourceEventDigest(), control.accountSourceEventDigest()) || !Arrays.equals(initializer.incarnationBytes(), control.stableIncarnationBytes()) || !initializer.incarnationDigest().equals(control.stableIncarnationDigest())) { - throw conflict("Captured original OPEN initializer differs from the frozen issuer source"); + throw conflict( + "Captured original OPEN initializer differs from the frozen issuer source"); } } String targetDigest = digestTargetSource(entry.getValue()); @@ -566,7 +589,8 @@ private static void insertCutoffTargets( initializer); int inserted = transaction.execute( - "INSERT INTO " + CUTOFF_TARGET + "INSERT INTO " + + CUTOFF_TARGET + " (operation_id, issuer_id, target_ordinal, tenant_id," + " playable_state_namespace_id, tenant_gameplay_tag, target_source_digest," + " captured_initializer_operation_id, captured_initializer_epoch," @@ -597,7 +621,8 @@ private static void verifyFrozenCohort( List rows = transaction .fetch( - "SELECT * FROM " + COHORT + "SELECT * FROM " + + COHORT + " WHERE operation_id = ? AND issuer_id = ? ORDER BY row_ordinal", control.currentOperationId(), ISSUER) @@ -608,7 +633,8 @@ private static void verifyFrozenCohort( if (!CanonicalGameplayIssuerAdmissionControlValue.sha256( json.getBytes(StandardCharsets.UTF_8)) .equals(storedDigest)) { - throw conflict("Issuer cutoff cohort source digest differs from its stored JSON"); + throw conflict( + "Issuer cutoff cohort source digest differs from its stored JSON"); } return new CohortRow( text(row, "source_kind"), @@ -626,7 +652,8 @@ private static void verifyFrozenCohort( } Record ordinal = transaction.fetchOne( - "SELECT row_ordinal FROM " + COHORT + "SELECT row_ordinal FROM " + + COHORT + " WHERE operation_id = ? AND issuer_id = ? AND source_kind = ? AND source_key = ?", control.currentOperationId(), ISSUER, @@ -645,7 +672,8 @@ private static void verifyFrozenCohort( private static String requireCurrentTenantTagMapping(DSLContext transaction, UUID tenantId) { Record mapping = transaction.fetchOne( - "SELECT allocation_version, tenant_gameplay_tag FROM " + TENANT_TAG + "SELECT allocation_version, tenant_gameplay_tag FROM " + + TENANT_TAG + " WHERE tenant_id = ? FOR SHARE", tenantId); Integer version = mapping == null ? null : mapping.get("allocation_version", Integer.class); @@ -664,7 +692,8 @@ private static void verifyCutoffTargets( DSLContext transaction, CanonicalGameplayIssuerAdmissionControlValue control) { List rows = transaction.fetch( - "SELECT * FROM " + CUTOFF_TARGET + "SELECT * FROM " + + CUTOFF_TARGET + " WHERE operation_id = ? AND issuer_id = ? ORDER BY target_ordinal", control.currentOperationId(), ISSUER); @@ -750,14 +779,24 @@ private static void requireCutoffOperationCurrent( || !control.bootstrapControlEpoch().equals(integer(operation, "bootstrap_control_epoch")) || !Arrays.equals(control.anchorExactBytes(), bytes(operation, "anchor_exact_bytes")) || !control.anchorExactDigest().equals(text(operation, "anchor_exact_digest")) - || !control.accountIssuerAuthGeneration().equals(integer(operation, "account_issuer_auth_generation")) - || !Arrays.equals(control.accountCheckpointBytes(), bytes(operation, "account_checkpoint_bytes")) + || !control + .accountIssuerAuthGeneration() + .equals(integer(operation, "account_issuer_auth_generation")) + || !Arrays.equals( + control.accountCheckpointBytes(), bytes(operation, "account_checkpoint_bytes")) || !control.accountCheckpointDigest().equals(text(operation, "account_checkpoint_digest")) - || !Arrays.equals(control.accountSourceEventBytes(), nullableBytes(operation, "account_source_event_bytes")) - || !Objects.equals(control.accountSourceEventDigest(), nullableText(operation, "account_source_event_digest")) - || !Arrays.equals(control.stableIncarnationBytes(), bytes(operation, "stable_incarnation_bytes")) + || !Arrays.equals( + control.accountSourceEventBytes(), + nullableBytes(operation, "account_source_event_bytes")) + || !Objects.equals( + control.accountSourceEventDigest(), + nullableText(operation, "account_source_event_digest")) + || !Arrays.equals( + control.stableIncarnationBytes(), bytes(operation, "stable_incarnation_bytes")) || !control.stableIncarnationDigest().equals(text(operation, "stable_incarnation_digest")) - || !control.inventorySnapshotRevision().equals(integer(operation, "inventory_snapshot_revision")) + || !control + .inventorySnapshotRevision() + .equals(integer(operation, "inventory_snapshot_revision")) || control.cohortRowCount() != longInteger(operation, "cohort_row_count") || !control.cohortDigest().equals(text(operation, "cohort_digest"))) { throw conflict("Live issuer cutoff has no exact current durable operation"); @@ -765,10 +804,13 @@ private static void requireCutoffOperationCurrent( } private static void updateControl( - DSLContext transaction, CanonicalGameplayIssuerAdmissionControlValue value, BigInteger expectedEpoch) { + DSLContext transaction, + CanonicalGameplayIssuerAdmissionControlValue value, + BigInteger expectedEpoch) { int updated = transaction.execute( - "UPDATE " + CONTROL + "UPDATE " + + CONTROL + " SET state = ?, live_barrier_epoch = ?, current_operation_id = ?," + " current_operation_kind = ?, bootstrap_operation_id = ?, bootstrap_request_id = ?," + " bootstrap_control_epoch = ?, anchor_exact_bytes = ?, anchor_exact_digest = ?," @@ -808,14 +850,13 @@ private static void updateControl( private static String digestCohort(List rows) { MessageDigest digest = sha256Digest(); rows.stream() - .sorted( - Comparator.comparing(CohortRow::sourceKind) - .thenComparing(CohortRow::sourceKey)) + .sorted(Comparator.comparing(CohortRow::sourceKind).thenComparing(CohortRow::sourceKey)) .forEach( row -> { updateFramed(digest, row.sourceKind().getBytes(StandardCharsets.UTF_8)); updateFramed(digest, row.sourceKey().getBytes(StandardCharsets.UTF_8)); - updateFramed(digest, row.sourceRevision().toString().getBytes(StandardCharsets.US_ASCII)); + updateFramed( + digest, row.sourceRevision().toString().getBytes(StandardCharsets.US_ASCII)); updateFramed(digest, row.sourceDigest().getBytes(StandardCharsets.US_ASCII)); }); return "sha256:" + HexFormat.of().formatHex(digest.digest()); @@ -824,9 +865,7 @@ private static String digestCohort(List rows) { private static String digestTargetSource(List rows) { MessageDigest digest = sha256Digest(); rows.stream() - .sorted( - Comparator.comparing(CohortRow::sourceKind) - .thenComparing(CohortRow::sourceKey)) + .sorted(Comparator.comparing(CohortRow::sourceKind).thenComparing(CohortRow::sourceKey)) .forEach( row -> { updateFramed(digest, row.sourceKind().getBytes(StandardCharsets.UTF_8)); @@ -885,8 +924,11 @@ static CanonicalGameplayIssuerAdmissionControlValue requireOpenInTransaction( Objects.requireNonNull(anchor, "anchor"); Objects.requireNonNull(currentState, "currentState"); lockLayoutControl(transaction, anchor); - Record row = transaction.fetchOne("SELECT * FROM " + CONTROL + " WHERE issuer_id = ? FOR UPDATE", ISSUER); - if (row == null) throw conflict("Ordinary issuer work requires a positive live admission-control row"); + Record row = + transaction.fetchOne( + "SELECT * FROM " + CONTROL + " WHERE issuer_id = ? FOR UPDATE", ISSUER); + if (row == null) + throw conflict("Ordinary issuer work requires a positive live admission-control row"); CanonicalGameplayIssuerAdmissionControlValue value = loadControl(row); requireExactAnchorAndCurrentSource(value, anchor, currentState); if (value.state() != CanonicalGameplayIssuerAdmissionControlValue.State.OPEN @@ -905,7 +947,9 @@ private CanonicalGameplayIssuerAdmissionControlValue installInitialInTransaction CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState currentState) { CanonicalGameplayBindingInventoryRepository.lockInventoryRevision(transaction); lockLayoutControl(transaction, anchor); - Record existing = transaction.fetchOne("SELECT * FROM " + CONTROL + " WHERE issuer_id = ? FOR UPDATE", ISSUER); + Record existing = + transaction.fetchOne( + "SELECT * FROM " + CONTROL + " WHERE issuer_id = ? FOR UPDATE", ISSUER); if (existing != null) { CanonicalGameplayIssuerAdmissionControlValue prior = loadControl(existing); requireExactAnchorAndCurrentSource(prior, anchor, currentState); @@ -920,7 +964,9 @@ private CanonicalGameplayIssuerAdmissionControlValue installInitialInTransaction throw conflict("Existing issuer admission control cannot be reset or reopened"); } - Record counter = transaction.fetchOne("SELECT * FROM " + COUNTER + " WHERE issuer_id = ? FOR UPDATE", ISSUER); + Record counter = + transaction.fetchOne( + "SELECT * FROM " + COUNTER + " WHERE issuer_id = ? FOR UPDATE", ISSUER); if (counter == null) throw conflict("The positive live issuer epoch counter is missing"); BigInteger last = integer(counter, "last_live_barrier_epoch"); if (last.signum() != 0) { @@ -938,13 +984,15 @@ private CanonicalGameplayIssuerAdmissionControlValue installInitialInTransaction Record allocated = transaction.fetchOne( - "UPDATE " + COUNTER + "UPDATE " + + COUNTER + " SET last_live_barrier_epoch = last_live_barrier_epoch + 1," + " updated_at = CURRENT_TIMESTAMP" + " WHERE issuer_id = ? AND last_live_barrier_epoch = 0" + " RETURNING last_live_barrier_epoch", ISSUER); - if (allocated == null) throw conflict("Live issuer epoch allocation lost its serialized counter"); + if (allocated == null) + throw conflict("Live issuer epoch allocation lost its serialized counter"); BigInteger liveEpoch = integer(allocated, "last_live_barrier_epoch"); CanonicalGameplayIssuerAdmissionControlValue requested = CanonicalGameplayIssuerAdmissionControlValue.initialOpen( @@ -953,11 +1001,14 @@ private CanonicalGameplayIssuerAdmissionControlValue installInitialInTransaction liveEpoch, 0L, CanonicalGameplayIssuerAdmissionControlValue.sha256( - "issuer-admission-initial-cohort/v1".getBytes(java.nio.charset.StandardCharsets.UTF_8))); + "issuer-admission-initial-cohort/v1" + .getBytes(java.nio.charset.StandardCharsets.UTF_8))); insertInitialOperation(transaction, requested); insertControl(transaction, requested); - Record saved = transaction.fetchOne("SELECT * FROM " + CONTROL + " WHERE issuer_id = ? FOR UPDATE", ISSUER); + Record saved = + transaction.fetchOne( + "SELECT * FROM " + CONTROL + " WHERE issuer_id = ? FOR UPDATE", ISSUER); if (saved == null) throw conflict("Initial live issuer control did not persist"); CanonicalGameplayIssuerAdmissionControlValue result = loadControl(saved); if (!Arrays.equals(result.exactBytes(), requested.exactBytes())) { @@ -978,10 +1029,15 @@ private static void lockLayoutControl( || !anchor.controlEpoch().equals(integer(control, "control_epoch")) || !anchor.operationFence().equals(integer(control, "current_operation_fence")) || !anchor.coverageFence().equals(integer(control, "current_coverage_fence"))) { - throw conflict("Live admission control requires its exact immutable V1030 bootstrap provenance"); + throw conflict( + "Live admission control requires its exact immutable V1030 bootstrap provenance"); } Record anchorRow = - transaction.fetchOne("SELECT exact_anchor_bytes, exact_anchor_digest FROM " + ANCHOR + " WHERE issuer_id = ? FOR UPDATE", ISSUER); + transaction.fetchOne( + "SELECT exact_anchor_bytes, exact_anchor_digest FROM " + + ANCHOR + + " WHERE issuer_id = ? FOR UPDATE", + ISSUER); if (anchorRow == null || !Arrays.equals(bytes(anchorRow, "exact_anchor_bytes"), anchor.exactAnchorBytes()) || !anchor.exactAnchorDigest().equals(text(anchorRow, "exact_anchor_digest"))) { @@ -993,7 +1049,8 @@ private static void insertInitialOperation( DSLContext transaction, CanonicalGameplayIssuerAdmissionControlValue value) { int inserted = transaction.execute( - "INSERT INTO " + OPERATION + "INSERT INTO " + + OPERATION + " (operation_id, request_id, issuer_id, operation_kind, operation_state," + " live_barrier_epoch, prior_live_barrier_epoch, bootstrap_operation_id," + " bootstrap_request_id, bootstrap_control_epoch, anchor_exact_bytes," @@ -1028,7 +1085,8 @@ private static void insertControl( DSLContext transaction, CanonicalGameplayIssuerAdmissionControlValue value) { int inserted = transaction.execute( - "INSERT INTO " + CONTROL + "INSERT INTO " + + CONTROL + " (issuer_id, state, live_barrier_epoch, current_operation_id, current_operation_kind," + " bootstrap_operation_id, bootstrap_request_id, bootstrap_control_epoch," + " anchor_exact_bytes, anchor_exact_digest, account_issuer_auth_generation," @@ -1081,11 +1139,15 @@ private static CanonicalGameplayIssuerAdmissionControlValue loadControl(Record r || !value.bootstrapControlEpoch().equals(integer(row, "bootstrap_control_epoch")) || !Arrays.equals(value.anchorExactBytes(), bytes(row, "anchor_exact_bytes")) || !value.anchorExactDigest().equals(text(row, "anchor_exact_digest")) - || !value.accountIssuerAuthGeneration().equals(integer(row, "account_issuer_auth_generation")) + || !value + .accountIssuerAuthGeneration() + .equals(integer(row, "account_issuer_auth_generation")) || !Arrays.equals(value.accountCheckpointBytes(), bytes(row, "account_checkpoint_bytes")) || !value.accountCheckpointDigest().equals(text(row, "account_checkpoint_digest")) - || !Arrays.equals(value.accountSourceEventBytes(), nullableBytes(row, "account_source_event_bytes")) - || !Objects.equals(value.accountSourceEventDigest(), nullableText(row, "account_source_event_digest")) + || !Arrays.equals( + value.accountSourceEventBytes(), nullableBytes(row, "account_source_event_bytes")) + || !Objects.equals( + value.accountSourceEventDigest(), nullableText(row, "account_source_event_digest")) || !Arrays.equals(value.stableIncarnationBytes(), bytes(row, "stable_incarnation_bytes")) || !value.stableIncarnationDigest().equals(text(row, "stable_incarnation_digest")) || !value.inventorySnapshotRevision().equals(integer(row, "inventory_snapshot_revision")) @@ -1111,7 +1173,9 @@ private static void requireExactAnchorAndCurrentSource( } private static void requireCounterMatchesCurrent(DSLContext transaction, BigInteger liveEpoch) { - Record counter = transaction.fetchOne("SELECT * FROM " + COUNTER + " WHERE issuer_id = ? FOR UPDATE", ISSUER); + Record counter = + transaction.fetchOne( + "SELECT * FROM " + COUNTER + " WHERE issuer_id = ? FOR UPDATE", ISSUER); if (counter == null || !integer(counter, "last_live_barrier_epoch").equals(liveEpoch)) { throw conflict("Live issuer admission epoch differs from its positive owner counter"); } @@ -1119,7 +1183,10 @@ private static void requireCounterMatchesCurrent(DSLContext transaction, BigInte private static void requireInitialOperationCurrent( DSLContext transaction, CanonicalGameplayIssuerAdmissionControlValue value) { - Record operation = transaction.fetchOne("SELECT * FROM " + OPERATION + " WHERE operation_id = ? FOR UPDATE", value.currentOperationId()); + Record operation = + transaction.fetchOne( + "SELECT * FROM " + OPERATION + " WHERE operation_id = ? FOR UPDATE", + value.currentOperationId()); if (operation == null || !ISSUER.equals(text(operation, "issuer_id")) || !"INITIAL_ANCHOR_INSTALL".equals(text(operation, "operation_kind")) @@ -1130,14 +1197,23 @@ private static void requireInitialOperationCurrent( || !value.bootstrapControlEpoch().equals(integer(operation, "bootstrap_control_epoch")) || !Arrays.equals(value.anchorExactBytes(), bytes(operation, "anchor_exact_bytes")) || !value.anchorExactDigest().equals(text(operation, "anchor_exact_digest")) - || !value.accountIssuerAuthGeneration().equals(integer(operation, "account_issuer_auth_generation")) - || !Arrays.equals(value.accountCheckpointBytes(), bytes(operation, "account_checkpoint_bytes")) + || !value + .accountIssuerAuthGeneration() + .equals(integer(operation, "account_issuer_auth_generation")) + || !Arrays.equals( + value.accountCheckpointBytes(), bytes(operation, "account_checkpoint_bytes")) || !value.accountCheckpointDigest().equals(text(operation, "account_checkpoint_digest")) - || !Arrays.equals(value.accountSourceEventBytes(), nullableBytes(operation, "account_source_event_bytes")) - || !Objects.equals(value.accountSourceEventDigest(), nullableText(operation, "account_source_event_digest")) - || !Arrays.equals(value.stableIncarnationBytes(), bytes(operation, "stable_incarnation_bytes")) + || !Arrays.equals( + value.accountSourceEventBytes(), nullableBytes(operation, "account_source_event_bytes")) + || !Objects.equals( + value.accountSourceEventDigest(), + nullableText(operation, "account_source_event_digest")) + || !Arrays.equals( + value.stableIncarnationBytes(), bytes(operation, "stable_incarnation_bytes")) || !value.stableIncarnationDigest().equals(text(operation, "stable_incarnation_digest")) - || !value.inventorySnapshotRevision().equals(integer(operation, "inventory_snapshot_revision")) + || !value + .inventorySnapshotRevision() + .equals(integer(operation, "inventory_snapshot_revision")) || value.cohortRowCount() != longInteger(operation, "cohort_row_count") || !value.cohortDigest().equals(text(operation, "cohort_digest"))) { throw conflict("Live issuer control has no exact persisted initial-anchor operation"); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionControlValue.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionControlValue.java index 73607681d6..90a2d3b555 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionControlValue.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionControlValue.java @@ -82,7 +82,8 @@ private CanonicalGameplayIssuerAdmissionControlValue( this.state = Objects.requireNonNull(state, "state"); this.liveBarrierEpoch = requirePositive(liveBarrierEpoch, "liveBarrierEpoch"); this.currentOperationId = requireNonNil(currentOperationId, "currentOperationId"); - this.currentOperationKind = Objects.requireNonNull(currentOperationKind, "currentOperationKind"); + this.currentOperationKind = + Objects.requireNonNull(currentOperationKind, "currentOperationKind"); this.bootstrapOperationId = requireNonNil(bootstrapOperationId, "bootstrapOperationId"); this.bootstrapRequestId = requireNonNil(bootstrapRequestId, "bootstrapRequestId"); this.bootstrapControlEpoch = requirePositive(bootstrapControlEpoch, "bootstrapControlEpoch"); @@ -92,27 +93,34 @@ private CanonicalGameplayIssuerAdmissionControlValue( this.accountIssuerAuthGeneration = requirePositive(accountIssuerAuthGeneration, "accountIssuerAuthGeneration"); this.accountCheckpointBytes = nonEmpty(accountCheckpointBytes, "accountCheckpointBytes"); - this.accountCheckpointDigest = requireDigest(accountCheckpointDigest, "accountCheckpointDigest"); + this.accountCheckpointDigest = + requireDigest(accountCheckpointDigest, "accountCheckpointDigest"); requireDigestMatches( this.accountCheckpointBytes, this.accountCheckpointDigest, "Account checkpoint"); if ((accountSourceEventBytes == null) != (accountSourceEventDigest == null)) { throw new IllegalArgumentException("Account source event bytes and digest must be paired"); } this.accountSourceEventBytes = - accountSourceEventBytes == null ? null : nonEmpty(accountSourceEventBytes, "accountSourceEventBytes"); + accountSourceEventBytes == null + ? null + : nonEmpty(accountSourceEventBytes, "accountSourceEventBytes"); this.accountSourceEventDigest = - accountSourceEventDigest == null ? null : requireDigest(accountSourceEventDigest, "accountSourceEventDigest"); + accountSourceEventDigest == null + ? null + : requireDigest(accountSourceEventDigest, "accountSourceEventDigest"); if (this.accountSourceEventBytes != null) { requireDigestMatches( this.accountSourceEventBytes, this.accountSourceEventDigest, "Account source event"); } this.stableIncarnationBytes = nonEmpty(stableIncarnationBytes, "stableIncarnationBytes"); - this.stableIncarnationDigest = requireDigest(stableIncarnationDigest, "stableIncarnationDigest"); + this.stableIncarnationDigest = + requireDigest(stableIncarnationDigest, "stableIncarnationDigest"); requireDigestMatches( this.stableIncarnationBytes, this.stableIncarnationDigest, "stable incarnation"); this.inventorySnapshotRevision = requirePositive(inventorySnapshotRevision, "inventorySnapshotRevision"); - if (cohortRowCount < 0) throw new IllegalArgumentException("cohortRowCount must not be negative"); + if (cohortRowCount < 0) + throw new IllegalArgumentException("cohortRowCount must not be negative"); this.cohortRowCount = cohortRowCount; this.cohortDigest = requireDigest(cohortDigest, "cohortDigest"); if ((state == State.OPEN) != (currentOperationKind == OperationKind.INITIAL_ANCHOR_INSTALL)) { @@ -143,7 +151,8 @@ static CanonicalGameplayIssuerAdmissionControlValue initialOpen( || !Arrays.equals( anchor.incarnationBytes(), CanonicalGameplayIssuerInstalledAnchor.encodeIncarnation(current.incarnation()))) { - throw new IllegalArgumentException("Live issuer control requires the exact current anchor sources"); + throw new IllegalArgumentException( + "Live issuer control requires the exact current anchor sources"); } return new CanonicalGameplayIssuerAdmissionControlValue( anchor.issuerId(), @@ -304,34 +313,101 @@ boolean matchesCurrentIssuerState( CanonicalGameplayIssuerInstalledAnchor.encodeIncarnation(current.incarnation())); } - String issuerId() { return issuerId; } - State state() { return state; } - BigInteger liveBarrierEpoch() { return liveBarrierEpoch; } - UUID currentOperationId() { return currentOperationId; } - OperationKind currentOperationKind() { return currentOperationKind; } - UUID bootstrapOperationId() { return bootstrapOperationId; } - UUID bootstrapRequestId() { return bootstrapRequestId; } - BigInteger bootstrapControlEpoch() { return bootstrapControlEpoch; } - byte[] anchorExactBytes() { return anchorExactBytes.clone(); } - String anchorExactDigest() { return anchorExactDigest; } - BigInteger accountIssuerAuthGeneration() { return accountIssuerAuthGeneration; } - byte[] accountCheckpointBytes() { return accountCheckpointBytes.clone(); } - String accountCheckpointDigest() { return accountCheckpointDigest; } - byte[] accountSourceEventBytes() { return accountSourceEventBytes == null ? null : accountSourceEventBytes.clone(); } - String accountSourceEventDigest() { return accountSourceEventDigest; } - byte[] stableIncarnationBytes() { return stableIncarnationBytes.clone(); } - String stableIncarnationDigest() { return stableIncarnationDigest; } - BigInteger inventorySnapshotRevision() { return inventorySnapshotRevision; } - long cohortRowCount() { return cohortRowCount; } - String cohortDigest() { return cohortDigest; } - byte[] exactBytes() { return exactBytes.clone(); } - String exactDigest() { return exactDigest; } + String issuerId() { + return issuerId; + } + + State state() { + return state; + } + + BigInteger liveBarrierEpoch() { + return liveBarrierEpoch; + } + + UUID currentOperationId() { + return currentOperationId; + } + + OperationKind currentOperationKind() { + return currentOperationKind; + } + + UUID bootstrapOperationId() { + return bootstrapOperationId; + } + + UUID bootstrapRequestId() { + return bootstrapRequestId; + } + + BigInteger bootstrapControlEpoch() { + return bootstrapControlEpoch; + } + + byte[] anchorExactBytes() { + return anchorExactBytes.clone(); + } + + String anchorExactDigest() { + return anchorExactDigest; + } + + BigInteger accountIssuerAuthGeneration() { + return accountIssuerAuthGeneration; + } + + byte[] accountCheckpointBytes() { + return accountCheckpointBytes.clone(); + } + + String accountCheckpointDigest() { + return accountCheckpointDigest; + } + + byte[] accountSourceEventBytes() { + return accountSourceEventBytes == null ? null : accountSourceEventBytes.clone(); + } + + String accountSourceEventDigest() { + return accountSourceEventDigest; + } + + byte[] stableIncarnationBytes() { + return stableIncarnationBytes.clone(); + } + + String stableIncarnationDigest() { + return stableIncarnationDigest; + } + + BigInteger inventorySnapshotRevision() { + return inventorySnapshotRevision; + } + + long cohortRowCount() { + return cohortRowCount; + } + + String cohortDigest() { + return cohortDigest; + } + + byte[] exactBytes() { + return exactBytes.clone(); + } + + String exactDigest() { + return exactDigest; + } static String sha256(byte[] bytes) { try { - return "sha256:" + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); } catch (Exception failure) { - throw new IllegalStateException("Could not digest exact issuer admission-control bytes", failure); + throw new IllegalStateException( + "Could not digest exact issuer admission-control bytes", failure); } } @@ -343,7 +419,8 @@ private static byte[] encode(Writer writer) { } return bytes.toByteArray(); } catch (IOException impossible) { - throw new IllegalStateException("Could not encode issuer admission-control bytes", impossible); + throw new IllegalStateException( + "Could not encode issuer admission-control bytes", impossible); } } @@ -381,7 +458,8 @@ private static void writeBigInteger(DataOutputStream out, BigInteger value) thro private static String readText(DataInputStream in) throws IOException { byte[] bytes = readBytes(in); try { - return StandardCharsets.UTF_8.newDecoder() + return StandardCharsets.UTF_8 + .newDecoder() .onMalformedInput(CodingErrorAction.REPORT) .onUnmappableCharacter(CodingErrorAction.REPORT) .decode(ByteBuffer.wrap(bytes)) @@ -432,7 +510,8 @@ private static String requireIssuer(String issuerId) { private static UUID requireNonNil(UUID value, String name) { Objects.requireNonNull(value, name); - if (value.equals(new UUID(0L, 0L))) throw new IllegalArgumentException(name + " must not be nil"); + if (value.equals(new UUID(0L, 0L))) + throw new IllegalArgumentException(name + " must not be nil"); return value; } @@ -454,7 +533,8 @@ private static byte[] nonEmpty(byte[] value, String name) { private static String requireDigest(String digest, String name) { Objects.requireNonNull(digest, name); - if (!digest.matches("sha256:[0-9a-f]{64}")) throw new IllegalArgumentException(name + " is malformed"); + if (!digest.matches("sha256:[0-9a-f]{64}")) + throw new IllegalArgumentException(name + " is malformed"); return digest; } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCandidate.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCandidate.java index 62b39b3e36..dbc3418b77 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCandidate.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCandidate.java @@ -17,8 +17,8 @@ /** * Exact, typed source bytes for the non-admitting original {@code NEW} session candidate. * - *

This is a data carrier only. It does not prove that any input came from Account or the - * durable Game Session owners, establish a physical Redis readback, finalize the Account lease, or + *

This is a data carrier only. It does not prove that any input came from Account or the durable + * Game Session owners, establish a physical Redis readback, finalize the Account lease, or * authorize gameplay. Authenticated session readers must reject its separate purpose discriminator. * *

The payload retains the complete immutable Account lease and original decision sources plus @@ -109,7 +109,9 @@ public TransitionSource transition() { return transition; } - /** Immutable reservation identity, fences and original snapshot; current revisions may advance. */ + /** + * Immutable reservation identity, fences and original snapshot; current revisions may advance. + */ public ReservationSource reservation() { return reservation; } @@ -136,7 +138,9 @@ public boolean matchesOriginalDecision(CanonicalGameplayAdmissionDecision decisi return CanonicalGameplayOriginalNewCandidateCodec.matchesOriginalDecision(this, decision); } - /** Checks stable source identity while allowing only the documented PREPARED/PROVISIONAL retry. */ + /** + * Checks stable source identity while allowing only the documented PREPARED/PROVISIONAL retry. + */ public boolean matchesProvisionalSources( CanonicalGameplayBindingProvisionalCasEvidence evidence) { return CanonicalGameplayOriginalNewCandidateCodec.matchesProvisionalSources(this, evidence); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCandidateCodec.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCandidateCodec.java index 348785dc12..577341d7cf 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCandidateCodec.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCandidateCodec.java @@ -53,7 +53,14 @@ final class CanonicalGameplayOriginalNewCandidateCodec { private static final ObjectMapper JSON = new ObjectMapper(JSON_FACTORY).enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS); private static final Set ROOT_FIELDS = - Set.of("purpose", "bindingDecisionId", "leaseEvidence", "binding", "target", "transition", "reservation"); + Set.of( + "purpose", + "bindingDecisionId", + "leaseEvidence", + "binding", + "target", + "transition", + "reservation"); private static final Set BINDING_FIELDS = Set.of( "accountId", @@ -155,8 +162,8 @@ static byte[] encode(CanonicalGameplayOriginalNewCandidate candidate) { "issuerCoverageOperationFence", false); requireCounterLimit(candidate.reservation().coverageFence(), "coverageFence", false); - requireCounterLimit(candidate.reservation().inventorySnapshotRevision(), - "inventorySnapshotRevision", false); + requireCounterLimit( + candidate.reservation().inventorySnapshotRevision(), "inventorySnapshotRevision", false); ObjectNode root = JSON.createObjectNode(); root.put("purpose", CanonicalGameplayOriginalNewCandidate.PURPOSE); @@ -242,7 +249,8 @@ static boolean matchesProvisionalSources( && candidate.transition().bindingGeneration().equals(transition.bindingGeneration()) && candidate.transition().issuerReservationId().equals(transition.issuerReservationId()) && candidate.transition().reservationFence().equals(transition.reservationFence()) - && candidate.transition() + && candidate + .transition() .candidateAccountIndexFence() .equals(transition.candidateAccountIndexFence()) && candidate.transition().bindingRef().equals(entry.bindingRef()) @@ -327,7 +335,9 @@ private static void validateDecodedSources(CanonicalGameplayOriginalNewCandidate || !transition.transitionId().equals(reservation.transitionId()) || !transition.issuerReservationId().equals(reservation.reservationId()) || !transition.reservationFence().equals(reservation.reservationFence()) - || !reservation.partitionId().equals(binding.bindingRef().partitionId(binding.issuerIndexPartitionCount()))) { + || !reservation + .partitionId() + .equals(binding.bindingRef().partitionId(binding.issuerIndexPartitionCount()))) { throw invalid("Candidate source identities, generation, or fences do not agree"); } if (!isPublicProductionNewLease(candidate.leaseEvidence())) { @@ -454,15 +464,14 @@ private static ObjectNode reservationNode( node.put("lifecycle", CanonicalIssuerPartitionReservation.Lifecycle.RESERVED.name()); node.put("reservationFence", reservation.reservationFence().toString()); node.put("issuerCoverageOperationId", reservation.issuerCoverageOperationId().toString()); - node.put( - "issuerCoverageOperationFence", reservation.issuerCoverageOperationFence().toString()); + node.put("issuerCoverageOperationFence", reservation.issuerCoverageOperationFence().toString()); node.put("coverageFence", reservation.coverageFence().toString()); node.put("inventorySnapshotRevision", reservation.inventorySnapshotRevision().toString()); return node; } - private static JsonNode parseCanonicalLeaseNode( - AccountGameplayAdmissionLeaseEvidence evidence) throws IOException { + private static JsonNode parseCanonicalLeaseNode(AccountGameplayAdmissionLeaseEvidence evidence) + throws IOException { return JSON.readTree(evidence.canonicalJson()); } @@ -477,8 +486,7 @@ private static AccountGameplayAdmissionLeaseEvidence parseLeaseEvidence(JsonNode new String(canonical, StandardCharsets.UTF_8)); } - private static CanonicalGameplayBindingIdentity parseBinding(JsonNode source) - throws IOException { + private static CanonicalGameplayBindingIdentity parseBinding(JsonNode source) throws IOException { ObjectNode node = requireObject(source, "binding"); requireFields(node, BINDING_FIELDS, "binding"); return new CanonicalGameplayBindingIdentity( @@ -570,7 +578,8 @@ private static CanonicalGameplayOriginalNewCandidate.ReservationSource parseRese JsonNode source) throws IOException { ObjectNode node = requireObject(source, "reservation"); requireFields(node, RESERVATION_FIELDS, "reservation"); - if (!text(node, "lifecycle").equals(CanonicalIssuerPartitionReservation.Lifecycle.RESERVED.name())) { + if (!text(node, "lifecycle") + .equals(CanonicalIssuerPartitionReservation.Lifecycle.RESERVED.name())) { throw invalid("Original NEW candidate reservation must remain RESERVED"); } return new CanonicalGameplayOriginalNewCandidate.ReservationSource( @@ -666,8 +675,7 @@ private static Instant instant(JsonNode node, String field) { } } - private static > E enumValue( - Class enumType, String value, String field) { + private static > E enumValue(Class enumType, String value, String field) { try { return Enum.valueOf(enumType, value); } catch (IllegalArgumentException malformed) { @@ -693,7 +701,9 @@ private static String base64(byte[] bytes) { private static void requireCounterLimit(BigInteger value, String name, boolean zeroAllowed) { Objects.requireNonNull(value, name); int digits = value.toString().length(); - if (digits > MAX_COUNTER_DIGITS || value.signum() < 0 || (!zeroAllowed && value.signum() == 0)) { + if (digits > MAX_COUNTER_DIGITS + || value.signum() < 0 + || (!zeroAllowed && value.signum() == 0)) { throw invalid(name + " exceeds its canonical integer bounds"); } } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayProtectedIncarnationReceiver.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayProtectedIncarnationReceiver.java index 9ccc4f0fc1..d8bc245f03 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayProtectedIncarnationReceiver.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayProtectedIncarnationReceiver.java @@ -198,11 +198,12 @@ VerifiedIncarnation observeForFenceTarget(UUID operationId, long targetOrdinal) } requireAvailable(OwnerKind.ACCOUNT_FENCE); CurrentContext before = loadCurrentContext(operationId, targetOrdinal); - return observeCurrentContext( - before, () -> loadCurrentContext(operationId, targetOrdinal)); + return observeCurrentContext(before, () -> loadCurrentContext(operationId, targetOrdinal)); } - /** Reads a separate INITIAL original-attempt context under the same trusted signature verifier. */ + /** + * Reads a separate INITIAL original-attempt context under the same trusted signature verifier. + */ VerifiedIncarnation observeForInitialAccountBarrier(UUID originalRequestId) { requireNoAmbientTransaction(); requireNonNil(originalRequestId, "originalRequestId"); @@ -458,10 +459,8 @@ private VerifiedPayload verifyObservation( requireText(owner, "ownerKind", OwnerKind.INITIAL_ACCOUNT_BARRIER.name()); requireText(owner, "initializerId", expected.operationId().toString()); requireText(owner, "originalRequestId", expected.requestId().toString()); - requireText( - owner, "originalCallerContextId", expected.originalCallerContextId().toString()); - if (requiredPositiveLong(owner, "originalAttemptFence") - != expected.originalAttemptFence()) { + requireText(owner, "originalCallerContextId", expected.originalCallerContextId().toString()); + if (requiredPositiveLong(owner, "originalAttemptFence") != expected.originalAttemptFence()) { throw new ObservationRejectedException("Protected INITIAL attempt fence differs"); } requireText(owner, "accountId", expected.accountId().toString()); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayTenantGameplayTagRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayTenantGameplayTagRepository.java index 4ee4454079..3fa08c3fc9 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayTenantGameplayTagRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayTenantGameplayTagRepository.java @@ -477,11 +477,7 @@ private record BarrierTarget( implements Target {} private record InitialTarget( - UUID initializerId, - UUID originalRequestId, - UUID accountId, - UUID tenantId, - UUID namespaceId) + UUID initializerId, UUID originalRequestId, UUID accountId, UUID tenantId, UUID namespaceId) implements Target {} /** Owner-issued immutable mapping plus the exact SQL source needed by the key builder. */ diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayIssuerAdmissionBarrierRedisScriptContribution.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayIssuerAdmissionBarrierRedisScriptContribution.java index 9ecc7591a8..d8e1bb24cf 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayIssuerAdmissionBarrierRedisScriptContribution.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayIssuerAdmissionBarrierRedisScriptContribution.java @@ -37,7 +37,8 @@ public String ownerId() { @Override public Collection descriptors() { - return List.of(readDescriptor(OPEN_DESCRIPTOR_PATH, OPEN_SCRIPT_ID), + return List.of( + readDescriptor(OPEN_DESCRIPTOR_PATH, OPEN_SCRIPT_ID), readDescriptor(CLOSE_DESCRIPTOR_PATH, CLOSE_SCRIPT_ID)); } diff --git a/services/game-session-service/src/main/resources/db/migration/V1046__canonical_issuer_live_admission_control.sql b/services/game-session-service/src/main/resources/db/migration/V1046__canonical_issuer_live_admission_control.sql index e98768762d..e30e4a576b 100644 --- a/services/game-session-service/src/main/resources/db/migration/V1046__canonical_issuer_live_admission_control.sql +++ b/services/game-session-service/src/main/resources/db/migration/V1046__canonical_issuer_live_admission_control.sql @@ -155,7 +155,9 @@ CREATE TABLE game_session_canonical_issuer_admission_cohort_row ( source_row_json text NOT NULL, source_row_digest character varying(71) NOT NULL, CONSTRAINT pk_gs_issuer_admission_cohort_row PRIMARY KEY (operation_id, row_ordinal), + -- [jooq ignore start] CONSTRAINT uq_gs_issuer_admission_cohort_source UNIQUE (operation_id, source_kind, source_key), + -- [jooq ignore stop] CONSTRAINT fk_gs_issuer_admission_cohort_operation FOREIGN KEY (operation_id, issuer_id) REFERENCES game_session_canonical_issuer_admission_operation (operation_id, issuer_id), @@ -278,7 +280,7 @@ CREATE TABLE game_session_canonical_issuer_admission_cutoff_target ( OR (target_state = 'CLOSED' AND octet_length(exact_closed_readback_bytes) BETWEEN 1 AND 524288 AND exact_closed_readback_digest ~ '^sha256:[0-9a-f]{64}$' - AND script_outcome IN (1, 2, 3))) + AND script_outcome IN (1, 2, 3)))) ); CREATE INDEX ix_gs_issuer_admission_cutoff_target_state diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountAdmissionBarrierRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountAdmissionBarrierRepositoryIntegrationTest.java index 29ece781fb..b68fb27763 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountAdmissionBarrierRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountAdmissionBarrierRepositoryIntegrationTest.java @@ -241,7 +241,8 @@ void pendingInitialAccountTargetIsFrozenIntoCutoffAndItsTargetSet() { .anySatisfy( row -> { assertThat(row.kind()) - .isEqualTo(CanonicalGameplayAccountAdmissionFenceIntent.CohortKind.INITIAL_TARGET); + .isEqualTo( + CanonicalGameplayAccountAdmissionFenceIntent.CohortKind.INITIAL_TARGET); assertThat(row.sourceKey()).isEqualTo(initial.initializerId() + ":0"); assertThat(row.tenantId()).isEqualTo(OTHER_TENANT_ID); assertThat(row.playableStateNamespaceId()).isEqualTo(OTHER_NAMESPACE_ID); @@ -282,7 +283,9 @@ void accountCutoffThatWinsInventoryClockOrderBlocksAnInitialTargetInsert() { CanonicalGameplayAccountAdmissionFenceIntent.CohortKind.INITIALIZER, CanonicalGameplayAccountAdmissionFenceIntent.CohortKind.INITIAL_TARGET)); assertThatThrownBy( - () -> insertControlledInitialTarget(testSchema.dsl(), ACCOUNT_ID, OTHER_TENANT_ID, OTHER_NAMESPACE_ID)) + () -> + insertControlledInitialTarget( + testSchema.dsl(), ACCOUNT_ID, OTHER_TENANT_ID, OTHER_NAMESPACE_ID)) .isInstanceOfSatisfying( org.jooq.exception.DataAccessException.class, failure -> assertThat(failure.sqlState()).isEqualTo("23514")); @@ -311,8 +314,9 @@ void initialSourceRequiresPresentNoActiveControlAndPreservesItsActualEpochInclud .execute( "UPDATE game_session_canonical_binding_inventory_clock" + " SET inventory_revision = 1 WHERE singleton_id = 1"); - var original = new net.firedevops.firemud.gamesession.dto.InitialGameplayLoginAttemptCoordinates( - UUID.randomUUID(), UUID.randomUUID(), 17L); + var original = + new net.firedevops.firemud.gamesession.dto.InitialGameplayLoginAttemptCoordinates( + UUID.randomUUID(), UUID.randomUUID(), 17L); var login = mockLoginResult(original, UUID.randomUUID(), UUID.randomUUID()); assertThatThrownBy( @@ -576,7 +580,9 @@ private static CanonicalGameplayBindingTransitionSnapshot prepare( transitionId, UUID.randomUUID(), candidate, reservation, null, null)); } - /** Controlled durable SQL source used only to exercise the existing inventory/control lock order. */ + /** + * Controlled durable SQL source used only to exercise the existing inventory/control lock order. + */ private static ControlledInitialTarget insertControlledInitialTarget( DSLContext dsl, UUID accountId, UUID tenantId, UUID namespaceId) { UUID originalRequestId = UUID.randomUUID(); @@ -642,10 +648,11 @@ private static ControlledInitialTarget insertControlledInitialTarget( return new ControlledInitialTarget(initializerId, originalRequestId); } - private static net.firedevops.firemud.gamesession.dto.CanonicalGameplayLoginResult mockLoginResult( - net.firedevops.firemud.gamesession.dto.InitialGameplayLoginAttemptCoordinates coordinates, - UUID accountId, - UUID tokenJti) { + private static net.firedevops.firemud.gamesession.dto.CanonicalGameplayLoginResult + mockLoginResult( + net.firedevops.firemud.gamesession.dto.InitialGameplayLoginAttemptCoordinates coordinates, + UUID accountId, + UUID tokenJti) { var evidence = new net.firedevops.firemud.gamesession.dto.CanonicalGameplayLoginResult.NonSecretEvidence( accountId, @@ -670,7 +677,8 @@ private static net.firedevops.firemud.gamesession.dto.CanonicalGameplayLoginResu private static void insertCommittedOriginalLogin( DSLContext dsl, net.firedevops.firemud.gamesession.dto.InitialGameplayLoginAttemptCoordinates original, - net.firedevops.firemud.gamesession.dto.CanonicalGameplayLoginResult.NonSecretEvidence evidence) { + net.firedevops.firemud.gamesession.dto.CanonicalGameplayLoginResult.NonSecretEvidence + evidence) { dsl.execute( "INSERT INTO game_session_initial_gameplay_login_journal" + " (request_id, caller_context_id, expected_attempt_fence) VALUES (?, ?, ?)", diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierRedisScriptIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierRedisScriptIntegrationTest.java index 78ae8a98e1..4e09cd01d4 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierRedisScriptIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierRedisScriptIntegrationTest.java @@ -91,20 +91,27 @@ void oneKeyOpenIsReadBackExactlyAndEveryExistingClosedTargetWins() throws Except UUID initializerId = UUID.randomUUID(); String gameplayTag = "g8-" + "b".repeat(32); String key = - "session:game:account-admission:{" - + gameplayTag - + "}:" + accountId + ":" + namespaceId; + "session:game:account-admission:{" + gameplayTag + "}:" + accountId + ":" + namespaceId; Map expectedOpen = Map.of( - "schema", SCHEMA, - "accountId", accountId.toString(), - "tenantId", tenantId.toString(), - "playableStateNamespaceId", namespaceId.toString(), - "tenantGameplayTag", gameplayTag, - "ownerOperationId", initializerId.toString(), - "ownerFenceEpoch", "8", - "incarnationDigest", INCARNATION, - "state", "OPEN"); + "schema", + SCHEMA, + "accountId", + accountId.toString(), + "tenantId", + tenantId.toString(), + "playableStateNamespaceId", + namespaceId.toString(), + "tenantGameplayTag", + gameplayTag, + "ownerOperationId", + initializerId.toString(), + "ownerFenceEpoch", + "8", + "incarnationDigest", + INCARNATION, + "state", + "OPEN"); RedisScriptDescriptor descriptor = RedisScriptCatalog.fromContributions( List.of(new CanonicalGameplayAccountInitialBarrierRedisScriptContribution())) @@ -126,10 +133,9 @@ void oneKeyOpenIsReadBackExactlyAndEveryExistingClosedTargetWins() throws Except byte[][] arguments = openArguments(accountId, tenantId, namespaceId, gameplayTag, initializerId, "8"); - assertThat( - commands.evalsha( - sha, ScriptOutputType.INTEGER, new byte[][] {ascii(key)}, arguments)) - .isEqualTo(1L); + Long createReply = + commands.evalsha(sha, ScriptOutputType.INTEGER, new byte[][] {ascii(key)}, arguments); + assertThat(createReply).isEqualTo(1L); assertThat(commands.type(ascii(key))).isEqualTo("hash"); assertThat(commands.pttl(ascii(key))).isEqualTo(-1L); assertThat(commands.hlen(ascii(key))).isEqualTo(9L); @@ -137,10 +143,9 @@ void oneKeyOpenIsReadBackExactlyAndEveryExistingClosedTargetWins() throws Except // A lost response cannot turn the key into a mutable replay; the SQL owner handles retries // with exact readback and never executes this create script again after DISPATCH_POSSIBLE. - assertThat( - commands.evalsha( - sha, ScriptOutputType.INTEGER, new byte[][] {ascii(key)}, arguments)) - .isEqualTo(0L); + Long repeatCreateReply = + commands.evalsha(sha, ScriptOutputType.INTEGER, new byte[][] {ascii(key)}, arguments); + assertThat(repeatCreateReply).isEqualTo(0L); assertThat(readFields(commands, key)).isEqualTo(expectedOpen); administratorCommands.del(ascii(key)); @@ -149,10 +154,9 @@ void oneKeyOpenIsReadBackExactlyAndEveryExistingClosedTargetWins() throws Except newerClosed.put("state", "CLOSED"); writeFields(administratorCommands, key, newerClosed); Map beforeRefusedOpen = readFields(administratorCommands, key); - assertThat( - commands.evalsha( - sha, ScriptOutputType.INTEGER, new byte[][] {ascii(key)}, arguments)) - .isEqualTo(0L); + Long closedTargetReply = + commands.evalsha(sha, ScriptOutputType.INTEGER, new byte[][] {ascii(key)}, arguments); + assertThat(closedTargetReply).isEqualTo(0L); assertThat(readFields(administratorCommands, key)).isEqualTo(beforeRefusedOpen); assertThat(readFields(administratorCommands, key)).containsEntry("state", "CLOSED"); assertThat(readFields(administratorCommands, key)).containsEntry("ownerFenceEpoch", "9"); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepositoryIntegrationTest.java index bea74d18ff..afa0312f44 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepositoryIntegrationTest.java @@ -19,13 +19,13 @@ import java.util.List; import java.util.Map; import java.util.UUID; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicReference; import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.Candidate; import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.Target; @@ -33,8 +33,8 @@ import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAdmissionDecision; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingIdentity; -import net.firedevops.firemud.gamesession.service.CanonicalGameplayIssuerBindingLocalRedisScriptContribution; import net.firedevops.firemud.gamesession.service.CanonicalGameplayIssuerAdmissionBarrierRedisScriptContribution; +import net.firedevops.firemud.gamesession.service.CanonicalGameplayIssuerBindingLocalRedisScriptContribution; import net.firedevops.firemud.test.TestContainerImages; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; @@ -127,9 +127,12 @@ void firstOpenIsPersistedExactRetryIsReplayOnlyAndCutoffPreservesNewerClosedStat assertThat(cutoffTargets).hasSize(1); var target = cutoffTargets.getFirst(); var closed = - state.owner().closeAndRead( - cutoffOperationId, target.closedValue().tenantId(), - target.closedValue().playableStateNamespaceId()); + state + .owner() + .closeAndRead( + cutoffOperationId, + target.closedValue().tenantId(), + target.closedValue().playableStateNamespaceId()); assertThat(closed.scriptOutcome()).isEqualTo(1L); var newerClosed = @@ -145,10 +148,12 @@ void firstOpenIsPersistedExactRetryIsReplayOnlyAndCutoffPreservesNewerClosedStat byte[] newerBytes = newerClosed.exactBytes(); assertThatThrownBy( () -> - state.owner().closeAndRead( - cutoffOperationId, - target.closedValue().tenantId(), - target.closedValue().playableStateNamespaceId())) + state + .owner() + .closeAndRead( + cutoffOperationId, + target.closedValue().tenantId(), + target.closedValue().playableStateNamespaceId())) .isInstanceOf(IllegalStateException.class); assertThat(administratorCommands.hget(bytes(target.key()), bytes("payload"))) .containsExactly(newerBytes); @@ -301,7 +306,8 @@ void cutoffCapturesAnInitializerWhoseCreatePermitWasClaimedButNotYetAttempted() } } catch (InterruptedException interrupted) { Thread.currentThread().interrupt(); - throw new IllegalStateException("Controlled initializer gate was interrupted", interrupted); + throw new IllegalStateException( + "Controlled initializer gate was interrupted", interrupted); } return prepared; } @@ -341,8 +347,7 @@ public void recordClosedReadback( ExecutorService executor = Executors.newSingleThreadExecutor(); try { var initializerAttempt = - executor.submit( - () -> state.owner(gatedRepository).initializeAndRead(operationId)); + executor.submit(() -> state.owner(gatedRepository).initializeAndRead(operationId)); assertThat(preparedForRedis.await(10, TimeUnit.SECONDS)).isTrue(); assertThat(initializationState(state, operationId)).isEqualTo("INITIALIZING"); @@ -356,10 +361,12 @@ public void recordClosedReadback( var targets = state.repository().readPreparedCutoffTargets(cutoffOperationId); assertThat(targets).hasSize(1); var closed = - state.owner().closeAndRead( - cutoffOperationId, - targets.getFirst().closedValue().tenantId(), - targets.getFirst().closedValue().playableStateNamespaceId()); + state + .owner() + .closeAndRead( + cutoffOperationId, + targets.getFirst().closedValue().tenantId(), + targets.getFirst().closedValue().playableStateNamespaceId()); assertThat(closed.scriptOutcome()).isEqualTo(1L); assertThat(countReceipt(state, operationId)).isZero(); } finally { @@ -377,7 +384,9 @@ void cutoffClosesAnAbortedOriginTargetAndRetainsItsFrozenInitializer() { new CanonicalGameplayBindingInventoryRepository(state.fixture().dsl()) .recordFirstNewAccountAbort(state.fixture().source(), UUID.randomUUID()); assertThat( - state.fixture().dsl() + state + .fixture() + .dsl() .fetchOne( "SELECT status FROM game_session_canonical_binding_transition" + " WHERE transition_id = ?", @@ -391,22 +400,27 @@ void cutoffClosesAnAbortedOriginTargetAndRetainsItsFrozenInitializer() { assertThat(targets).hasSize(1); var target = targets.getFirst(); assertThat(target.expectedOpenValue()).isNotNull(); - assertThat(target.expectedOpenValue().exactBytes()).containsExactly(opened.exactPhysicalPayload()); + assertThat(target.expectedOpenValue().exactBytes()) + .containsExactly(opened.exactPhysicalPayload()); assertThat(target.closedValue().initializer().exactBytes()) .containsExactly(opened.value().initializer().exactBytes()); var closed = - state.owner().closeAndRead( - cutoffOperationId, - target.closedValue().tenantId(), - target.closedValue().playableStateNamespaceId()); + state + .owner() + .closeAndRead( + cutoffOperationId, + target.closedValue().tenantId(), + target.closedValue().playableStateNamespaceId()); assertThat(closed.scriptOutcome()).isEqualTo(1L); var installed = state.repository().completeCutoff(cutoffOperationId); assertThat(installed.state()) .isEqualTo(CanonicalGameplayIssuerAdmissionControlValue.State.INSTALLED); var frozenInitializer = - state.fixture().dsl() + state + .fixture() + .dsl() .fetchOne( "SELECT operation_id, open_payload_bytes FROM" + " game_session_canonical_issuer_admission_initializer" @@ -431,8 +445,7 @@ void reusesFrozenTargetInitializerAcrossOperationsRevisionProgressAndOriginAbort assertThat(secondAccountId).isNotEqualTo(state.candidate().accountId()); CanonicalGameplayIssuerBindingLocalOperation currentOperation = - prepareCurrentOperation( - state, "same-target-different-account", secondAccountId); + prepareCurrentOperation(state, "same-target-different-account", secondAccountId); var originalRetry = state.owner().initializeAndRead(originalOperationId); assertThat(originalRetry.scriptOutcome()).isEqualTo(2L); assertThat(originalRetry.exactPhysicalPayload()).containsExactly(originalPayload); @@ -441,7 +454,9 @@ void reusesFrozenTargetInitializerAcrossOperationsRevisionProgressAndOriginAbort new CanonicalGameplayBindingInventoryRepository(state.fixture().dsl()) .recordFirstNewAccountAbort(abortSource, UUID.randomUUID()); assertThat( - state.fixture().dsl() + state + .fixture() + .dsl() .fetchOne( "SELECT status FROM game_session_canonical_binding_transition" + " WHERE transition_id = ?", @@ -453,13 +468,14 @@ void reusesFrozenTargetInitializerAcrossOperationsRevisionProgressAndOriginAbort assertThat(abortedOriginRetry.scriptOutcome()).isEqualTo(2L); assertThat(abortedOriginRetry.exactPhysicalPayload()).containsExactly(originalPayload); - var currentCandidateReadback = - state.owner().initializeAndRead(currentOperation.operationId()); + var currentCandidateReadback = state.owner().initializeAndRead(currentOperation.operationId()); assertThat(currentCandidateReadback.scriptOutcome()).isEqualTo(2L); assertThat(currentCandidateReadback.exactPhysicalPayload()).containsExactly(originalPayload); var storedInitializer = - state.fixture().dsl() + state + .fixture() + .dsl() .fetchOne( "SELECT operation_id, open_payload_bytes FROM" + " game_session_canonical_issuer_admission_initializer" @@ -471,15 +487,13 @@ void reusesFrozenTargetInitializerAcrossOperationsRevisionProgressAndOriginAbort .containsExactly(originalPayload); state.currentState().set(currentIssuerState(state.candidate(), "moved-source")); - assertThatThrownBy( - () -> state.owner().initializeAndRead(currentOperation.operationId())) + assertThatThrownBy(() -> state.owner().initializeAndRead(currentOperation.operationId())) .isInstanceOf(IllegalStateException.class); state.currentState().set(currentIssuerState(state.candidate())); var prepared = state.repository().readPreparedInitializer(currentOperation.operationId()); administratorCommands.del(bytes(prepared.key())); - assertThatThrownBy( - () -> state.owner().initializeAndRead(currentOperation.operationId())) + assertThatThrownBy(() -> state.owner().initializeAndRead(currentOperation.operationId())) .isInstanceOf(IllegalStateException.class); assertThat(administratorCommands.exists(bytes(prepared.key()))).isZero(); } @@ -489,35 +503,45 @@ void callerOwnedJooqTransactionRefusesBeforeSourceOrRemoteDispatch() { FixtureState state = fixtureState(); var dsl = state.fixture().dsl(); var current = state.currentState().get(); - var anchor = dsl.transactionResult(configuration -> { - var transaction = org.jooq.impl.DSL.using(configuration); - CanonicalGameplayBindingInventoryRepository.lockInventoryRevision(transaction); - return CanonicalGameplayIssuerBootstrapCoverageRepository - .readInstalledAnchorForBindingPreparationInTransaction(transaction, current); - }); + var anchor = + dsl.transactionResult( + configuration -> { + var transaction = org.jooq.impl.DSL.using(configuration); + CanonicalGameplayBindingInventoryRepository.lockInventoryRevision(transaction); + return CanonicalGameplayIssuerBootstrapCoverageRepository + .readInstalledAnchorForBindingPreparationInTransaction(transaction, current); + }); AtomicBoolean sourceCalled = new AtomicBoolean(); - CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerStateSource source = () -> { - sourceCalled.set(true); - return current; - }; - dsl.transaction(configuration -> { - var transaction = org.jooq.impl.DSL.using(configuration); - var repository = new CanonicalGameplayIssuerAdmissionBarrierRepository( - transaction, - new CanonicalGameplayTenantGameplayTagRepository( - transaction, state.fixture().target().targetNamespace(), 1), - source); - assertThatThrownBy(() -> repository.readPreparedInitializer(state.fixture().originalOperationId())) - .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) - .hasMessageContaining("jOOQ transaction"); - assertThatThrownBy(() -> new CanonicalGameplayIssuerAdmissionControlRepository(transaction) - .installInitialOpen(anchor, source)) - .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) - .hasMessageContaining("jOOQ transaction"); - }); + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerStateSource source = + () -> { + sourceCalled.set(true); + return current; + }; + dsl.transaction( + configuration -> { + var transaction = org.jooq.impl.DSL.using(configuration); + var repository = + new CanonicalGameplayIssuerAdmissionBarrierRepository( + transaction, + new CanonicalGameplayTenantGameplayTagRepository( + transaction, state.fixture().target().targetNamespace(), 1), + source); + assertThatThrownBy( + () -> repository.readPreparedInitializer(state.fixture().originalOperationId())) + .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) + .hasMessageContaining("jOOQ transaction"); + assertThatThrownBy( + () -> + new CanonicalGameplayIssuerAdmissionControlRepository(transaction) + .installInitialOpen(anchor, source)) + .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) + .hasMessageContaining("jOOQ transaction"); + }); assertThat(sourceCalled).isFalse(); - assertThat(dsl.fetchCount(org.jooq.impl.DSL.table( - "game_session_canonical_issuer_admission_initializer"))).isZero(); + assertThat( + dsl.fetchCount( + org.jooq.impl.DSL.table("game_session_canonical_issuer_admission_initializer"))) + .isZero(); } private FixtureState fixtureState() { @@ -605,7 +629,7 @@ private CanonicalGameplayIssuerBindingLocalOperation prepareCurrentOperation( identity, operation.preparedTransition().bindingGeneration(), null, - state.fixture().target())); + state.fixture().source().originalDecision().targetEvidence())); var localCatalog = RedisScriptCatalog.fromContributions( List.of(new CanonicalGameplayIssuerBindingLocalRedisScriptContribution())); @@ -779,7 +803,9 @@ private static Map checkpoint(String key, String sequence) { } private static String initializationState(FixtureState state, UUID operationId) { - return state.fixture().dsl() + return state + .fixture() + .dsl() .fetchOne( "SELECT initialization_state FROM game_session_canonical_issuer_admission_initializer" + " WHERE operation_id = ?", @@ -788,7 +814,9 @@ private static String initializationState(FixtureState state, UUID operationId) } private static long countReceipt(FixtureState state, UUID operationId) { - return state.fixture().dsl() + return state + .fixture() + .dsl() .fetchOne( "SELECT count(*) AS receipt_count" + " FROM game_session_canonical_issuer_admission_initializer_receipt" @@ -797,8 +825,7 @@ private static long countReceipt(FixtureState state, UUID operationId) { .get("receipt_count", Long.class); } - private void writePhysicalValue( - String key, CanonicalGameplayIssuerAdmissionBarrierValue value) { + private void writePhysicalValue(String key, CanonicalGameplayIssuerAdmissionBarrierValue value) { var initializer = value.initializer(); Map fields = new LinkedHashMap<>(); fields.put("schema", CanonicalGameplayIssuerAdmissionBarrierValue.SCHEMA); @@ -809,8 +836,11 @@ private void writePhysicalValue( fields.put("state", value.state().name()); fields.put("admissionEpoch", value.admissionEpoch().toString()); fields.put("ownerOperationId", value.ownerOperationId().toString()); - fields.put("initializerOperationId", initializer == null ? "none" : initializer.operationId().toString()); - fields.put("initializerEpoch", initializer == null ? "0" : initializer.admissionEpoch().toString()); + fields.put( + "initializerOperationId", + initializer == null ? "none" : initializer.operationId().toString()); + fields.put( + "initializerEpoch", initializer == null ? "0" : initializer.admissionEpoch().toString()); fields.put("initializerDigest", initializer == null ? "none" : initializer.exactDigest()); fields.put("payloadDigest", value.exactDigest()); for (Map.Entry field : fields.entrySet()) { @@ -851,7 +881,8 @@ private record FixtureState( } private CanonicalGameplayIssuerAdmissionBarrierRedisOwner owner( - CanonicalGameplayIssuerAdmissionBarrierRedisOwner.ProjectionRepository projectionRepository) { + CanonicalGameplayIssuerAdmissionBarrierRedisOwner.ProjectionRepository + projectionRepository) { return new CanonicalGameplayIssuerAdmissionBarrierRedisOwner( ownerClient, RedisScriptCatalog.fromContributions( diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayProtectedIncarnationReceiverPostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayProtectedIncarnationReceiverPostgresIntegrationTest.java index bb4e781b5f..58f6f84bae 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayProtectedIncarnationReceiverPostgresIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayProtectedIncarnationReceiverPostgresIntegrationTest.java @@ -218,7 +218,7 @@ void changedCurrentSqlContextAfterSourceCallCannotProduceVerifiedEvidence() thro @Test void initialArmVerifiesExactOriginalAndNonzeroNoActiveEpochWithSameTrustedVerifier() throws Exception { - try (InitialFixture fixture = InitialFixture.open()) { + try (Fixture.InitialFixture fixture = Fixture.InitialFixture.open()) { ControlledSigner channel = new ControlledSigner(fixture.keyPair()); var receiver = fixture.receiver(channel); @@ -228,7 +228,8 @@ void initialArmVerifiesExactOriginalAndNonzeroNoActiveEpochWithSameTrustedVerifi .isEqualTo( CanonicalGameplayProtectedIncarnationReceiver.OwnerKind.INITIAL_ACCOUNT_BARRIER); assertThat(verified.requestId()).isEqualTo(fixture.original().requestId()); - assertThat(verified.originalCallerContextId()).isEqualTo(fixture.original().callerContextId()); + assertThat(verified.originalCallerContextId()) + .isEqualTo(fixture.original().callerContextId()); assertThat(verified.originalAttemptFence()).isEqualTo(17L); assertThat(verified.accountId()).isEqualTo(fixture.accountId()); assertThat(verified.sourceControlState()).isEqualTo("NO_ACTIVE_ACCOUNT_WIDE_FLOW"); @@ -240,7 +241,8 @@ void initialArmVerifiesExactOriginalAndNonzeroNoActiveEpochWithSameTrustedVerifi assertThat(repeated.observationNonce()).isNotEqualTo(verified.observationNonce()); assertThat(repeated.incarnationDigest()).isEqualTo(verified.incarnationDigest()); - for (Mutation mutation : List.of(Mutation.WRONG_INITIAL_SOURCE_EPOCH, Mutation.WRONG_INITIAL_ATTEMPT)) { + for (Mutation mutation : + List.of(Mutation.WRONG_INITIAL_SOURCE_EPOCH, Mutation.WRONG_INITIAL_ATTEMPT)) { assertThatThrownBy( () -> fixture @@ -254,7 +256,7 @@ void initialArmVerifiesExactOriginalAndNonzeroNoActiveEpochWithSameTrustedVerifi @Test void changedNoActiveEpochAfterInitialObservationCannotProduceVerifiedEvidence() throws Exception { - try (InitialFixture fixture = InitialFixture.open()) { + try (Fixture.InitialFixture fixture = Fixture.InitialFixture.open()) { ControlledSigner channel = new ControlledSigner(fixture.keyPair(), Mutation.NONE, fixture.dsl()); @@ -331,7 +333,8 @@ public CanonicalGameplayProtectedIncarnationReceiver.SignedObservation observe( case WRONG_OPERATION_ID -> { String field = request.context().ownerKind() - == CanonicalGameplayProtectedIncarnationReceiver.OwnerKind.INITIAL_ACCOUNT_BARRIER + == CanonicalGameplayProtectedIncarnationReceiver.OwnerKind + .INITIAL_ACCOUNT_BARRIER ? "initializerId" : "operationId"; asMap(root.get("owner")).put(field, UUID.randomUUID().toString()); @@ -339,15 +342,14 @@ public CanonicalGameplayProtectedIncarnationReceiver.SignedObservation observe( case WRONG_OPERATION_FENCE -> { String field = request.context().ownerKind() - == CanonicalGameplayProtectedIncarnationReceiver.OwnerKind.INITIAL_ACCOUNT_BARRIER + == CanonicalGameplayProtectedIncarnationReceiver.OwnerKind + .INITIAL_ACCOUNT_BARRIER ? "sourceControlEpoch" : "operationFence"; asMap(root.get("owner")).put(field, "999999"); } - case WRONG_INITIAL_SOURCE_EPOCH -> - asMap(root.get("owner")).put("sourceControlEpoch", "9"); - case WRONG_INITIAL_ATTEMPT -> - asMap(root.get("owner")).put("originalAttemptFence", 18L); + case WRONG_INITIAL_SOURCE_EPOCH -> asMap(root.get("owner")).put("sourceControlEpoch", "9"); + case WRONG_INITIAL_ATTEMPT -> asMap(root.get("owner")).put("originalAttemptFence", 18L); case WRONG_STORAGE_GENERATION -> asMap(root.get("targetDeploymentEvidence")) .put("storageGeneration", "storage-untrusted-response"); @@ -669,242 +671,252 @@ public void close() { dropSchema(schema); } - private static final class InitialFixture implements AutoCloseable { - private final String schema; - private final DSLContext dsl; - private final InitialGameplayLoginAttemptCoordinates original; - private final UUID accountId; - private final UUID tenantId; - private final UUID namespaceId; - private final String targetWorkloadNamespace; - private final KeyPair keyPair; - private final CanonicalGameplayProtectedIncarnationReceiver.ExpectedTargetDeploymentEvidence - expectedEvidence; - private final CanonicalGameplayAccountInitialBarrierInitializerRepository initialRepository; - private final CanonicalGameplayTenantGameplayTagRepository tenantTags; + private static final class InitialFixture implements AutoCloseable { + private final String schema; + private final DSLContext dsl; + private final InitialGameplayLoginAttemptCoordinates original; + private final UUID accountId; + private final UUID tenantId; + private final UUID namespaceId; + private final String targetWorkloadNamespace; + private final KeyPair keyPair; + private final CanonicalGameplayProtectedIncarnationReceiver.ExpectedTargetDeploymentEvidence + expectedEvidence; + private final CanonicalGameplayAccountInitialBarrierInitializerRepository initialRepository; + private final CanonicalGameplayTenantGameplayTagRepository tenantTags; + + private InitialFixture( + String schema, + DSLContext dsl, + InitialGameplayLoginAttemptCoordinates original, + UUID accountId, + UUID tenantId, + UUID namespaceId, + String targetWorkloadNamespace, + KeyPair keyPair, + CanonicalGameplayProtectedIncarnationReceiver.ExpectedTargetDeploymentEvidence + expectedEvidence, + CanonicalGameplayAccountInitialBarrierInitializerRepository initialRepository, + CanonicalGameplayTenantGameplayTagRepository tenantTags) { + this.schema = schema; + this.dsl = dsl; + this.original = original; + this.accountId = accountId; + this.tenantId = tenantId; + this.namespaceId = namespaceId; + this.targetWorkloadNamespace = targetWorkloadNamespace; + this.keyPair = keyPair; + this.expectedEvidence = expectedEvidence; + this.initialRepository = initialRepository; + this.tenantTags = tenantTags; + } - private InitialFixture( - String schema, - DSLContext dsl, - InitialGameplayLoginAttemptCoordinates original, - UUID accountId, - UUID tenantId, - UUID namespaceId, - String targetWorkloadNamespace, - KeyPair keyPair, - CanonicalGameplayProtectedIncarnationReceiver.ExpectedTargetDeploymentEvidence + private static InitialFixture open() throws Exception { + String schema = "gs_initial_incarnation_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName("org.postgresql.Driver"); + String jdbcUrl = postgres.getJdbcUrl(); + String separator = jdbcUrl.contains("?") ? "&" : "?"; + dataSource.setUrl(jdbcUrl + separator + "currentSchema=" + schema); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history") + .locations(MIGRATION_LOCATION) + .load() + .migrate(); + DSLContext dsl = DSL.using(dataSource, SQLDialect.POSTGRES); + UUID tenantId = UUID.randomUUID(); + var runtime = + CanonicalGameplayBindingRuntimeTestFixtures.seedRunningLaunch(dataSource, tenantId); + CanonicalGameplayBindingInventoryRepositoryIntegrationTest + .seedSyntheticVerifiedLegacyDisposition(dsl); + + UUID accountId = UUID.randomUUID(); + UUID transitionId = UUID.randomUUID(); + UUID characterId = UUID.randomUUID(); + var identity = + new CanonicalGameplayBindingIdentity( + accountId, + runtime.canonicalTenantId(), + runtime.playableStateNamespaceId(), + characterId, + "SHARED", + runtime.gameInstanceUuid(), + runtime.gameInstanceId(), + UUID.randomUUID().toString(), + UUID.randomUUID(), + BigInteger.ONE, + GameSessionAccountDelegationProfile.ISSUER, + BigInteger.ONE, + BigInteger.ONE, + BigInteger.valueOf(16), + BigInteger.valueOf(32)); + var reservation = + new CanonicalIssuerReservationFenceEvidence( + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + BigInteger.ONE, + BigInteger.ONE, + BigInteger.ONE); + new CanonicalGameplayBindingInventoryRepository(dsl) + .prepare( + new CanonicalGameplayBindingTransitionRequest( + transitionId, UUID.randomUUID(), identity, reservation, null, null)); + dsl.execute( + "UPDATE game_session_canonical_account_coverage_control" + + " SET last_operation_fence = 8 WHERE account_id = ?", + accountId); + + InitialGameplayLoginAttemptCoordinates original = + new InitialGameplayLoginAttemptCoordinates(UUID.randomUUID(), UUID.randomUUID(), 17L); + var accountLogin = mockInitialLoginResult(original, accountId, UUID.randomUUID()); + dsl.execute( + "INSERT INTO game_session_initial_gameplay_login_journal" + + " (request_id, caller_context_id, expected_attempt_fence) VALUES (?, ?, ?)", + original.requestId(), + original.callerContextId(), + original.expectedAttemptFence()); + dsl.execute( + "UPDATE game_session_initial_gameplay_login_journal" + + " SET verified_token_jti = ?, verified_token_sha256 = ?," + + " verified_token_generation = 1, verified_issuance_fence = 1" + + " WHERE request_id = ?", + accountLogin.evidence().tokenJti(), + accountLogin.evidence().tokenSha256(), + original.requestId()); + CanonicalGameplayAccountInitialBarrierInitializerRepository initialRepository = + new CanonicalGameplayAccountInitialBarrierInitializerRepository(dsl); + initialRepository.beginOrRead( + original, + accountLogin, + runtime.canonicalTenantId(), + runtime.playableStateNamespaceId()); + accountLogin.close(); + + KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); + generator.initialize(2048); + KeyPair keyPair = generator.generateKeyPair(); + var expectedEvidence = controlledExpectedEvidence(); + var tenantTags = + new CanonicalGameplayTenantGameplayTagRepository(dsl, runtime.targetNamespace(), 1); + return new InitialFixture( + schema, + dsl, + original, + accountId, + runtime.canonicalTenantId(), + runtime.playableStateNamespaceId(), + runtime.targetNamespace(), + keyPair, expectedEvidence, - CanonicalGameplayAccountInitialBarrierInitializerRepository initialRepository, - CanonicalGameplayTenantGameplayTagRepository tenantTags) { - this.schema = schema; - this.dsl = dsl; - this.original = original; - this.accountId = accountId; - this.tenantId = tenantId; - this.namespaceId = namespaceId; - this.targetWorkloadNamespace = targetWorkloadNamespace; - this.keyPair = keyPair; - this.expectedEvidence = expectedEvidence; - this.initialRepository = initialRepository; - this.tenantTags = tenantTags; - } - - private static InitialFixture open() throws Exception { - String schema = "gs_initial_incarnation_" + UUID.randomUUID().toString().replace("-", ""); - DriverManagerDataSource dataSource = new DriverManagerDataSource(); - dataSource.setDriverClassName("org.postgresql.Driver"); - String jdbcUrl = postgres.getJdbcUrl(); - String separator = jdbcUrl.contains("?") ? "&" : "?"; - dataSource.setUrl(jdbcUrl + separator + "currentSchema=" + schema); - dataSource.setUsername(postgres.getUsername()); - dataSource.setPassword(postgres.getPassword()); - Flyway.configure() - .dataSource(dataSource) - .schemas(schema) - .defaultSchema(schema) - .table("flyway_schema_history") - .locations(MIGRATION_LOCATION) - .load() - .migrate(); - DSLContext dsl = DSL.using(dataSource, SQLDialect.POSTGRES); - UUID tenantId = UUID.randomUUID(); - var runtime = - CanonicalGameplayBindingRuntimeTestFixtures.seedRunningLaunch(dataSource, tenantId); - CanonicalGameplayBindingInventoryRepositoryIntegrationTest - .seedSyntheticVerifiedLegacyDisposition(dsl); - - UUID accountId = UUID.randomUUID(); - UUID transitionId = UUID.randomUUID(); - UUID characterId = UUID.randomUUID(); - var identity = - new CanonicalGameplayBindingIdentity( - accountId, - runtime.canonicalTenantId(), - runtime.playableStateNamespaceId(), - characterId, - "SHARED", - runtime.gameInstanceUuid(), - runtime.gameInstanceId(), - UUID.randomUUID().toString(), - UUID.randomUUID(), - BigInteger.ONE, - GameSessionAccountDelegationProfile.ISSUER, - BigInteger.ONE, - BigInteger.ONE, - BigInteger.valueOf(16), - BigInteger.valueOf(32)); - var reservation = - new CanonicalIssuerReservationFenceEvidence( - UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID(), BigInteger.ONE, BigInteger.ONE, BigInteger.ONE); - new CanonicalGameplayBindingInventoryRepository(dsl) - .prepare( - new CanonicalGameplayBindingTransitionRequest( - transitionId, UUID.randomUUID(), identity, reservation, null, null)); - dsl.execute( - "UPDATE game_session_canonical_account_coverage_control" - + " SET last_operation_fence = 8 WHERE account_id = ?", - accountId); - - InitialGameplayLoginAttemptCoordinates original = - new InitialGameplayLoginAttemptCoordinates(UUID.randomUUID(), UUID.randomUUID(), 17L); - var accountLogin = mockInitialLoginResult(original, accountId, UUID.randomUUID()); - dsl.execute( - "INSERT INTO game_session_initial_gameplay_login_journal" - + " (request_id, caller_context_id, expected_attempt_fence) VALUES (?, ?, ?)", - original.requestId(), - original.callerContextId(), - original.expectedAttemptFence()); - dsl.execute( - "UPDATE game_session_initial_gameplay_login_journal" - + " SET verified_token_jti = ?, verified_token_sha256 = ?," - + " verified_token_generation = 1, verified_issuance_fence = 1" - + " WHERE request_id = ?", - accountLogin.evidence().tokenJti(), - accountLogin.evidence().tokenSha256(), - original.requestId()); - CanonicalGameplayAccountInitialBarrierInitializerRepository initialRepository = - new CanonicalGameplayAccountInitialBarrierInitializerRepository(dsl); - initialRepository.beginOrRead( - original, accountLogin, runtime.canonicalTenantId(), runtime.playableStateNamespaceId()); - accountLogin.close(); - - KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); - generator.initialize(2048); - KeyPair keyPair = generator.generateKeyPair(); - var expectedEvidence = controlledExpectedEvidence(); - var tenantTags = - new CanonicalGameplayTenantGameplayTagRepository( - dsl, runtime.targetNamespace(), 1); - return new InitialFixture( - schema, - dsl, - original, - accountId, - runtime.canonicalTenantId(), - runtime.playableStateNamespaceId(), - runtime.targetNamespace(), - keyPair, - expectedEvidence, - initialRepository, - tenantTags); - } + initialRepository, + tenantTags); + } - private CanonicalGameplayProtectedIncarnationReceiver receiver( - CanonicalGameplayProtectedIncarnationReceiver.ProtectedObservationChannel channel) { - return receiver( - channel, - new CanonicalGameplayProtectedIncarnationReceiver.TrustedConfiguration( - ATTESTOR_BINDING, - ACCEPTED_ATTESTATION_DIGEST, - Map.of(KEY_ID, (java.security.interfaces.RSAPublicKey) keyPair.getPublic()), - expectedEvidence, - ACL_DIGEST, - CONFIG_DIGEST, - 16 * 1024, - 1, - Duration.ofSeconds(30))); - } + private CanonicalGameplayProtectedIncarnationReceiver receiver( + CanonicalGameplayProtectedIncarnationReceiver.ProtectedObservationChannel channel) { + return receiver( + channel, + new CanonicalGameplayProtectedIncarnationReceiver.TrustedConfiguration( + ATTESTOR_BINDING, + ACCEPTED_ATTESTATION_DIGEST, + Map.of(KEY_ID, (java.security.interfaces.RSAPublicKey) keyPair.getPublic()), + expectedEvidence, + ACL_DIGEST, + CONFIG_DIGEST, + 16 * 1024, + 1, + Duration.ofSeconds(30))); + } - private CanonicalGameplayProtectedIncarnationReceiver receiver( - CanonicalGameplayProtectedIncarnationReceiver.ProtectedObservationChannel channel, - CanonicalGameplayProtectedIncarnationReceiver.TrustedConfiguration configuration) { - return new CanonicalGameplayProtectedIncarnationReceiver( - initialRepository, tenantTags, channel, configuration, Clock.fixed(NOW, ZoneOffset.UTC)); - } + private CanonicalGameplayProtectedIncarnationReceiver receiver( + CanonicalGameplayProtectedIncarnationReceiver.ProtectedObservationChannel channel, + CanonicalGameplayProtectedIncarnationReceiver.TrustedConfiguration configuration) { + return new CanonicalGameplayProtectedIncarnationReceiver( + initialRepository, + tenantTags, + channel, + configuration, + Clock.fixed(NOW, ZoneOffset.UTC)); + } - private InitialGameplayLoginAttemptCoordinates original() { - return original; - } + private InitialGameplayLoginAttemptCoordinates original() { + return original; + } - private UUID accountId() { - return accountId; - } + private UUID accountId() { + return accountId; + } - private KeyPair keyPair() { - return keyPair; - } + private KeyPair keyPair() { + return keyPair; + } - private DSLContext dsl() { - return dsl; - } + private DSLContext dsl() { + return dsl; + } - private CanonicalGameplayProtectedIncarnationReceiver.ExpectedTargetDeploymentEvidence - expectedEvidence() { - return expectedEvidence; - } + private CanonicalGameplayProtectedIncarnationReceiver.ExpectedTargetDeploymentEvidence + expectedEvidence() { + return expectedEvidence; + } - @Override - public void close() { - try (var connection = - java.sql.DriverManager.getConnection( - postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); - var statement = connection.createStatement()) { - statement.execute("DROP SCHEMA IF EXISTS " + schema + " CASCADE"); - } catch (Exception failure) { - throw new IllegalStateException("Could not dispose INITIAL observation schema", failure); + @Override + public void close() { + try (var connection = + java.sql.DriverManager.getConnection( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); + var statement = connection.createStatement()) { + statement.execute("DROP SCHEMA IF EXISTS " + schema + " CASCADE"); + } catch (Exception failure) { + throw new IllegalStateException("Could not dispose INITIAL observation schema", failure); + } } } - } - private static CanonicalGameplayLoginResult mockInitialLoginResult( - InitialGameplayLoginAttemptCoordinates original, UUID accountId, UUID tokenJti) { - var evidence = - new CanonicalGameplayLoginResult.NonSecretEvidence( - accountId, - original.requestId(), - original.callerContextId(), - tokenJti, - "e".repeat(64), - GameSessionAccountDelegationProfile.PROFILE, - NOW.getEpochSecond(), - NOW.getEpochSecond(), - NOW.plusSeconds(120).getEpochSecond(), - "1", - "1", - ByteString.copyFromUtf8("{}"), - ByteString.copyFromUtf8("[]"), - ByteString.copyFromUtf8("[]")); - CanonicalGameplayLoginResult result = mock(CanonicalGameplayLoginResult.class); - when(result.evidence()).thenReturn(evidence); - return result; - } - - private static - CanonicalGameplayProtectedIncarnationReceiver.ExpectedTargetDeploymentEvidence - controlledExpectedEvidence() { - return new CanonicalGameplayProtectedIncarnationReceiver.ExpectedTargetDeploymentEvidence( - "controlled-target-deployment", - "generation-7", - List.of("redis-node-a"), - "redis-test-build", - "registry-test-v1", - "sha256:" + "d".repeat(64), - "READY", - "boot-7", - "startup-7", - "storage-7", - "aof-7"); - } + private static CanonicalGameplayLoginResult mockInitialLoginResult( + InitialGameplayLoginAttemptCoordinates original, UUID accountId, UUID tokenJti) { + var evidence = + new CanonicalGameplayLoginResult.NonSecretEvidence( + accountId, + original.requestId(), + original.callerContextId(), + tokenJti, + "e".repeat(64), + GameSessionAccountDelegationProfile.PROFILE, + NOW.getEpochSecond(), + NOW.getEpochSecond(), + NOW.plusSeconds(120).getEpochSecond(), + "1", + "1", + ByteString.copyFromUtf8("{}"), + ByteString.copyFromUtf8("[]"), + ByteString.copyFromUtf8("[]")); + CanonicalGameplayLoginResult result = mock(CanonicalGameplayLoginResult.class); + when(result.evidence()).thenReturn(evidence); + return result; + } + + private static CanonicalGameplayProtectedIncarnationReceiver.ExpectedTargetDeploymentEvidence + controlledExpectedEvidence() { + return new CanonicalGameplayProtectedIncarnationReceiver.ExpectedTargetDeploymentEvidence( + "controlled-target-deployment", + "generation-7", + List.of("redis-node-a"), + "redis-test-build", + "registry-test-v1", + "sha256:" + "d".repeat(64), + "READY", + "boot-7", + "startup-7", + "storage-7", + "aof-7"); + } private static DriverManagerDataSource dataSource(String schema) { DriverManagerDataSource dataSource = new DriverManagerDataSource(); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierRedisOwnerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierRedisOwnerTest.java index 6f02d96df2..d0124cad6b 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierRedisOwnerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierRedisOwnerTest.java @@ -3,6 +3,8 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; @@ -19,8 +21,8 @@ import java.util.List; import java.util.Map; import java.util.UUID; -import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; import net.firedevops.firemud.gamesession.dto.CanonicalGameplayLoginResult; import net.firedevops.firemud.gamesession.dto.InitialGameplayLoginAttemptCoordinates; @@ -32,7 +34,8 @@ class CanonicalGameplayAccountInitialBarrierRedisOwnerTest { @Test @SuppressWarnings({"unchecked", "rawtypes"}) - void missingPhysicalValueAfterPossibleDispatchRefusesWithoutFreshScriptAttempt() throws Exception { + void missingPhysicalValueAfterPossibleDispatchRefusesWithoutFreshScriptAttempt() + throws Exception { UUID requestId = UUID.randomUUID(); UUID callerContextId = UUID.randomUUID(); UUID initializerId = UUID.randomUUID(); @@ -80,7 +83,8 @@ void missingPhysicalValueAfterPossibleDispatchRefusesWithoutFreshScriptAttempt() var observation = mock(CanonicalGameplayProtectedIncarnationReceiver.VerifiedIncarnation.class); when(observation.ownerKind()) - .thenReturn(CanonicalGameplayProtectedIncarnationReceiver.OwnerKind.INITIAL_ACCOUNT_BARRIER); + .thenReturn( + CanonicalGameplayProtectedIncarnationReceiver.OwnerKind.INITIAL_ACCOUNT_BARRIER); when(observation.operationId()).thenReturn(initializerId); when(observation.requestId()).thenReturn(requestId); when(observation.originalCallerContextId()).thenReturn(callerContextId); @@ -105,8 +109,8 @@ void missingPhysicalValueAfterPossibleDispatchRefusesWithoutFreshScriptAttempt() when(redis.connect(any(ByteArrayCodec.class))).thenReturn(connection); when(connection.isOpen()).thenReturn(true); when(connection.async()).thenReturn(commands); - when(commands.aclWhoami()).thenReturn(future("gamesession_coord_app")); - when(commands.type(any(byte[].class))).thenReturn(future("none")); + doReturn(future("gamesession_coord_app")).when(commands).aclWhoami(); + doReturn(future("none")).when(commands).type(any(byte[].class)); RedisScriptCatalog catalog = mock(RedisScriptCatalog.class); var owner = @@ -114,16 +118,14 @@ void missingPhysicalValueAfterPossibleDispatchRefusesWithoutFreshScriptAttempt() redis, catalog, repository, tenantTags, receiver); var proof = owner.initializeOnce( - original, - mock(CanonicalGameplayLoginResult.class), - tenantId, - namespaceId); + original, mock(CanonicalGameplayLoginResult.class), tenantId, namespaceId); assertThat(proof) .isEqualTo( new CanonicalGameplayAccountInitialOpenProof.Refused( CanonicalGameplayAccountInitialOpenProof.Reason.REMOTE_OUTCOME_UNCERTAIN)); - verify(repository).beginOrRead(original, org.mockito.ArgumentMatchers.any(), tenantId, namespaceId); + verify(repository) + .beginOrRead(eq(original), any(), eq(tenantId), eq(namespaceId)); verify(commands).type(any(byte[].class)); verifyNoInteractions(catalog); } @@ -206,10 +208,7 @@ void possibleDispatchIsPersistedBeforeRedisAndMissingAfterwardNeverGetsAFreshCre var proof = owner.initializeOnce( - original, - mock(CanonicalGameplayLoginResult.class), - tenantId, - namespaceId); + original, mock(CanonicalGameplayLoginResult.class), tenantId, namespaceId); assertThat(proof) .isEqualTo( @@ -274,28 +273,32 @@ void exactSameOriginalOpenReplayIsReadOnlyAndReturnsCurrentTypedProof() throws E CanonicalGameplayAccountInitialBarrierValue.open( accountId, tenantId, namespaceId, tag, initializerId, BigInteger.valueOf(8), DIGEST); Map raw = new HashMap<>(); - expected.fields().forEach( - (field, value) -> - raw.put( - field.getBytes(StandardCharsets.US_ASCII), - value.getBytes(StandardCharsets.US_ASCII))); + expected + .fields() + .forEach( + (field, value) -> + raw.put( + field.getBytes(StandardCharsets.US_ASCII), + value.getBytes(StandardCharsets.US_ASCII))); RedisClient redis = mock(RedisClient.class); StatefulRedisConnection connection = mock(StatefulRedisConnection.class); RedisAsyncCommands commands = mock(RedisAsyncCommands.class); when(redis.connect(any(ByteArrayCodec.class))).thenReturn(connection); when(connection.isOpen()).thenReturn(true); when(connection.async()).thenReturn(commands); - when(commands.aclWhoami()).thenReturn(future("gamesession_coord_app")); - when(commands.type(any(byte[].class))).thenReturn(future("hash")); - when(commands.pttl(any(byte[].class))).thenReturn(future(-1L)); - when(commands.hlen(any(byte[].class))).thenReturn(future(9L)); - when(commands.hgetall(any(byte[].class))).thenReturn(future(raw)); + doReturn(future("gamesession_coord_app")).when(commands).aclWhoami(); + doReturn(future("hash")).when(commands).type(any(byte[].class)); + doReturn(future(-1L)).when(commands).pttl(any(byte[].class)); + doReturn(future(9L)).when(commands).hlen(any(byte[].class)); + doReturn(future(raw)).when(commands).hgetall(any(byte[].class)); RedisScriptCatalog catalog = mock(RedisScriptCatalog.class); var owner = new CanonicalGameplayAccountInitialBarrierRedisOwner( redis, catalog, repository, tenantTags, receiver); - var proof = owner.initializeOnce(original, mock(CanonicalGameplayLoginResult.class), tenantId, namespaceId); + var proof = + owner.initializeOnce( + original, mock(CanonicalGameplayLoginResult.class), tenantId, namespaceId); assertThat(proof).isInstanceOf(CanonicalGameplayAccountInitialOpenProof.CurrentOpen.class); var current = (CanonicalGameplayAccountInitialOpenProof.CurrentOpen) proof; @@ -303,7 +306,8 @@ void exactSameOriginalOpenReplayIsReadOnlyAndReturnsCurrentTypedProof() throws E assertThat(current.sourceControlEpoch()).isEqualTo(BigInteger.valueOf(8)); assertThat(current.exactFields()).isEqualTo(expected.fields()); verify(repository, org.mockito.Mockito.times(2)).readCurrent(requestId); - verify(repository).beginOrRead(original, org.mockito.ArgumentMatchers.any(), tenantId, namespaceId); + verify(repository) + .beginOrRead(eq(original), any(), eq(tenantId), eq(namespaceId)); verify(repository, org.mockito.Mockito.times(3)).requireNoAmbientTransaction(); verify(receiver, org.mockito.Mockito.times(2)).observeForInitialAccountBarrier(requestId); verifyNoInteractions(catalog); @@ -391,34 +395,38 @@ void ambiguousDispatchRetryRequiresExactOpenReadbackBeforeCompletingOriginalRece CanonicalGameplayAccountInitialBarrierValue.open( accountId, tenantId, namespaceId, tag, initializerId, BigInteger.valueOf(8), DIGEST); Map raw = new HashMap<>(); - expected.fields().forEach( - (field, value) -> - raw.put( - field.getBytes(StandardCharsets.US_ASCII), - value.getBytes(StandardCharsets.US_ASCII))); + expected + .fields() + .forEach( + (field, value) -> + raw.put( + field.getBytes(StandardCharsets.US_ASCII), + value.getBytes(StandardCharsets.US_ASCII))); RedisClient redis = mock(RedisClient.class); StatefulRedisConnection connection = mock(StatefulRedisConnection.class); RedisAsyncCommands commands = mock(RedisAsyncCommands.class); when(redis.connect(any(ByteArrayCodec.class))).thenReturn(connection); when(connection.isOpen()).thenReturn(true); when(connection.async()).thenReturn(commands); - when(commands.aclWhoami()).thenReturn(future("gamesession_coord_app")); - when(commands.type(any(byte[].class))).thenReturn(future("hash")); - when(commands.pttl(any(byte[].class))).thenReturn(future(-1L)); - when(commands.hlen(any(byte[].class))).thenReturn(future(9L)); - when(commands.hgetall(any(byte[].class))).thenReturn(future(raw)); + doReturn(future("gamesession_coord_app")).when(commands).aclWhoami(); + doReturn(future("hash")).when(commands).type(any(byte[].class)); + doReturn(future(-1L)).when(commands).pttl(any(byte[].class)); + doReturn(future(9L)).when(commands).hlen(any(byte[].class)); + doReturn(future(raw)).when(commands).hgetall(any(byte[].class)); RedisScriptCatalog catalog = mock(RedisScriptCatalog.class); var owner = new CanonicalGameplayAccountInitialBarrierRedisOwner( redis, catalog, repository, tenantTags, receiver); - var proof = owner.initializeOnce(original, mock(CanonicalGameplayLoginResult.class), tenantId, namespaceId); + var proof = + owner.initializeOnce( + original, mock(CanonicalGameplayLoginResult.class), tenantId, namespaceId); assertThat(proof).isInstanceOf(CanonicalGameplayAccountInitialOpenProof.CurrentOpen.class); var current = (CanonicalGameplayAccountInitialOpenProof.CurrentOpen) proof; assertThat(current.originalRequestId()).isEqualTo(requestId); assertThat(current.exactFields()).isEqualTo(expected.fields()); - verify(repository).acceptOpenReadback(requestId, org.mockito.ArgumentMatchers.any()); + verify(repository).acceptOpenReadback(eq(requestId), any()); verify(repository).readCurrent(requestId); verify(receiver, org.mockito.Mockito.times(2)).observeForInitialAccountBarrier(requestId); verifyNoInteractions(catalog); @@ -460,10 +468,12 @@ void ambiguousDispatchRetryRequiresExactOpenReadbackBeforeCompletingOriginalRece private static CanonicalGameplayProtectedIncarnationReceiver.VerifiedIncarnation initialObservation( - CanonicalGameplayAccountInitialBarrierInitializerRepository.InitializerSnapshot snapshot) { + CanonicalGameplayAccountInitialBarrierInitializerRepository.InitializerSnapshot + snapshot) { var observation = mock(CanonicalGameplayProtectedIncarnationReceiver.VerifiedIncarnation.class); when(observation.ownerKind()) - .thenReturn(CanonicalGameplayProtectedIncarnationReceiver.OwnerKind.INITIAL_ACCOUNT_BARRIER); + .thenReturn( + CanonicalGameplayProtectedIncarnationReceiver.OwnerKind.INITIAL_ACCOUNT_BARRIER); when(observation.operationId()).thenReturn(snapshot.initializerId()); when(observation.requestId()).thenReturn(snapshot.originalRequestId()); when(observation.originalCallerContextId()).thenReturn(snapshot.originalCallerContextId()); @@ -475,7 +485,8 @@ void ambiguousDispatchRetryRequiresExactOpenReadbackBeforeCompletingOriginalRece when(observation.sourceControlEpoch()).thenReturn(snapshot.sourceControlEpoch().toString()); when(observation.inventorySnapshotRevision()) .thenReturn(snapshot.inventorySnapshotRevision().toString()); - when(observation.accountLoginEvidenceDigest()).thenReturn(snapshot.accountLoginEvidenceDigest()); + when(observation.accountLoginEvidenceDigest()) + .thenReturn(snapshot.accountLoginEvidenceDigest()); when(observation.sourceControlDigest()).thenReturn(snapshot.sourceControlDigest()); when(observation.barrierTargetDigest()).thenReturn(snapshot.targetDigest()); when(observation.incarnationDigest()).thenReturn(DIGEST); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierValueTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierValueTest.java index e72605e73d..8ce2a1fa43 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierValueTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierValueTest.java @@ -34,15 +34,24 @@ void initialBarrierValueRetainsTheExactPositivelyReadEpochIncludingZero() { assertThat(value.fields()) .containsExactlyInAnyOrderEntriesOf( Map.of( - "schema", CanonicalGameplayAccountInitialBarrierValue.SCHEMA, - "accountId", accountId.toString(), - "tenantId", tenantId.toString(), - "playableStateNamespaceId", namespaceId.toString(), - "tenantGameplayTag", "g7-" + "b".repeat(32), - "ownerOperationId", initializerId.toString(), - "ownerFenceEpoch", "0", - "incarnationDigest", DIGEST, - "state", "OPEN")); + "schema", + CanonicalGameplayAccountInitialBarrierValue.SCHEMA, + "accountId", + accountId.toString(), + "tenantId", + tenantId.toString(), + "playableStateNamespaceId", + namespaceId.toString(), + "tenantGameplayTag", + "g7-" + "b".repeat(32), + "ownerOperationId", + initializerId.toString(), + "ownerFenceEpoch", + "0", + "incarnationDigest", + DIGEST, + "state", + "OPEN")); assertThat(value.fields().keySet()) .containsExactlyInAnyOrderElementsOf(CanonicalGameplayAccountInitialBarrierValue.FIELDS); } @@ -74,7 +83,12 @@ void currentOpenProofRequiresExactCapturedEpochOriginalAttemptAndNineFields() { accountId, tenantId, namespaceId, - "session:game:account-admission:{g8-" + "c".repeat(32) + "}:" + accountId + ":" + namespaceId, + "session:game:account-admission:{g8-" + + "c".repeat(32) + + "}:" + + accountId + + ":" + + namespaceId, BigInteger.valueOf(9), BigInteger.ONE, DIGEST, @@ -152,8 +166,7 @@ void initialKeyUsesCanonicalBarrierSerializationOnlyForItsPersistedOriginalTarge when(assignment.isInitialBarrierTarget()).thenReturn(true); when(assignment.initialBarrierInitializerId()).thenReturn(initializerId); when(assignment.initialBarrierOriginalRequestId()).thenReturn(requestId); - when(assignment.tenantGameplayTag()) - .thenReturn("g7-" + tenantId.toString().replace("-", "")); + when(assignment.tenantGameplayTag()).thenReturn("g7-" + tenantId.toString().replace("-", "")); when(assignment.accountId()).thenReturn(accountId); when(assignment.playableStateNamespaceId()).thenReturn(namespaceId); @@ -164,7 +177,7 @@ void initialKeyUsesCanonicalBarrierSerializationOnlyForItsPersistedOriginalTarge .isEqualTo( "session:game:account-admission:{g7-" + tenantId.toString().replace("-", "") - + "]:" + + "}:" + accountId + ":" + namespaceId); @@ -173,8 +186,7 @@ void initialKeyUsesCanonicalBarrierSerializationOnlyForItsPersistedOriginalTarge CanonicalGameplayAccountInitialBarrierKey.forTarget( assignment, UUID.randomUUID(), requestId)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> CanonicalGameplaySessionRedisKeys.accountAdmissionBarrier(assignment)) + assertThatThrownBy(() -> CanonicalGameplaySessionRedisKeys.accountAdmissionBarrier(assignment)) .isInstanceOf(IllegalArgumentException.class); } } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCandidateTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCandidateTest.java index 39848d20a9..47d96cb69f 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCandidateTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCandidateTest.java @@ -60,7 +60,10 @@ void retainsExactNonAdmittingCandidateAndStableRetryBytes() { assertThat( first.matchesProvisionalSources( provisionalEvidence( - prepared.identity(), prepared.bindingGeneration(), BigInteger.valueOf(28), true))) + prepared.identity(), + prepared.bindingGeneration(), + BigInteger.valueOf(28), + true))) .isTrue(); CanonicalGameplayOriginalNewCandidate decoded = @@ -73,9 +76,15 @@ void retainsExactNonAdmittingCandidateAndStableRetryBytes() { assertThat(decoded.transition().transitionId()).isEqualTo(prepared.decision().transitionId()); assertThat(decoded.reservation().bindingGeneration()).isEqualTo(BigInteger.valueOf(7)); assertThat(decoded.reservation().inventorySnapshotRevision()).isEqualTo(BigInteger.valueOf(19)); - assertThat(first.matchesProvisionalSources(provisionalEvidence( - prepared.identity(), prepared.bindingGeneration(), BigInteger.valueOf(28), true, - BigInteger.valueOf(20)))).isFalse(); + assertThat( + first.matchesProvisionalSources( + provisionalEvidence( + prepared.identity(), + prepared.bindingGeneration(), + BigInteger.valueOf(28), + true, + BigInteger.valueOf(20)))) + .isFalse(); String encoded = first.canonicalJson(); assertThat(encoded) @@ -92,7 +101,8 @@ void retainsExactNonAdmittingCandidateAndStableRetryBytes() { "raw-original-jwt", "private-rebind-handle"); assertThat(first.toString()) - .doesNotContain(prepared.leaseEvidence().sha256(), "raw-original-jwt", "private-rebind-handle"); + .doesNotContain( + prepared.leaseEvidence().sha256(), "raw-original-jwt", "private-rebind-handle"); } @Test @@ -165,19 +175,29 @@ void rejectsUnknownDuplicateMalformedOversizedNoncanonicalAndOutOfBoundInput() { preparedEvidence(original), original.decision()) .canonicalJson(); - rejects(canonical.replace( - "\"purpose\":\"" + CanonicalGameplayOriginalNewCandidate.PURPOSE + "\"", - "\"purpose\":\"" + CanonicalGameplayOriginalNewCandidate.PURPOSE + "\",\"extra\":\"x\"")); - rejects(canonical.replace( - "\"purpose\":\"" + CanonicalGameplayOriginalNewCandidate.PURPOSE + "\"", - "\"purpose\":\"" + CanonicalGameplayOriginalNewCandidate.PURPOSE + "\",\"purpose\":\"" - + CanonicalGameplayOriginalNewCandidate.PURPOSE + "\"")); - rejects(canonical.replace( - "\"leaseKind\":\"NEW_BINDING\"", - "\"leaseKind\":\"NEW_BINDING\",\"leaseKind\":\"NEW_BINDING\"")); + rejects( + canonical.replace( + "\"purpose\":\"" + CanonicalGameplayOriginalNewCandidate.PURPOSE + "\"", + "\"purpose\":\"" + + CanonicalGameplayOriginalNewCandidate.PURPOSE + + "\",\"extra\":\"x\"")); + rejects( + canonical.replace( + "\"purpose\":\"" + CanonicalGameplayOriginalNewCandidate.PURPOSE + "\"", + "\"purpose\":\"" + + CanonicalGameplayOriginalNewCandidate.PURPOSE + + "\",\"purpose\":\"" + + CanonicalGameplayOriginalNewCandidate.PURPOSE + + "\"")); + rejects( + canonical.replace( + "\"leaseKind\":\"NEW_BINDING\"", + "\"leaseKind\":\"NEW_BINDING\",\"leaseKind\":\"NEW_BINDING\"")); rejects(" " + canonical); rejects(canonical.replace("\"bindingGeneration\":\"7\"", "\"bindingGeneration\":\"07\"")); - rejects(canonical.replace("\"bindingDecisionId\":\"" + id(500) + "\"", "\"bindingDecisionId\":\"not-a-uuid\"")); + rejects( + canonical.replace( + "\"bindingDecisionId\":\"" + id(500) + "\"", "\"bindingDecisionId\":\"not-a-uuid\"")); rejects("{"); byte[] canonicalBytes = canonical.getBytes(StandardCharsets.UTF_8); @@ -209,7 +229,8 @@ private static CanonicalGameplayBindingProvisionalCasEvidence provisionalEvidenc BigInteger generation, BigInteger inventoryRevision, boolean provisional) { - return provisionalEvidence(identity, generation, inventoryRevision, provisional, BigInteger.valueOf(19)); + return provisionalEvidence( + identity, generation, inventoryRevision, provisional, BigInteger.valueOf(19)); } private static CanonicalGameplayBindingProvisionalCasEvidence provisionalEvidence( @@ -335,7 +356,12 @@ private static CanonicalGameplayBindingProvisionalCasEvidence evidenceWithStatus null, null, new CanonicalGameplayLegacyMigrationDisposition( - id(505), id(506), id(507), BigInteger.ONE, BigInteger.TWO, BigInteger.valueOf(3), + id(505), + id(506), + id(507), + BigInteger.ONE, + BigInteger.TWO, + BigInteger.valueOf(3), "sha256:" + "f".repeat(64))); } @@ -347,8 +373,7 @@ private static Bundle bundle( AccountGameplayAdmissionLeaseEvidence.fromCarrier( leaseCarrier(identity, target, alternateLease, generation)); var decision = - new CanonicalGameplayAdmissionDecision( - id(500), lease, identity, generation, null, target); + new CanonicalGameplayAdmissionDecision(id(500), lease, identity, generation, null, target); return new Bundle(identity, generation, target, lease, decision); } @@ -472,11 +497,10 @@ private static Map leaseCarrier( .map( stream -> Map.of( - "outboxStreamKey", stream, + "outboxStreamKey", + stream, "outboxSequence", - stream.contains("tenant/") || stream.contains("membership/") - ? "4" - : "0")) + stream.contains("tenant/") || stream.contains("membership/") ? "4" : "0")) .toList()); carrier.put( "tokenIdentityEvidence", @@ -499,7 +523,7 @@ private static Map leaseCarrier( } private static UUID id(long value) { - return new UUID(0L, value); + return new UUID(0x4000L, Long.MIN_VALUE | value); } private record Bundle( From c01154b91404efe5d8e8b6c772c33699815aee74 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 27 Oct 2026 12:54:50 +1300 Subject: [PATCH 05/26] Prepare original NEW candidates and bound Account credentials --- .../account-service/runtime-and-data.md | 2 +- design/project-management/ai-observations.md | 10 + .../player-access-and-session.md | 6 +- .../v1/account_gameplay_admission_lease.proto | 54 +- ...ntOriginalNewFinalAdmissionReadClient.java | 154 +++ .../AccountGameplayTokenIdentityFence.java | 31 +- ...ssionOriginalAckReceiptCommitExecutor.java | 69 +- ...AdmissionOriginalAckReceiptRepository.java | 44 +- ...tGameplayTokenIdentityFenceRepository.java | 73 +- ...iginalNewBoundGameplayCredentialOwner.java | 1198 +++++++++++++++++ ...nalNewBoundGameplayIssuanceRepository.java | 935 +++++++++++++ ...ountGameplayAdmissionLeaseGrpcService.java | 112 +- ...ntGameplayAdmissionLeaseManualFactory.java | 45 + ...ntGameplayAdmissionLeaseWorkloadGuard.java | 36 + .../AccountGameplayDelegationRedisClient.java | 240 ++++ .../AccountGameplayDelegationSigner.java | 308 +++++ ...ccountGameplayDelegationTokenRegistry.java | 123 ++ .../AccountMountedJwtSignerBundle.java | 154 +++ ...riginal_new_bound_gameplay_credentials.sql | 370 +++++ ..._original_ack_pg18_historical_recovery.sql | 142 ++ ...rotectedEntryPrototypeIntegrationTest.java | 514 ++++++- ...ameplayCredentialOwnerIntegrationTest.java | 693 ++++++++++ ...nOriginalAckReceiptCommitExecutorTest.java | 239 +++- ...eplayTokenIdentityFenceRepositoryTest.java | 70 +- ...alNewBoundGameplayCredentialOwnerTest.java | 50 + .../AccountGameplayDelegationSignerTest.java | 100 ++ ...ccountGameplayAdmissionLeaseGrpcCodec.java | 612 ++++++++- ...ntGameplayAdmissionLeaseGrpcCodecTest.java | 152 +++ .../AccountGameplayAdmissionLeaseClient.java | 74 +- ...ntInitialBarrierInitializerRepository.java | 68 +- ...meplayAccountInitialBarrierRedisOwner.java | 43 + ...calGameplayBindingInventoryRepository.java | 326 +++++ .../CanonicalGameplayIssuerCohortSql.java | 11 +- ...meplayOriginalNewAuthenticatedSession.java | 587 ++++++++ ...layOriginalNewBoundCredentialVerifier.java | 318 +++++ ...ameplayOriginalNewCandidateRedisOwner.java | 547 ++++++++ ...OriginalNewCandidateRedisOwnerFactory.java | 22 + ...alNewCandidateRedisScriptContribution.java | 52 + ...on.redis.contracts.RedisScriptContribution | 1 + ...al_original_new_candidate_installation.sql | 106 ++ ...session-original-new-candidate-install.lua | 79 ++ ...ession-original-new-candidate-install.json | 40 + ...ssionBarrierRepositoryIntegrationTest.java | 4 +- ...losedBarrierRedisOwnerIntegrationTest.java | 156 ++- ...calGameplayBindingRuntimeTestFixtures.java | 2 +- ...ssionBarrierRepositoryIntegrationTest.java | 25 +- ...BindingLocalRedisOwnerIntegrationTest.java | 7 +- ...rtitionBuildRepositoryIntegrationTest.java | 14 + ...NewCandidateRedisOwnerIntegrationTest.java | 659 +++++++++ ...nationReceiverPostgresIntegrationTest.java | 220 ++- ...countGameplayAdmissionLeaseClientTest.java | 206 +++ ...ayAccountInitialBarrierRedisOwnerTest.java | 170 ++- ...ayOriginalNewAuthenticatedSessionTest.java | 709 ++++++++++ 53 files changed, 10872 insertions(+), 110 deletions(-) create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/AccountOriginalNewFinalAdmissionReadClient.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountOriginalNewBoundGameplayCredentialOwner.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountOriginalNewBoundGameplayIssuanceRepository.java create mode 100644 services/account-service/src/main/resources/db/migration/V161__account_original_new_bound_gameplay_credentials.sql create mode 100644 services/account-service/src/main/resources/db/migration/V162__account_original_ack_pg18_historical_recovery.sql create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountOriginalNewBoundGameplayCredentialOwnerIntegrationTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountOriginalNewBoundGameplayCredentialOwnerTest.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewAuthenticatedSession.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewBoundCredentialVerifier.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCandidateRedisOwner.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCandidateRedisOwnerFactory.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayOriginalNewCandidateRedisScriptContribution.java create mode 100644 services/game-session-service/src/main/resources/db/migration/V1048__canonical_original_new_candidate_installation.sql create mode 100644 services/game-session-service/src/main/resources/redis/lua/game-session-original-new-candidate-install.lua create mode 100644 services/game-session-service/src/main/resources/redis/scripts/game-session-original-new-candidate-install.json create mode 100644 services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCandidateRedisOwnerIntegrationTest.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewAuthenticatedSessionTest.java diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index 78cfff2898..25bd8a75d5 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -18,7 +18,7 @@ The manually composed admission acquisition owner reads the retained original Ac Account has an unregistered initial private gameplay LOGIN source slice for request-bound credential digests, signer and JWKS trust, pending and committed registry ownership, authority projection reads, and encrypted response recovery. Before its final Account transaction, the commit source publishes the current issuer and Account projections and requires an exact matching observation; publication or observation failure denies the commit. Caller currentness and response recovery may use an older committed signer generation only while the exact original public-key fingerprint remains in the current trusted JWKS and current owner evidence, including the original issuance JTI, still matches; the applicable authority, API, source, expiry, and compromise fences remain required. The source fixes the explicitly approved `game-session-account-delegation` profile and has no caller-selected profile or property bypass. It adds no endpoint or runtime registration; deployed ACL/TLS, signer-key custody, caller authentication, consumer authorization, gameplay admission, and runtime activation remain unproved. See the [Player Access and Session tracker](../../../project-management/implementation-tracking/player-access-and-session.md#initial-private-gameplay-login-issuance-source-intake) for exact unit and physical fixture proof scope. -Account's unregistered original-ACK storage seam requires PostgreSQL 18 for fresh operations: the original executor performs a writable SERIALIZABLE physical COMMIT on its enlisted connection and returns an opaque acknowledgement only after observing the database clock before unchanged expiry; a separate transaction commits the exact receipt. Receiving V146 changes only the fresh receipt-insert guard, preserving the donor V122 SQL unchanged as receiving V144. Its historical durable reader remains PostgreSQL 16-only, so lost-acknowledgement recovery and retained-receipt retries remain denied on PostgreSQL 18. This storage evidence does not authenticate a caller, establish current Account ownership or admission, authorize gameplay, or register runtime behavior. Migration provenance and pending receiving proof are recorded in the [Player Access and Session tracker](../../../project-management/implementation-tracking/player-access-and-session.md#account-fresh-original-ack-storage-preparation). +Account's unregistered original-ACK owner preserves the original physical COMMIT and its separately committed receipt. Forward V162 extends historical receipt recovery to PostgreSQL 18 while retaining V144/V146 and the original evidence. The private owner captures one fixed snapshot and WAL fence, releases its SQL locks, positively observes coverage of that unchanged fence, and independently compares the exact receipt. Focused PostgreSQL 18 proof covers this recovery boundary. This source remains unregistered and supplies no caller authentication or gameplay admission. Migration provenance, proof and remaining gaps belong to the [Player Access and Session tracker](../../../project-management/implementation-tracking/player-access-and-session.md#account-fresh-original-ack-storage-preparation). Account V40 adds owner-proven sequence-zero source baselines to the inherited V30–V39 authority-storage and retention-safety foundation; V74–V89 preserve that baseline and add source/global-role guards, draft-source writer exclusions and fences, immutable reset/logout/security-operation receipts, creator and tenant-bootstrap provenance, individual Creator Party and hosted-terms/environment-binding persistence, and source-change journals. V90–V97 add persistence relations and guards for source-currentness work across Account, control-UI issuance, selected-publication authorization/settlement, and Game Logic. V98 adds durable hosted-terms disclosure handoff and immutable source-evidence relations with database transition guards. These DDL stages establish persistence and source-writer fence relationships; they do not activate owner writers, legal authority verification, dispatch, or consumers. New repository-created Accounts receive the V40 source baseline; retained pre-V40 rows are neither backfilled nor admitted. Password-reset completion atomically claims and consumes its token, updates the Account, appends the canonical event and receipt, and reads back current source evidence in the owner transaction. If an earlier source intent remains `WAITING`, the request returns retryable `AUTH_UNAVAILABLE`; it does not wait on a thread for settlement, and an exact retry retains the original operation identity. A `WAITING` reset intent retains the Argon2 password verifier needed by that retry; terminal source commit or abort clears the verifier while preserving its digest and immutable source binding and receipt. Finite receipt retention remains unresolved under the owning retention policy; no lifetime is selected here. Logout-all production remains unregistered and unwired. These persistence primitives do not provide public JOIN, target-currentness protection, or runtime activation. Exact physical and local proof limits are recorded in 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. diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 471d770689..f6a465620f 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -453,3 +453,13 @@ Entry format: - Observation: the production migration was present and executed in other schema contexts. A controlled historical SQL seed preserves the old assignment receipt, actor and snapshot without manufacturing a runtime projection or moving the test to the latest frontier. Current-schema assignments retain the production writer. Later shutdown connection noise is separate and its cause remains unproven. - Outcome: full Entity R722 executes 584 methods, with 519 passing, 46 failing on a missing placeholder in the new historical INSERT and 19 failing on separate PostgreSQL connection setup. R723 corrects only that placeholder and passes all 65 affected native cases with no skips; the 454 unit methods and other 65 native cases retain their R722 passing attribution. Enabled affected static analysis and formatting pass. The failed full-check aggregate remains recorded; the focused recovery does not relabel it as green. - Expected pattern: retain the exact pre-upgrade schema, source rows and history in migration proof. Use explicitly historical fixture input when current Java requires a later schema; do not add production compatibility branches or backfill authority merely to seed a test. + +- `2026-10-27`: A running test task can conceal an already recorded failure + - Context: #3315 Game Session job `121874695249` first logged a bootstrap assertion failure at 11:28 NZDT but remained running until 11:53 NZDT; Gradle Checks took about 50 minutes. The shared observer reported the actual terminal failure, but the job conclusion could not expose the earlier assertion. + - Observation: Monitoring completed job conclusions prevents missed failures but does not provide early feedback while a long test task continues after its first failure. This is distinct from the earlier active-job-filter observer bug. + - Expected pattern: Keep scoped local migration and shared-fixture proof ahead of publication. If these delays recur, assess bounded test grouping or failure reporting in the existing CI runner against the loss of full failure diagnostics; do not treat a running job as green or retrigger it merely for a faster status. + +- `2026-10-27`: A global WAL insert fence can outlive quiet-server flush progress + - Context: #2972 R763 passed 23 of 25 native cases; actual bound issuance and a populated historical receipt upgrade refused durability because the captured global insert position remained 56 bytes beyond flush. The exact record type is unknown. + - Observation: PostgreSQL background WAL flushing considers full pages and asynchronous transaction work; an unrelated partial-page tail need not advance during a bounded read. Raising a polling count or lowering the proof fence would not establish the required durability. + - Qualified recovery: retain the SQL-issued snapshot and exact upper fence in a private pending capability, finish its capture transaction, then explicitly observe flush coverage of that same fence outside SQL locks and independently compare the original immutable receipt. No reader COMMIT authenticates the original clock, and no marker, forced flush or replacement timing is introduced. R766 passes all 26 selected PostgreSQL/Redis cases, including quiet-server frozen-fence coverage, unchanged retained migration rows and lost-confirmation recovery; the previous failed aggregates remain recorded. 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 c02da6506b..be878b746b 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -8,7 +8,9 @@ This is a non-normative implementation tracker for player access and session. Ca ### Canonical NEW admission components -The Account gameplay-admission lease and the unregistered Game Session receiver remain separate authority boundaries. The unregistered Account verifier uses the pinned trusted JWKS and fixed gameplay-delegation profile, selects the current `COMMITTED`/`ACTIVE` issuance by verified JTI, and compares the full immutable token identity, hash and authority; it retains no presented JWT and makes no membership, entitlement or lease decision. Focused acquisition proof joins the exact recovered JWT to actual current issuance, physical Coordination Redis and the same-connection Account source graph, preserving the original pending lease on retry. R494 freshly passes 104 Account unit cases and eight selected PostgreSQL/Redis cases, with affected static analysis and formatting. Its manual TLS receiver exercises all four generated RPCs with the exact recovered Account JWT and current issuance/registry and SQL sources, then performs PostgreSQL 18 physical COMMIT and independent durable original-ACK insertion/readback. The original lease attempt and ACK are immutable. The original physical-commit executor retains focused PostgreSQL component proof, and the Game Session lease client has controlled mTLS proof; the retained PostgreSQL 18 receipt-reader denial remains unchanged. The reverse Game Session target/decision response and protected signer/materializer evidence remain controlled. Exact metadata and cleanup-obligation recovery revalidate the current caller/global Account/token under Account-first SQL locks without requiring a superseded tenant admission baseline; new acquisition and first finalization retain full tenant-source checks. These results do not prove genuine Game Session authority, cleanup delivery, final controller admission, production custody or activation. Token-retirement, orphan-cleanup delivery and admitted binding remain open. +The receiving #2972 boundary adds unregistered issuer LIVE/tenant OPEN and Account INITIAL OPEN owners, exact nonadmitting original-NEW candidate installation, and Account-owned generation-1 bound credential/opaque-handle issuance with a strict immediate session consumer. It remains a preparation boundary: the concrete final controller CAS, committed Game Session result reader and whole-flow coordinator are not supplied by this publication. Account final confirmation fails closed without its authenticated final-read dependency. R765 passes all 49 selected receipt/owner unit cases, production and unit static checks, formatting and documentation checks. R766 passes all 26 selected PostgreSQL/Redis cases and integration static/format checks, including genuine original COMMIT and independent receipt recovery, populated V161→V162 retention, same-transaction and stale-snapshot refusal, and actual bound issuance with unchanged replay. Its owned SQL fault occurs after real Redis activation; unavailable or changed controlled Game Session final reads leave SQL unconfirmed, and a fresh exact read confirms the same credential and expiry. The Game Session final-read callback and signer custody remain controlled inputs. Source hashes match the passing native scope and all five observed containers are independently absent. Earlier failed aggregates remain failed. These results do not establish the complete Game Session final-CAS flow, production custody, default registration or activation. + +The Account gameplay-admission lease and the unregistered Game Session receiver remain separate authority boundaries. The unregistered Account verifier uses the pinned trusted JWKS and fixed gameplay-delegation profile, selects the current `COMMITTED`/`ACTIVE` issuance by verified JTI, and compares the full immutable token identity, hash and authority; it retains no presented JWT and makes no membership, entitlement or lease decision. Focused acquisition proof joins the exact recovered JWT to actual current issuance, physical Coordination Redis and the same-connection Account source graph, preserving the original pending lease on retry. R494 freshly passes 104 Account unit cases and eight selected PostgreSQL/Redis cases, with affected static analysis and formatting. Its manual TLS receiver exercises all four generated RPCs with the exact recovered Account JWT and current issuance/registry and SQL sources, then performs PostgreSQL 18 physical COMMIT and independent durable original-ACK insertion/readback. The original lease attempt and ACK are immutable. The original physical-commit executor retains focused PostgreSQL component proof, and the Game Session lease client has controlled mTLS proof; that earlier proof retained the PostgreSQL 18 historical-reader denial. The receiving V162 qualification below extends that owner without changing the original evidence. The reverse Game Session target/decision response and protected signer/materializer evidence remain controlled. Exact metadata and cleanup-obligation recovery revalidate the current caller/global Account/token under Account-first SQL locks without requiring a superseded tenant admission baseline; new acquisition and first finalization retain full tenant-source checks. These results do not prove genuine Game Session authority, cleanup delivery, final controller admission, production custody or activation. Token-retirement, orphan-cleanup delivery and admitted binding remain open. The Game Session canonical inventory now retains Account's exact issuer string through the forward V1024→V1025 conversion. R488 passes 19 selected PostgreSQL cases, including populated-row migration preservation, restart, canonical writes, and refusal by the typed reader to reinterpret retained UUID issuers. This proves storage identity conversion only; issuer ownership and admission remain unqualified. @@ -276,7 +278,7 @@ This preparation is owned by AA-1.3 in [Capability Status](#capability-status), The receiving Account cut imports the preserved original-ACK storage preparation from `codex/gameplay-game-design-publication-storage-foundation-20261009` at `d66d36951d3df780641e0ef04819f15df52ddc39` plus its uncommitted PostgreSQL 18 fresh-path changes. Only the receiving migration filenames are allocated anew: V140 ← source V118 (lease operations), V141 ← V119 (unknown-decision abort), V142 ← V120 (original-finalization stamp and experimental confirmation storage), V143 ← V121 (global pending fences), V144 ← V122 (original-ACK receipt), V145 ← V136 (experimental confirmation write retirement), and V146 ← V139 (PostgreSQL 18 fresh-insert guard). Their SQL bytes, including historical version comments, are preserved. Source V122 retains SHA-256 `c4f66ce16c77514717cbc9d2e0d65bc8c8ee0882239371d8518f587a0ef53490`, matching the historical `2cb445617f584d25c805f5c08e9dde67fff4efc4` migration; no donor renumbering or external migration application is performed. -The unregistered executors and receipt repository preserve the exact original operation, source identity, finalization XID, unchanged expiry and original clock bound. Fresh original and independent receipt COMMITs are explicitly PostgreSQL 18-only; retained COMMITTED retries cannot mint another acknowledgement, and the unchanged historical durable reader still denies PostgreSQL 18 recovery or retained-receipt retries. The `AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest` PostgreSQL prototype contains 18 `@Test` cases and uses the receiving canonical `AccountPostgresIntegrationFixture(true)` without importing another fixture or build dependencies. The copied unit proof sources are separate mocked-JDBC cases. Full-check selected the PostgreSQL cases, but they skipped because local Docker was unavailable; physical PostgreSQL proof remains pending the consolidated gate. No donor or earlier receiving result proves this new intake. Authentication, current ownership/admission, runtime registration, activation and playable capability status remain unchanged. Account-local storage consequences remain in [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#implementation-status). +The unregistered executors and receipt repository preserve the exact original operation, source identity, finalization XID, unchanged expiry and original clock bound. Fresh original and independent receipt COMMITs remain PostgreSQL 18-only. A retained COMMITTED retry cannot mint another original acknowledgement. Forward V162 extends the existing historical reader to PostgreSQL 18 as well as its previously supported PostgreSQL 16, retaining the fixed snapshot, WAL upper fence, independently committed receipt, Account-first row locks and bounded flush-coverage observation. It never writes a marker, forces a flush or restamps timing. R766 freshly passes the 25-case PostgreSQL prototype: the populated V161→V162 case retains pre-upgrade PostgreSQL 18 denial and proves unchanged operation/receipt row images and `xmin`; restarted-owner and lost-receipt-acknowledgement recovery preserve original timing. The private pending capture is not durability proof. The executor positively observes actual flush coverage of its exact frozen fence after the capture transaction releases its locks, then independently compares the entire receipt. R763 exposed the strict in-transaction reader’s quiet-server WAL-tail liveness limit; its two failures remain recorded. Unit coverage includes unavailable flush observations and changed readback, while a deterministic physical WAL-unavailable case remains unqualified. PostgreSQL 16 and other server majors have not been rerun in this receiving scope. This is storage recovery, with no renewal of admission authority or production registration. ### Restricted original-claim evidence continuation preparation diff --git a/protos/account/v1/account_gameplay_admission_lease.proto b/protos/account/v1/account_gameplay_admission_lease.proto index 2063a5022f..227f22e0e0 100644 --- a/protos/account/v1/account_gameplay_admission_lease.proto +++ b/protos/account/v1/account_gameplay_admission_lease.proto @@ -19,6 +19,15 @@ service AccountGameplayAdmissionLeaseService { returns (AccountGameplayAdmissionLeaseResponse); rpc AbortGameplayAdmissionLease(AbortGameplayAdmissionLeaseRequest) returns (AccountGameplayAdmissionLeaseResponse); + // Issues the first purpose-bound credential only after Account's original COMMITTED lease and + // independent original-ACK receipt have been re-read. The returned handle is internal to + // Game Session and is never forwarded to a player client. + rpc IssueOriginalNewGameplayCredential(IssueOriginalNewGameplayCredentialRequest) + returns (AccountGameplayAdmissionLeaseResponse); + // Requests exact recovery of the final Account confirmation. Account performs the protected + // original-final-admission read itself; this request carries no proof or timestamps. + rpc ConfirmOriginalNewGameplayAdmission(ConfirmOriginalNewGameplayAdmissionRequest) + returns (OriginalNewAdmissionConfirmationResponse); } // A new operation selector and expected current values only; Account still resolves and checks @@ -59,6 +68,30 @@ message AbortGameplayAdmissionLeaseRequest { repeated string binding_decision_uuid = 4; } +// Exact recovery or first issuance for one unchanged original NEW lease. The unscoped LOGIN GSA is +// only the authenticated caller; it is not the credential this operation produces. +message IssueOriginalNewGameplayCredentialRequest { + repeated uint32 schema_version = 1; + repeated string presented_initial_gsa_compact_jwt = 2; + repeated bytes original_lease_evidence_utf8 = 3; +} + +message ConfirmOriginalNewGameplayAdmissionRequest { + repeated uint32 schema_version = 1; + repeated string presented_initial_gsa_compact_jwt = 2; + repeated bytes original_lease_evidence_utf8 = 3; +} + +message OriginalNewAdmissionConfirmationResponse { + repeated uint32 schema_version = 1; + repeated string lineage_uuid = 2; + repeated string original_lease_uuid = 3; + repeated string original_lease_fence = 4; + repeated string admission_at_ms = 5; + repeated string continuity_expires_at_ms = 6; + repeated string confirmation_readback_sha256 = 7; +} + enum AccountGameplayAdmissionLeaseState { ACCOUNT_GAMEPLAY_ADMISSION_LEASE_STATE_UNSPECIFIED = 0; ACCOUNT_GAMEPLAY_ADMISSION_LEASE_STATE_PENDING = 1; @@ -66,7 +99,7 @@ enum AccountGameplayAdmissionLeaseState { ACCOUNT_GAMEPLAY_ADMISSION_LEASE_STATE_ABORTED = 3; } -// All four methods return the same closed original-operation readback. Repeated fields preserve +// Lease operations return the same closed original-operation readback. Repeated fields preserve // absence and duplicates for receiver validation. The lease bytes remain unchanged and complete. message AccountGameplayAdmissionLeaseResponse { repeated uint32 schema_version = 1; @@ -76,6 +109,25 @@ message AccountGameplayAdmissionLeaseResponse { // ABORTED-only pending cleanup obligation; this never reports cleanup completion. repeated string orphan_cleanup_uuid = 5; repeated AccountGameplayAdmissionOriginalAckReceiptEvidence original_ack_receipt = 6; + // Present only on IssueOriginalNewGameplayCredential. Kept separate so closed original lease + // evidence and its committed receipt remain byte-for-byte unchanged. + repeated OriginalNewGameplayCredentialResult original_new_credential = 7; +} + +// Protected Account result transported only to the authenticated Game Session service. The +// codec and recipient keep diagnostics redacted; the opaque handle is never client-visible. +message OriginalNewGameplayCredentialResult { + repeated uint32 schema_version = 1; + repeated string signed_bound_gsa_compact_jwt = 2; + repeated bytes opaque_rebind_handle = 3; + repeated string lineage_uuid = 4; + repeated string token_jti_uuid = 5; + repeated string token_sha256 = 6; + repeated string issuance_fence = 7; + repeated string original_lease_uuid = 8; + repeated string original_lease_fence = 9; + repeated string original_ack_receipt_xid = 10; + repeated string checkpoints_sha256 = 11; } // Complete durable AccountGameplayAdmissionOriginalAckReceipt shape. The operation identity and diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/AccountOriginalNewFinalAdmissionReadClient.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/AccountOriginalNewFinalAdmissionReadClient.java new file mode 100644 index 0000000000..e7ce40ef76 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/AccountOriginalNewFinalAdmissionReadClient.java @@ -0,0 +1,154 @@ +package net.firedevops.firemud.accountservice.client; + +import java.util.Objects; +import java.util.UUID; + +/** + * Protected Account-to-Game-Session boundary for the actual ORIGINAL final-admission readback. + * + *

Account calls this source after its original credential has been issued. Implementations must + * perform the authenticated same-namespace Game Session final-result read themselves; no RPC + * caller-provided timestamp, boolean, candidate, or receipt can construct this result for Account. + * Until the canonical authenticated final-result reader is wired, no implementation is supplied and + * Account fails closed. + */ +@FunctionalInterface +public interface AccountOriginalNewFinalAdmissionReadClient { + AuthenticatedFinalAdmissionReadback readActualOriginalFinalAdmission( + ExpectedOriginalAdmission expected); + + /** Complete immutable Account anchors supplied to the protected Game Session read. */ + record ExpectedOriginalAdmission( + UUID requestId, + UUID accountId, + UUID tenantId, + UUID sessionId, + UUID bindingDecisionId, + UUID originalLeaseId, + long originalLeaseFence, + String originalLeaseEvidenceSha256, + UUID lineageId, + UUID tokenJti, + String tokenSha256, + long tokenGeneration, + long issuanceFence, + String bindingScopeSha256, + String membershipBaselineSha256, + String checkpointsSha256, + String rebindHandleSha256) { + public ExpectedOriginalAdmission { + requireUuid(requestId); + requireUuid(accountId); + requireUuid(tenantId); + requireUuid(sessionId); + requireUuid(bindingDecisionId); + requireUuid(originalLeaseId); + requireUuid(lineageId); + requireUuid(tokenJti); + requireSha256(originalLeaseEvidenceSha256); + requireSha256(tokenSha256); + requireSha256(bindingScopeSha256); + requireSha256(membershipBaselineSha256); + requireSha256(checkpointsSha256); + requireSha256(rebindHandleSha256); + if (originalLeaseFence <= 0L + || tokenGeneration != 1L + || issuanceFence <= 0L + || lineageId.equals(tokenJti)) throw invalid(); + } + + @Override + public String toString() { + return "ExpectedOriginalAdmission[redacted]"; + } + } + + /** + * Typed response only constructible by the protected reader implementation. Account exact- + * compares every anchor and checks the canonical continuity deadline before persisting it. + */ + final class AuthenticatedFinalAdmissionReadback { + private final int sessionSchemaVersion; + private final String admissionState; + private final ExpectedOriginalAdmission anchors; + private final long admissionAtMillis; + private final long continuityExpiresAtMillis; + private final long canonicalSessionDurationMillis; + private final String canonicalReadbackSha256; + + AuthenticatedFinalAdmissionReadback( + int sessionSchemaVersion, + String admissionState, + ExpectedOriginalAdmission anchors, + long admissionAtMillis, + long continuityExpiresAtMillis, + long canonicalSessionDurationMillis, + String canonicalReadbackSha256) { + this.sessionSchemaVersion = sessionSchemaVersion; + this.admissionState = Objects.requireNonNull(admissionState); + this.anchors = Objects.requireNonNull(anchors); + this.admissionAtMillis = admissionAtMillis; + this.continuityExpiresAtMillis = continuityExpiresAtMillis; + this.canonicalSessionDurationMillis = canonicalSessionDurationMillis; + this.canonicalReadbackSha256 = canonicalReadbackSha256; + requireSha256(canonicalReadbackSha256); + long expectedExpiry; + try { + expectedExpiry = Math.addExact(admissionAtMillis, canonicalSessionDurationMillis); + } catch (ArithmeticException malformed) { + throw invalid(); + } + if (sessionSchemaVersion != 2 + || !"COMPLETE".equals(admissionState) + || admissionAtMillis <= 0L + || canonicalSessionDurationMillis <= 0L + || continuityExpiresAtMillis != expectedExpiry) throw invalid(); + } + + public int sessionSchemaVersion() { + return sessionSchemaVersion; + } + + public String admissionState() { + return admissionState; + } + + public ExpectedOriginalAdmission anchors() { + return anchors; + } + + public long admissionAtMillis() { + return admissionAtMillis; + } + + public long continuityExpiresAtMillis() { + return continuityExpiresAtMillis; + } + + public long canonicalSessionDurationMillis() { + return canonicalSessionDurationMillis; + } + + public String canonicalReadbackSha256() { + return canonicalReadbackSha256; + } + + @Override + public String toString() { + return "AuthenticatedFinalAdmissionReadback[redacted]"; + } + } + + private static void requireUuid(UUID value) { + Objects.requireNonNull(value); + if (value.version() != 4 || value.variant() != 2) throw invalid(); + } + + private static void requireSha256(String value) { + if (value == null || !value.matches("[0-9a-f]{64}")) throw invalid(); + } + + private static IllegalArgumentException invalid() { + return new IllegalArgumentException("Protected original final-admission readback is malformed"); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountGameplayTokenIdentityFence.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountGameplayTokenIdentityFence.java index 4f228b4732..98809bde8e 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountGameplayTokenIdentityFence.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountGameplayTokenIdentityFence.java @@ -43,13 +43,36 @@ public record TokenIdentity( UUID tokenJti, long notBeforeEpochSecond, long tokenGeneration, - long issuanceFence) { + long issuanceFence, + SourceKind sourceKind) { + public TokenIdentity( + UUID accountId, + UUID operationId, + UUID issuanceRequestId, + String tokenSha256, + UUID tokenJti, + long notBeforeEpochSecond, + long tokenGeneration, + long issuanceFence) { + this( + accountId, + operationId, + issuanceRequestId, + tokenSha256, + tokenJti, + notBeforeEpochSecond, + tokenGeneration, + issuanceFence, + SourceKind.LOGIN); + } + public TokenIdentity { requireUuid(accountId); requireUuid(operationId); requireUuid(issuanceRequestId); requireUuid(tokenJti); requireDigest(tokenSha256); + Objects.requireNonNull(sourceKind); if (notBeforeEpochSecond <= 0L || tokenGeneration <= 0L || issuanceFence <= 0L) { throw new IllegalArgumentException("Positive exact token identity metadata required"); } @@ -61,6 +84,12 @@ public String toString() { } } + /** Distinguishes original unscoped LOGIN rows from fresh tenant-bound ORIGINAL-NEW lineages. */ + public enum SourceKind { + LOGIN, + ORIGINAL_NEW + } + private static void requireUuid(UUID value) { if (value == null || value.version() != 4 || value.variant() != 2) { throw new IllegalArgumentException("Canonical UUIDv4 required"); diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptCommitExecutor.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptCommitExecutor.java index a3c6e2569a..12f1484898 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptCommitExecutor.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptCommitExecutor.java @@ -1,6 +1,7 @@ package net.firedevops.firemud.accountservice.repository; import java.sql.Connection; +import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; @@ -50,13 +51,12 @@ AccountGameplayAdmissionOriginalAckReceipt confirm( // row. rejectAmbient(); var read = - execute( - new ReceiptTransactionManager(dataSource), - repository -> - creation.inserted() - ? repository.readExact(acknowledgement.evidence(), acknowledgement.decisionId()) - : repository.readDurably( - acknowledgement.evidence(), acknowledgement.decisionId())); + creation.inserted() + ? execute( + new ReceiptTransactionManager(dataSource), + repository -> + repository.readExact(acknowledgement.evidence(), acknowledgement.decisionId())) + : read(acknowledgement.evidence(), acknowledgement.decisionId()); validate(read, acknowledgement.evidence(), acknowledgement.decisionId()); if (!created.equals(read)) throw denied(); return read; @@ -67,14 +67,67 @@ AccountGameplayAdmissionOriginalAckReceipt read( Objects.requireNonNull(evidence); Objects.requireNonNull(decisionId); rejectAmbient(); + var pending = + execute( + new ReceiptTransactionManager(dataSource), + repository -> repository.captureHistorical(evidence, decisionId)); + validate(pending.receipt(), evidence, decisionId); + // Capture completion is not proof of original timing or durability. Observe actual durable + // coverage of the exact SQL-issued upper fence, after releasing the capture's row locks. + awaitFrozenFenceCoverage(pending); + rejectAmbient(); var receipt = execute( new ReceiptTransactionManager(dataSource), - repository -> repository.readDurably(evidence, decisionId)); + repository -> repository.readExact(evidence, decisionId)); validate(receipt, evidence, decisionId); + if (!pending.receipt().equals(receipt)) throw denied(); return receipt; } + private void awaitFrozenFenceCoverage( + AccountGameplayAdmissionOriginalAckReceiptRepository.PendingHistoricalReceipt pending) { + rejectAmbient(); + try (Connection connection = dataSource.getConnection()) { + if (!connection.getAutoCommit() + || !"PostgreSQL".equals(connection.getMetaData().getDatabaseProductName())) + throw denied(); + try (PreparedStatement statement = + connection.prepareStatement( + "SELECT current_setting('server_version_num')::integer, pg_is_in_recovery(), " + + "current_setting('fsync'), pg_current_wal_flush_lsn() >= ?::pg_lsn")) { + statement.setQueryTimeout(1); + statement.setString(1, pending.walUpperFence()); + for (int observation = 0; observation < 50; observation++) { + boolean covered; + try (ResultSet result = statement.executeQuery()) { + if (!result.next()) throw denied(); + int version = result.getInt(1); + if (version < 180000 + || version >= 190000 + || result.getBoolean(2) + || !"on".equals(result.getString(3))) throw denied(); + covered = result.getBoolean(4); + if (result.wasNull() || result.next()) throw denied(); + } + if (covered) return; + if (observation < 49) { + try { + Thread.sleep(10L); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw denied(); + } + } + } + } + } catch (SQLException failure) { + throw new TransactionSystemException("Account receipt WAL coverage unavailable", failure); + } + throw new IllegalStateException( + "Original Account acknowledgement receipt WAL coverage unavailable"); + } + private static void validate( AccountGameplayAdmissionOriginalAckReceipt receipt, AccountGameplayAdmissionLeaseEvidence evidence, diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptRepository.java index ea0df8aeb8..b79d4f2ecc 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptRepository.java @@ -72,7 +72,9 @@ Creation create(OriginalCommitAcknowledgement acknowledgement) { return new Creation(receipt, wasInserted); } - /** Exact storage-only read for the sibling owner after it observed successful receipt COMMIT. */ + /** + * Exact storage-only read after the sibling owner proved receipt COMMIT or frozen WAL coverage. + */ AccountGameplayAdmissionOriginalAckReceipt readExact( AccountGameplayAdmissionLeaseEvidence evidence, UUID decisionId) { requireWritableSerializableTransaction(); @@ -82,6 +84,24 @@ AccountGameplayAdmissionOriginalAckReceipt readExact( return decode(row, exactCommitted(evidence, decisionId)); } + /** Captures exact pending evidence; this method alone proves no WAL durability. */ + PendingHistoricalReceipt captureHistorical( + AccountGameplayAdmissionLeaseEvidence evidence, UUID decisionId) { + requireWritableSerializableTransaction(); + UUID requestId = validateRequest(evidence, decisionId); + Record row = + dsl.fetchOne( + "SELECT (capture.captured_receipt).*, capture.wal_upper_fence::text AS wal_upper_fence " + + "FROM account_gameplay_admission_capture_original_ack_receipt(?, ?, ?) capture", + requestId, + evidence.sha256(), + decisionId); + if (row == null) throw unavailable(); + return new PendingHistoricalReceipt( + decode(row, exactCommitted(evidence, decisionId)), + required(row, "wal_upper_fence", String.class)); + } + /** Proves historical independent receipt durability without changing its original evidence. */ AccountGameplayAdmissionOriginalAckReceipt readDurably( AccountGameplayAdmissionLeaseEvidence evidence, UUID decisionId) { @@ -164,6 +184,28 @@ private static IllegalStateException unavailable() { "Original Account admission acknowledgement receipt unavailable"); } + /** Non-wire SQL-issued pending capability. Only captureHistorical can stamp its frozen fence. */ + static final class PendingHistoricalReceipt { + private final AccountGameplayAdmissionOriginalAckReceipt receipt; + private final String walUpperFence; + + private PendingHistoricalReceipt( + AccountGameplayAdmissionOriginalAckReceipt receipt, String walUpperFence) { + this.receipt = Objects.requireNonNull(receipt); + this.walUpperFence = Objects.requireNonNull(walUpperFence); + if (!walUpperFence.matches("(0|[1-9A-F][0-9A-F]{0,7})/(0|[1-9A-F][0-9A-F]{0,7})") + || "0/0".equals(walUpperFence)) throw unavailable(); + } + + AccountGameplayAdmissionOriginalAckReceipt receipt() { + return receipt; + } + + String walUpperFence() { + return walUpperFence; + } + } + record Creation(AccountGameplayAdmissionOriginalAckReceipt receipt, boolean inserted) { Creation { Objects.requireNonNull(receipt); diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayTokenIdentityFenceRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayTokenIdentityFenceRepository.java index 9f85b30fa6..538a94f2d0 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayTokenIdentityFenceRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayTokenIdentityFenceRepository.java @@ -8,6 +8,7 @@ import java.util.Objects; import java.util.UUID; import net.firedevops.firemud.accountservice.dto.AccountGameplayTokenIdentityFence; +import net.firedevops.firemud.accountservice.dto.AccountGameplayTokenIdentityFence.SourceKind; import net.firedevops.firemud.accountservice.dto.AccountGameplayTokenIdentityFence.State; import net.firedevops.firemud.accountservice.dto.AccountGameplayTokenIdentityFence.TokenIdentity; import org.jooq.DSLContext; @@ -28,7 +29,7 @@ public class AccountGameplayTokenIdentityFenceRepository { private static final String TABLE = "account_gameplay_token_identity_fences"; private static final String COLUMNS = "account_uuid, operation_id, issuance_request_id, token_hash, token_jti, " - + "not_before_epoch_second, token_generation, issuance_fence, token_identity_fence, " + + "not_before_epoch_second, token_generation, issuance_fence, source_kind, token_identity_fence, " + "state, revocation_request_id, revocation_digest"; private final DSLContext dsl; @@ -65,13 +66,14 @@ public AccountGameplayTokenIdentityFence requireActiveForUpdate(TokenIdentity id AccountGameplayTokenIdentityFence registerCommittedIssuance(TokenIdentity identity) { requireTransaction(); lockAccountForUpdate(identity.accountId()); + if (identity.sourceKind() != SourceKind.LOGIN) throw new TokenFenceUnavailableException(); dsl.execute( "INSERT INTO " + TABLE + " (account_uuid, operation_id, issuance_request_id, token_hash, " - + "token_jti, not_before_epoch_second, token_generation, issuance_fence) " + + "token_jti, not_before_epoch_second, token_generation, issuance_fence, source_kind) " + "SELECT account_uuid, operation_id, request_id, token_hash, token_jti, " - + "not_before_epoch_second, token_generation, issuance_fence " + + "not_before_epoch_second, token_generation, issuance_fence, 'LOGIN' " + "FROM account_gameplay_delegation_issuance_operations " + "WHERE operation_id = ? AND request_id = ? AND account_uuid = ? " + "AND token_hash = ? AND token_jti = ? AND not_before_epoch_second = ? " @@ -88,6 +90,35 @@ AccountGameplayTokenIdentityFence registerCommittedIssuance(TokenIdentity identi return requireActiveForUpdate(identity); } + /** Registers a committed ORIGINAL-NEW lineage in the same Account token-identity fence owner. */ + AccountGameplayTokenIdentityFence registerCommittedOriginalNewIssuance(TokenIdentity identity) { + requireTransaction(); + if (identity.sourceKind() != SourceKind.ORIGINAL_NEW) + throw new TokenFenceUnavailableException(); + lockAccountForUpdate(identity.accountId()); + dsl.execute( + "INSERT INTO " + + TABLE + + " (account_uuid, operation_id, issuance_request_id, token_hash, token_jti, " + + "not_before_epoch_second, token_generation, issuance_fence, source_kind) " + + "SELECT account_uuid, operation_id, request_id, token_hash, token_jti, " + + "not_before_epoch_second, token_generation, issuance_fence, 'ORIGINAL_NEW' " + + "FROM account_original_new_bound_gameplay_issuances " + + "WHERE operation_id = ? AND request_id = ? AND account_uuid = ? " + + "AND token_hash = ? AND token_jti = ? AND not_before_epoch_second = ? " + + "AND token_generation = ? AND issuance_fence = ? AND status = 'COMMITTED' " + + "ON CONFLICT (operation_id) DO NOTHING", + identity.operationId(), + identity.issuanceRequestId(), + identity.accountId(), + identity.tokenSha256(), + identity.tokenJti(), + identity.notBeforeEpochSecond(), + identity.tokenGeneration(), + identity.issuanceFence()); + return requireActiveForUpdate(identity); + } + /** Independent metadata readback, including the source COMMITTED identity, never registration. */ AccountGameplayTokenIdentityFence requireActiveReadback(TokenIdentity identity) { AccountGameplayTokenIdentityFence fence = requireExact(identity, false); @@ -144,7 +175,10 @@ public static String revocationDigest(TokenIdentity identity, UUID requestId) { } // All fields have fixed/canonical syntax, so the domain-separated framing is unambiguous. String input = - "account-gameplay-token-revocation-intent/v1\n" + (identity.sourceKind() == SourceKind.LOGIN + ? "account-gameplay-token-revocation-intent/v1" + : "account-original-new-bound-gameplay-token-revocation-intent/v1") + + "\n" + requestId + "\n" + identity.accountId() @@ -174,10 +208,11 @@ public static String revocationDigest(TokenIdentity identity, UUID requestId) { } private AccountGameplayTokenIdentityFence requireExact(TokenIdentity identity, boolean lock) { - if (dsl.fetchOne( - "SELECT request_id FROM account_initial_gameplay_login_disposals WHERE request_id = ?", - identity.issuanceRequestId()) - != null) throw new TokenRevokedException(); + if (identity.sourceKind() == SourceKind.LOGIN + && dsl.fetchOne( + "SELECT request_id FROM account_initial_gameplay_login_disposals WHERE request_id = ?", + identity.issuanceRequestId()) + != null) throw new TokenRevokedException(); return requireExactStoredIdentity(identity, lock); } @@ -196,10 +231,15 @@ private AccountGameplayTokenIdentityFence requireExactStoredIdentity( if (row == null) throw new TokenFenceUnavailableException(); AccountGameplayTokenIdentityFence fence = decode(row); if (!identity.equals(fence.identity())) throw new TokenFenceUnavailableException(); + String sourceTable = + identity.sourceKind() == SourceKind.LOGIN + ? "account_gameplay_delegation_issuance_operations" + : "account_original_new_bound_gameplay_issuances"; Record source = dsl.fetchOne( - "SELECT operation_id FROM account_gameplay_delegation_issuance_operations " - + "WHERE operation_id = ? AND request_id = ? AND account_uuid = ? AND token_hash = ? " + "SELECT operation_id FROM " + + sourceTable + + " WHERE operation_id = ? AND request_id = ? AND account_uuid = ? AND token_hash = ? " + "AND token_jti = ? AND not_before_epoch_second = ? AND token_generation = ? " + "AND issuance_fence = ? AND status = 'COMMITTED'", identity.operationId(), @@ -218,10 +258,15 @@ private static AccountGameplayTokenIdentityFence decode(Record row) { try { return new AccountGameplayTokenIdentityFence( new TokenIdentity( - row.get("account_uuid", UUID.class), row.get("operation_id", UUID.class), - row.get("issuance_request_id", UUID.class), row.get("token_hash", String.class), - row.get("token_jti", UUID.class), row.get("not_before_epoch_second", Long.class), - row.get("token_generation", Long.class), row.get("issuance_fence", Long.class)), + row.get("account_uuid", UUID.class), + row.get("operation_id", UUID.class), + row.get("issuance_request_id", UUID.class), + row.get("token_hash", String.class), + row.get("token_jti", UUID.class), + row.get("not_before_epoch_second", Long.class), + row.get("token_generation", Long.class), + row.get("issuance_fence", Long.class), + SourceKind.valueOf(row.get("source_kind", String.class))), row.get("token_identity_fence", Long.class), State.valueOf(row.get("state", String.class)), row.get("revocation_request_id", UUID.class), diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountOriginalNewBoundGameplayCredentialOwner.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountOriginalNewBoundGameplayCredentialOwner.java new file mode 100644 index 0000000000..651e671521 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountOriginalNewBoundGameplayCredentialOwner.java @@ -0,0 +1,1198 @@ +package net.firedevops.firemud.accountservice.repository; + +import io.grpc.Status; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; +import java.time.Clock; +import java.time.Instant; +import java.util.Arrays; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import javax.sql.DataSource; +import net.firedevops.firemud.accountservice.client.AccountOriginalNewFinalAdmissionReadClient; +import net.firedevops.firemud.accountservice.client.AccountOriginalNewFinalAdmissionReadClient.AuthenticatedFinalAdmissionReadback; +import net.firedevops.firemud.accountservice.client.AccountOriginalNewFinalAdmissionReadClient.ExpectedOriginalAdmission; +import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionLeaseOperation; +import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionLeaseOperation.State; +import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionOriginalAckReceipt; +import net.firedevops.firemud.accountservice.dto.AccountGameplayTokenIdentityFence.SourceKind; +import net.firedevops.firemud.accountservice.dto.AccountGameplayTokenIdentityFence.TokenIdentity; +import net.firedevops.firemud.accountservice.repository.AccountOriginalNewBoundGameplayIssuanceRepository.Genesis; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayAdmissionCallerVerifier; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayAdmissionCallerVerifier.VerifiedCaller; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationRedisClient; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationRedisClient.PendingRegistrationReceipt; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationSigner; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationSigner.OriginalNewBoundSignedCandidate; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationTokenRegistry; +import net.firedevops.firemud.accountservice.service.session.AccountResponseEnvelopeCryptography; +import net.firedevops.firemud.accountservice.service.session.AccountResponseEnvelopeCryptography.Binding; +import net.firedevops.firemud.accountservice.service.session.AccountResponseEnvelopeCryptography.EncryptedResponseEnvelope; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseGrpcCodec; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseGrpcCodec.OriginalNewCredential; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationRegistryRecord; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationRegistryRecord.AccountAuthoritySnapshot; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationRegistryRecord.EvidenceBundleReference; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationRegistryRecord.IssuanceBinding; +import net.firedevops.firemud.common.security.SessionContext; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.springframework.jdbc.datasource.ConnectionHolder; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; +import tools.jackson.databind.json.JsonMapper; + +/** + * Manually composed Account owner for the first bound ORIGINAL-NEW gameplay credential. + * + *

The caller's LOGIN token is only authentication for this operation. The new token and its + * opaque handle are anchored to one immutable original NEW lease plus its separately durable ACK. + * This owner does not install a Game Session admission, activate a session, or implement REBIND. + */ +public final class AccountOriginalNewBoundGameplayCredentialOwner { + private static final String GAME_SESSION_SERVICE = "game-session-service"; + private static final String ENVELOPE_OPERATION = "original-new-bound-gameplay-credential"; + private static final JsonMapper JSON = JsonMapper.builder().build(); + + private final DataSource dataSource; + private final String workloadNamespace; + private final AccountGameplayAdmissionCallerVerifier callerVerifier; + private final AccountGameplayAdmissionOriginalAckReceiptCommitExecutor receiptExecutor; + private final AccountGameplayDelegationSigner signer; + private final AccountGameplayDelegationTokenRegistry tokenRegistry; + private final AccountResponseEnvelopeCryptography responseCryptography; + private final AccountOriginalNewFinalAdmissionReadClient finalAdmissionReadClient; + private final Clock clock; + private final SecureRandom secureRandom; + + public AccountOriginalNewBoundGameplayCredentialOwner( + DataSource dataSource, + String workloadNamespace, + AccountGameplayAdmissionCallerVerifier callerVerifier, + AccountGameplayDelegationSigner signer, + AccountGameplayDelegationTokenRegistry tokenRegistry, + AccountResponseEnvelopeCryptography responseCryptography, + Clock clock) { + this( + dataSource, + workloadNamespace, + callerVerifier, + signer, + tokenRegistry, + responseCryptography, + clock, + null, + new SecureRandom()); + } + + /** Explicitly protected final-admission reader; absent reader leaves confirmation fail-closed. */ + public AccountOriginalNewBoundGameplayCredentialOwner( + DataSource dataSource, + String workloadNamespace, + AccountGameplayAdmissionCallerVerifier callerVerifier, + AccountGameplayDelegationSigner signer, + AccountGameplayDelegationTokenRegistry tokenRegistry, + AccountResponseEnvelopeCryptography responseCryptography, + Clock clock, + AccountOriginalNewFinalAdmissionReadClient finalAdmissionReadClient) { + this( + dataSource, + workloadNamespace, + callerVerifier, + signer, + tokenRegistry, + responseCryptography, + clock, + Objects.requireNonNull(finalAdmissionReadClient), + new SecureRandom()); + } + + AccountOriginalNewBoundGameplayCredentialOwner( + DataSource dataSource, + String workloadNamespace, + AccountGameplayAdmissionCallerVerifier callerVerifier, + AccountGameplayDelegationSigner signer, + AccountGameplayDelegationTokenRegistry tokenRegistry, + AccountResponseEnvelopeCryptography responseCryptography, + Clock clock, + SecureRandom secureRandom) { + this( + dataSource, + workloadNamespace, + callerVerifier, + signer, + tokenRegistry, + responseCryptography, + clock, + null, + secureRandom); + } + + private AccountOriginalNewBoundGameplayCredentialOwner( + DataSource dataSource, + String workloadNamespace, + AccountGameplayAdmissionCallerVerifier callerVerifier, + AccountGameplayDelegationSigner signer, + AccountGameplayDelegationTokenRegistry tokenRegistry, + AccountResponseEnvelopeCryptography responseCryptography, + Clock clock, + AccountOriginalNewFinalAdmissionReadClient finalAdmissionReadClient, + SecureRandom secureRandom) { + this.dataSource = Objects.requireNonNull(dataSource, "Account DataSource is required"); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Canonical Account workload namespace required"); + } + this.workloadNamespace = workloadNamespace; + this.callerVerifier = Objects.requireNonNull(callerVerifier); + this.receiptExecutor = new AccountGameplayAdmissionOriginalAckReceiptCommitExecutor(dataSource); + this.signer = Objects.requireNonNull(signer); + this.tokenRegistry = Objects.requireNonNull(tokenRegistry); + this.responseCryptography = Objects.requireNonNull(responseCryptography); + this.finalAdmissionReadClient = finalAdmissionReadClient; + this.clock = Objects.requireNonNull(clock); + this.secureRandom = Objects.requireNonNull(secureRandom); + } + + /** Issues once after the durable original COMMITTED lease and ACK are independently read back. */ + public OriginalNewCredential issue( + String presentedInitialGsACompactJwt, AccountGameplayAdmissionLeaseEvidence requestedLease) { + GrpcPeerIdentity peer = requireGameSessionCaller(); + requireNoAmbientSql(); + Objects.requireNonNull(requestedLease, "Original NEW lease is required"); + VerifiedCaller caller = verifyCaller(presentedInitialGsACompactJwt, peer); + requireCallerMatchesLease(caller, peer, requestedLease); + + SourceRead initial = readCurrentOriginalSource(caller, requestedLease); + if (initial.operation().state() != State.COMMITTED + || initial.operation().bindingDecisionId() == null) throw unavailable(); + AccountGameplayAdmissionOriginalAckReceipt receipt = + receiptExecutor.read(requestedLease, initial.operation().bindingDecisionId()); + requireExactReceipt(receipt, initial.operation(), requestedLease); + + long nowSeconds = clock.instant().getEpochSecond(); + if (nowSeconds <= 0L) throw unavailable(); + UUID newLineageId = UUID.randomUUID(); + UUID newTokenJti = UUID.randomUUID(); + while (newTokenJti.equals(newLineageId) || newTokenJti.equals(caller.identity().tokenJti())) { + newTokenJti = UUID.randomUUID(); + } + UUID frozenNewTokenJti = newTokenJti; + long expirySeconds; + try { + expirySeconds = + Math.addExact(nowSeconds, GameSessionAccountDelegationProfile.MAX_TOKEN_LIFETIME_SECONDS); + } catch (ArithmeticException malformed) { + throw unavailable(); + } + + Genesis genesis = + inWritableSerializableTransaction( + dsl -> + new AccountOriginalNewBoundGameplayIssuanceRepository(dsl) + .beginGenesis( + requestedLease, + receipt, + newLineageId, + frozenNewTokenJti, + nowSeconds, + nowSeconds, + expirySeconds)); + + if (genesis.tokenHash() == null) { + genesis = signAndPersistCandidate(caller, requestedLease, receipt, genesis); + } + if (genesis.tokenHash() == null || genesis.encryptedResultEnvelopeBytes() == null) { + throw unavailable(); + } + + final String receiptDigest; + if (genesis.status() == AccountOriginalNewBoundGameplayIssuanceRepository.Status.COMMITTED) { + receiptDigest = genesis.committedRegistryReceiptSha256(); + if (receiptDigest == null) throw unavailable(); + if (genesis.confirmedAdmissionAtMillis() != null) { + tokenRegistry.requireExactOriginalNewActiveRecord(genesis); + } else { + // Reasserts the same immutable PENDING bytes and deadline. The original SQL receipt digest + // remains frozen; this retry does not replace it with a later WAITAOF observation. + tokenRegistry.registerOriginalNewPending(genesis); + } + } else { + PendingRegistrationReceipt redisReceipt = tokenRegistry.registerOriginalNewPending(genesis); + receiptDigest = pendingRegistryReceiptDigest(redisReceipt); + } + + // Network registration has completed with no SQL lock held. Re-authenticate the original + // caller, then atomically commit this exact issuance and create its independent token fence. + VerifiedCaller currentCaller = verifyCaller(presentedInitialGsACompactJwt, peer); + if (!AccountGameplayDelegationIssuanceRepository.CommittedCandidateVerificationData + .hasSameOwnerEvidence(caller.currentCandidate(), currentCaller.currentCandidate())) { + throw unavailable(); + } + final Genesis exactGenesisForCommit = genesis; + Genesis committed = + inWritableSerializableTransaction( + dsl -> { + SourceRead current = readCurrentOriginalSource(dsl, currentCaller, requestedLease); + requireSameOriginalOperation(initial.operation(), current.operation()); + AccountOriginalNewBoundGameplayIssuanceRepository issuance = + new AccountOriginalNewBoundGameplayIssuanceRepository(dsl); + Genesis stored = issuance.readByLease(leaseId(requestedLease)); + requireSameGenesisIdentity(exactGenesisForCommit, stored); + Genesis committedResult = issuance.commit(stored, receiptDigest); + var fenceRepository = new AccountGameplayTokenIdentityFenceRepository(dsl); + var tokenIdentity = + new TokenIdentity( + committedResult.accountId(), + committedResult.lineageId(), + committedResult.requestId(), + committedResult.tokenHash(), + committedResult.tokenJti(), + committedResult.notBeforeEpochSecond(), + committedResult.tokenGeneration(), + committedResult.issuanceFence(), + SourceKind.ORIGINAL_NEW); + fenceRepository.registerCommittedOriginalNewIssuance(tokenIdentity); + return committedResult; + }); + + // The caller receives the result only after Account's issuance row and active identity fence + // committed together. Opening requires a fresh source and exact active-fence readback. + return openCommittedResult(currentCaller, requestedLease, receipt, committed); + } + + /** Full protected RPC result, with the original lease and ACK carrier left unchanged. */ + public net.firedevops.firemud.account.v1.AccountGameplayAdmissionLeaseResponse issue( + AccountGameplayAdmissionLeaseGrpcCodec.OriginalNewCredentialRequest request) { + Objects.requireNonNull(request, "Parsed ORIGINAL-NEW credential request is required"); + AccountGameplayAdmissionLeaseEvidence lease = request.originalLeaseEvidence(); + SourceRead source = readCurrentOriginalSourceAfterAuthentication(request, lease); + if (source.operation().state() != State.COMMITTED + || source.operation().bindingDecisionId() == null) throw unavailable(); + AccountGameplayAdmissionOriginalAckReceipt receipt = + receiptExecutor.read(lease, source.operation().bindingDecisionId()); + requireExactReceipt(receipt, source.operation(), lease); + OriginalNewCredential credential = issue(request.presentedInitialGsACompactJwt(), lease); + try { + var ack = + AccountGameplayAdmissionLeaseGrpcCodec.OriginalAckReceiptEvidence.fromFields( + receipt.schemaVersion(), + receipt.requestId(), + receipt.accountId(), + receipt.leaseId(), + receipt.leaseFence(), + receipt.evidenceSha256(), + receipt.bindingDecisionId(), + receipt.expiresAtMs(), + receipt.finalizationXid(), + receipt.committedBeforeMs(), + receipt.receiptXid()); + return AccountGameplayAdmissionLeaseGrpcCodec.toIssueOriginalNewCredentialResponse( + request, + lease, + AccountGameplayAdmissionLeaseGrpcCodec.State.COMMITTED, + source.operation().bindingDecisionId(), + ack, + credential); + } finally { + credential.close(); + } + } + + private SourceRead readCurrentOriginalSourceAfterAuthentication( + AccountGameplayAdmissionLeaseGrpcCodec.OriginalNewCredentialRequest request, + AccountGameplayAdmissionLeaseEvidence lease) { + GrpcPeerIdentity peer = requireGameSessionCaller(); + VerifiedCaller caller = verifyCaller(request.presentedInitialGsACompactJwt(), peer); + requireCallerMatchesLease(caller, peer, lease); + return readCurrentOriginalSource(caller, lease); + } + + /** + * Confirms only an actual Game Session final-admission readback fetched by Account's protected + * client. The caller supplies neither timestamps nor a proof object. No credential is reminted. + */ + public OriginalAdmissionConfirmation confirmOriginalFinalAdmission( + String presentedInitialGsACompactJwt, AccountGameplayAdmissionLeaseEvidence requestedLease) { + if (finalAdmissionReadClient == null) throw unavailable(); + GrpcPeerIdentity peer = requireGameSessionCaller(); + requireNoAmbientSql(); + VerifiedCaller caller = verifyCaller(presentedInitialGsACompactJwt, peer); + requireCallerMatchesLease(caller, peer, requestedLease); + SourceRead beforeRead = readCurrentOriginalSource(caller, requestedLease); + if (beforeRead.operation().state() != State.COMMITTED + || beforeRead.operation().bindingDecisionId() == null) throw unavailable(); + AccountGameplayAdmissionOriginalAckReceipt receipt = + receiptExecutor.read(requestedLease, beforeRead.operation().bindingDecisionId()); + requireExactReceipt(receipt, beforeRead.operation(), requestedLease); + Genesis beforeGenesis = + inWritableSerializableTransaction( + dsl -> { + SourceRead current = readCurrentOriginalSource(dsl, caller, requestedLease); + requireSameOriginalOperation(beforeRead.operation(), current.operation()); + Genesis stored = + new AccountOriginalNewBoundGameplayIssuanceRepository(dsl) + .readByLease(leaseId(requestedLease)); + if (stored == null + || stored.status() + != AccountOriginalNewBoundGameplayIssuanceRepository.Status.COMMITTED) { + throw unavailable(); + } + return stored; + }); + OriginalNewCredential storedCredential = + beforeGenesis.confirmedAdmissionAtMillis() == null + ? openFrozenCredentialForFinalAdmissionVerification( + caller, requestedLease, receipt, beforeGenesis) + : openCommittedResult(caller, requestedLease, receipt, beforeGenesis); + String storedCompactJwt = storedCredential.signedBoundGsACompactJwt(); + String boundTenantId = tenantId(requestedLease).toString(); + try { + Map boundTuple = + stringObjectMap(beforeGenesis.authorityTupleCanonicalBytes()); + Map boundMembership = + stringStringMap(beforeGenesis.membershipVersionCanonicalBytes()); + signer.verifyOriginalNewBoundCredential( + storedCompactJwt, + beforeGenesis, + beforeRead.accountAuthority(), + boundTenantId, + boundTuple, + boundMembership); + } finally { + storedCredential.close(); + } + ExpectedOriginalAdmission expected = expectedAdmission(requestedLease, beforeGenesis); + + if (beforeGenesis.confirmedAdmissionAtMillis() != null) { + long nowMillis = clock.millis(); + if (nowMillis <= 0L || nowMillis >= beforeGenesis.confirmedContinuityExpiresAtMillis()) + throw unavailable(); + VerifiedCaller currentCaller = verifyCaller(presentedInitialGsACompactJwt, peer); + if (!AccountGameplayDelegationIssuanceRepository.CommittedCandidateVerificationData + .hasSameOwnerEvidence(caller.currentCandidate(), currentCaller.currentCandidate())) { + throw unavailable(); + } + Genesis recovered = + inWritableSerializableTransaction( + dsl -> { + SourceRead current = readCurrentOriginalSource(dsl, currentCaller, requestedLease); + requireSameOriginalOperation(beforeRead.operation(), current.operation()); + AccountGameplayAdmissionOriginalAckReceipt durableReceipt = + new AccountGameplayAdmissionOriginalAckReceiptRepository( + dsl, new AccountGameplayAdmissionLeaseRepository(dsl)) + .readExact(requestedLease, current.operation().bindingDecisionId()); + // The receipt owner already proved independent durability outside this + // transaction. Re-read the immutable row here under current source locks. + requireExactReceipt(durableReceipt, current.operation(), requestedLease); + if (!receipt.equals(durableReceipt)) throw unavailable(); + var issuance = new AccountOriginalNewBoundGameplayIssuanceRepository(dsl); + Genesis exact = issuance.readByLease(leaseId(requestedLease)); + requireSameGenesisIdentity(beforeGenesis, exact); + if (exact.confirmedAdmissionAtMillis() == null + || !Objects.equals( + exact.confirmedAdmissionAtMillis(), + beforeGenesis.confirmedAdmissionAtMillis()) + || !Objects.equals( + exact.confirmedContinuityExpiresAtMillis(), + beforeGenesis.confirmedContinuityExpiresAtMillis()) + || !exact + .confirmationReadbackSha256() + .equals(beforeGenesis.confirmationReadbackSha256())) throw unavailable(); + new AccountGameplayTokenIdentityFenceRepository(dsl) + .requireActiveReadback(originalNewIdentity(exact)); + return exact; + }); + tokenRegistry.requireExactOriginalNewActiveRecord(recovered); + if (clock.millis() >= recovered.confirmedContinuityExpiresAtMillis()) throw unavailable(); + return new OriginalAdmissionConfirmation( + recovered.lineageId(), + recovered.leaseId(), + recovered.confirmedAdmissionAtMillis(), + recovered.confirmedContinuityExpiresAtMillis(), + recovered.confirmationReadbackSha256()); + } + + final AuthenticatedFinalAdmissionReadback finalReadback; + try { + finalReadback = + Objects.requireNonNull( + finalAdmissionReadClient.readActualOriginalFinalAdmission(expected)); + } catch (RuntimeException unavailable) { + throw unavailable(); + } + if (!expected.equals(finalReadback.anchors())) throw unavailable(); + long nowMillis = clock.millis(); + if (nowMillis <= 0L + || finalReadback.admissionAtMillis() > nowMillis + || nowMillis >= finalReadback.continuityExpiresAtMillis()) throw unavailable(); + + // Activation is Account-owned and happens only after the authenticated GS readback exists. + // If its reply is lost, the Redis CAS accepts only the same immutable active projection. + AccountGameplayDelegationRedisClient.OriginalNewActivationReadback activation = + tokenRegistry.activateOriginalNewCommittedPending(beforeGenesis); + requireActivationMatches(beforeGenesis, activation); + + VerifiedCaller currentCaller = verifyCaller(presentedInitialGsACompactJwt, peer); + if (!AccountGameplayDelegationIssuanceRepository.CommittedCandidateVerificationData + .hasSameOwnerEvidence(caller.currentCandidate(), currentCaller.currentCandidate())) { + throw unavailable(); + } + signer.verifyOriginalNewBoundCredential( + storedCompactJwt, + beforeGenesis, + beforeRead.accountAuthority(), + boundTenantId, + stringObjectMap(beforeGenesis.authorityTupleCanonicalBytes()), + stringStringMap(beforeGenesis.membershipVersionCanonicalBytes())); + String confirmationDigest = confirmationDigest(finalReadback, activation); + Genesis confirmed = + inWritableSerializableTransaction( + dsl -> { + SourceRead current = readCurrentOriginalSource(dsl, currentCaller, requestedLease); + requireSameOriginalOperation(beforeRead.operation(), current.operation()); + AccountGameplayAdmissionOriginalAckReceipt durableReceipt = + new AccountGameplayAdmissionOriginalAckReceiptRepository( + dsl, new AccountGameplayAdmissionLeaseRepository(dsl)) + .readExact(requestedLease, current.operation().bindingDecisionId()); + // Keep the independently proved receipt exact; this transaction supplies + // current source exclusion, not another historical durability attempt. + requireExactReceipt(durableReceipt, current.operation(), requestedLease); + if (!receipt.equals(durableReceipt)) throw unavailable(); + var issuance = new AccountOriginalNewBoundGameplayIssuanceRepository(dsl); + Genesis exact = issuance.readByLease(leaseId(requestedLease)); + requireSameGenesisIdentity(beforeGenesis, exact); + TokenIdentity tokenIdentity = originalNewIdentity(exact); + new AccountGameplayTokenIdentityFenceRepository(dsl) + .requireActiveReadback(tokenIdentity); + return issuance.confirmFinalAdmission( + exact, + finalReadback.admissionAtMillis(), + finalReadback.continuityExpiresAtMillis(), + confirmationDigest); + }); + tokenRegistry.requireExactOriginalNewActiveRecord(confirmed); + if (!confirmationDigest.equals(confirmed.confirmationReadbackSha256())) throw unavailable(); + return new OriginalAdmissionConfirmation( + confirmed.lineageId(), + confirmed.leaseId(), + confirmed.confirmedAdmissionAtMillis(), + confirmed.confirmedContinuityExpiresAtMillis(), + confirmed.confirmationReadbackSha256()); + } + + private static ExpectedOriginalAdmission expectedAdmission( + AccountGameplayAdmissionLeaseEvidence lease, Genesis genesis) { + Map scope = object(lease.carrier().get("bindingScope")); + UUID sessionId = uuid(scope.get("sessionId")); + UUID tenantId = uuid(scope.get("tenantId")); + return new ExpectedOriginalAdmission( + genesis.requestId(), + genesis.accountId(), + tenantId, + sessionId, + genesis.bindingDecisionId(), + genesis.leaseId(), + genesis.leaseFence(), + genesis.originalLeaseEvidenceSha256(), + genesis.lineageId(), + genesis.tokenJti(), + genesis.tokenHash(), + genesis.tokenGeneration(), + genesis.issuanceFence(), + genesis.bindingScopeSha256(), + sha256(genesis.membershipBaselineCanonicalBytes()), + sha256(genesis.outboxCheckpointsCanonicalBytes()), + genesis.rebindHandleSha256()); + } + + private static void requireActivationMatches( + Genesis genesis, + AccountGameplayDelegationRedisClient.OriginalNewActivationReadback activation) { + if (activation == null + || !genesis.tokenHash().equals(activation.tokenHash()) + || !genesis.accountId().toString().equals(activation.accountId()) + || !genesis.lineageId().toString().equals(activation.lineageId()) + || !genesis.tokenJti().toString().equals(activation.tokenJti()) + || activation.localAofCount() < 1L + || activation.replicaAofCount() < 1L) throw unavailable(); + } + + private static String confirmationDigest( + AuthenticatedFinalAdmissionReadback finalReadback, + AccountGameplayDelegationRedisClient.OriginalNewActivationReadback activation) { + Map fields = new LinkedHashMap<>(); + fields.put("domain", "account-original-new-final-admission-confirmation/v1"); + fields.put("finalReadbackSha256", finalReadback.canonicalReadbackSha256()); + fields.put("admissionAtMs", Long.toString(finalReadback.admissionAtMillis())); + fields.put("continuityExpiresAtMs", Long.toString(finalReadback.continuityExpiresAtMillis())); + fields.put("sessionDurationMs", Long.toString(finalReadback.canonicalSessionDurationMillis())); + fields.put("activeRecordSha256", activation.activeRecordSha256()); + fields.put("redisAbsoluteExpiryMs", Long.toString(activation.absoluteExpiryMillis())); + return sha256(canonicalJson(fields)); + } + + private Genesis signAndPersistCandidate( + VerifiedCaller caller, + AccountGameplayAdmissionLeaseEvidence lease, + AccountGameplayAdmissionOriginalAckReceipt receipt, + Genesis genesis) { + Map tuple = stringObjectMap(genesis.authorityTupleCanonicalBytes()); + Map membershipVersion = + stringStringMap(genesis.membershipVersionCanonicalBytes()); + Object tenantValue = objectMap(genesis.bindingScopeCanonicalBytes()).get("tenantId"); + if (!(tenantValue instanceof String tenantId)) throw unavailable(); + AccountAuthoritySnapshot accountAuthority = caller.currentCandidate().authoritySnapshot(); + EvidenceBundleReference evidenceReference = caller.currentCandidate().evidenceBundleReference(); + + byte[] handle = new byte[32]; + byte[] compactBytes = null; + byte[] envelopeBytes = null; + byte[] recordBytes = null; + byte[] payload = null; + try { + secureRandom.nextBytes(handle); + try (OriginalNewBoundSignedCandidate signed = + signer.signOriginalNewBoundCandidate( + genesis, accountAuthority, tenantId, tuple, membershipVersion)) { + compactBytes = signed.compactJwtBytes(); + String compactJwt = new String(compactBytes, StandardCharsets.US_ASCII); + GameSessionAccountDelegationRegistryRecord record = + GameSessionAccountDelegationRegistryRecord.fromAccountSignedBoundCompactJwt( + compactJwt, + signed.signerGeneration(), + new IssuanceBinding( + genesis.lineageId().toString(), + genesis.requestId().toString(), + genesis.requestDigest(), + genesis.accountId().toString()), + accountAuthority, + evidenceReference, + tenantId, + tuple, + membershipVersion, + genesis.issuedAtEpochSecond(), + GameSessionAccountDelegationProfile.MAX_REGISTRY_RECORD_BYTES); + recordBytes = + record.toCanonicalJsonBytes( + GameSessionAccountDelegationProfile.MAX_REGISTRY_RECORD_BYTES); + if (!signed.tokenHash().equals(record.tokenHash())) throw unavailable(); + payload = encodeProtectedResult(compactBytes, handle); + EncryptedResponseEnvelope envelope = + responseCryptography.encrypt( + responseBinding(genesis, lease, receipt), + payload, + Instant.ofEpochSecond(genesis.expiresAtEpochSecond())); + envelopeBytes = envelope.bytes(); + String handleHash = sha256(handle); + String tokenHash = signed.tokenHash(); + String signerKid = signed.signerKid(); + String signerGeneration = signed.signerGeneration(); + byte[] exactRecord = recordBytes.clone(); + byte[] exactEnvelope = envelopeBytes.clone(); + try { + return inWritableSerializableTransaction( + dsl -> { + SourceRead current = readCurrentOriginalSource(dsl, caller, lease); + if (current.operation().state() != State.COMMITTED + || !current + .operation() + .bindingDecisionId() + .equals(receipt.bindingDecisionId())) { + throw unavailable(); + } + requireExactReceipt(receipt, current.operation(), lease); + Genesis currentGenesis = + new AccountOriginalNewBoundGameplayIssuanceRepository(dsl) + .readByLease(leaseId(lease)); + requireSameGenesisIdentity(genesis, currentGenesis); + return new AccountOriginalNewBoundGameplayIssuanceRepository(dsl) + .bindSignedResult( + currentGenesis, + tokenHash, + signerKid, + signerGeneration, + exactRecord, + handleHash, + exactEnvelope); + }); + } finally { + wipe(exactRecord); + wipe(exactEnvelope); + } + } + } finally { + wipe(handle); + wipe(compactBytes); + wipe(envelopeBytes); + wipe(recordBytes); + wipe(payload); + } + } + + private OriginalNewCredential openCommittedResult( + VerifiedCaller caller, + AccountGameplayAdmissionLeaseEvidence lease, + AccountGameplayAdmissionOriginalAckReceipt receipt, + Genesis expectedGenesis) { + SourceRead source = readCurrentOriginalSource(caller, lease); + requireExactReceipt(receipt, source.operation(), lease); + Genesis committed = + inWritableSerializableTransaction( + dsl -> { + SourceRead current = readCurrentOriginalSource(dsl, caller, lease); + requireSameOriginalOperation(source.operation(), current.operation()); + var issuance = new AccountOriginalNewBoundGameplayIssuanceRepository(dsl); + Genesis exact = issuance.readByLease(leaseId(lease)); + requireSameGenesisIdentity(expectedGenesis, exact); + if (exact.status() + != AccountOriginalNewBoundGameplayIssuanceRepository.Status.COMMITTED) { + throw unavailable(); + } + var tokenIdentity = + new TokenIdentity( + exact.accountId(), + exact.lineageId(), + exact.requestId(), + exact.tokenHash(), + exact.tokenJti(), + exact.notBeforeEpochSecond(), + exact.tokenGeneration(), + exact.issuanceFence(), + SourceKind.ORIGINAL_NEW); + new AccountGameplayTokenIdentityFenceRepository(dsl) + .requireActiveReadback(tokenIdentity); + return exact; + }); + + if (committed.confirmedAdmissionAtMillis() != null) { + tokenRegistry.requireExactOriginalNewActiveRecord(committed); + } else { + tokenRegistry.registerOriginalNewPending(committed); + } + + return openFrozenCredentialResult(lease, receipt, source, committed); + } + + /** + * Opens only the already-frozen signed credential needed to verify Account's actual Game Session + * final-admission read. This path deliberately does not require or mutate a Redis registry state; + * the later positive result still requires the authenticated Game Session read and the exact + * Account-owned pending-to-active CAS. + */ + private OriginalNewCredential openFrozenCredentialForFinalAdmissionVerification( + VerifiedCaller caller, + AccountGameplayAdmissionLeaseEvidence lease, + AccountGameplayAdmissionOriginalAckReceipt receipt, + Genesis expectedGenesis) { + SourceRead source = readCurrentOriginalSource(caller, lease); + requireExactReceipt(receipt, source.operation(), lease); + Genesis committed = + inWritableSerializableTransaction( + dsl -> { + SourceRead current = readCurrentOriginalSource(dsl, caller, lease); + requireSameOriginalOperation(source.operation(), current.operation()); + var issuance = new AccountOriginalNewBoundGameplayIssuanceRepository(dsl); + Genesis exact = issuance.readByLease(leaseId(lease)); + requireSameGenesisIdentity(expectedGenesis, exact); + if (exact.status() + != AccountOriginalNewBoundGameplayIssuanceRepository.Status.COMMITTED) { + throw unavailable(); + } + new AccountGameplayTokenIdentityFenceRepository(dsl) + .requireActiveReadback(originalNewIdentity(exact)); + return exact; + }); + + return openFrozenCredentialResult(lease, receipt, source, committed); + } + + private OriginalNewCredential openFrozenCredentialResult( + AccountGameplayAdmissionLeaseEvidence lease, + AccountGameplayAdmissionOriginalAckReceipt receipt, + SourceRead source, + Genesis committed) { + + byte[] plaintext = null; + try { + plaintext = + responseCryptography.decrypt( + new EncryptedResponseEnvelope(committed.encryptedResultEnvelopeBytes()), + responseBinding(committed, lease, receipt), + Instant.ofEpochSecond(committed.expiresAtEpochSecond())); + OpenedProtectedResult stored = decodeProtectedResult(plaintext); + byte[] jwtBytes = stored.compactJwtBytes(); + byte[] handle = stored.handleBytes(); + try { + if (handle.length != 32 + || !sha256(handle).equals(committed.rebindHandleSha256()) + || !sha256(jwtBytes).equals(committed.tokenHash())) { + throw unavailable(); + } + String compactJwt = new String(jwtBytes, StandardCharsets.US_ASCII); + signer.verifyOriginalNewBoundCredential( + compactJwt, + committed, + source.accountAuthority(), + tenantId(lease).toString(), + stringObjectMap(committed.authorityTupleCanonicalBytes()), + stringStringMap(committed.membershipVersionCanonicalBytes())); + return AccountGameplayAdmissionLeaseGrpcCodec.originalNewCredential( + compactJwt, + handle, + committed.lineageId(), + committed.tokenJti(), + committed.tokenHash(), + committed.issuanceFence(), + committed.leaseId(), + committed.leaseFence(), + receipt.receiptXid(), + sha256(committed.outboxCheckpointsCanonicalBytes())); + } finally { + wipe(handle); + wipe(jwtBytes); + } + } catch (RuntimeException failure) { + throw unavailable(); + } finally { + wipe(plaintext); + } + } + + private SourceRead readCurrentOriginalSource( + VerifiedCaller caller, AccountGameplayAdmissionLeaseEvidence lease) { + return inWritableSerializableTransaction(dsl -> readCurrentOriginalSource(dsl, caller, lease)); + } + + private SourceRead readCurrentOriginalSource( + DSLContext dsl, VerifiedCaller caller, AccountGameplayAdmissionLeaseEvidence lease) { + UUID tenantId = tenantId(lease); + AccountGameplayAdmissionCurrentSources sourceReader = + AccountGameplayAdmissionCurrentSources.bind(dsl, workloadNamespace); + var current = + sourceReader.readCurrentPublicProductionNew( + tenantId, caller.identity().tokenJti(), caller.currentCandidate()); + current.requireMatchesOriginalLease(lease); + AccountGameplayAdmissionLeaseOperation operation = + new AccountGameplayAdmissionLeaseRepository(dsl) + .readExact(lease) + .orElseThrow(AccountOriginalNewBoundGameplayCredentialOwner::unavailable); + return new SourceRead(operation, current.currentCommittedCandidate().authoritySnapshot()); + } + + private Binding responseBinding( + Genesis genesis, + AccountGameplayAdmissionLeaseEvidence lease, + AccountGameplayAdmissionOriginalAckReceipt receipt) { + Map evidence = new LinkedHashMap<>(); + evidence.put("bindingScopeSha256", genesis.bindingScopeSha256()); + evidence.put("leaseEvidenceSha256", genesis.originalLeaseEvidenceSha256()); + evidence.put("ackEvidenceSha256", genesis.originalAckEvidenceSha256()); + evidence.put("ackReceiptXid", genesis.originalAckReceiptXid()); + evidence.put("outboxCheckpoints", checkpointArray(genesis.outboxCheckpointsCanonicalBytes())); + evidence.put("receiptCommittedBeforeMs", Long.toString(receipt.committedBeforeMs())); + byte[] evidenceBytes = canonicalJson(evidence); + try { + return new Binding( + ENVELOPE_OPERATION, + genesis.requestId().toString(), + HexFormat.of().parseHex(genesis.requestDigest()), + genesis.callerWorkload(), + genesis.leaseId().toString(), + Optional.of(genesis.lineageId().toString()), + Optional.empty(), + Optional.of(genesis.leaseId().toString()), + genesis.issuanceFence(), + genesis.authorityTupleCanonicalBytes(), + genesis.membershipVersionCanonicalBytes(), + evidenceBytes); + } finally { + wipe(evidenceBytes); + } + } + + private static byte[] encodeProtectedResult(byte[] compactJwt, byte[] handle) { + if (compactJwt == null + || compactJwt.length == 0 + || compactJwt.length > GameSessionAccountDelegationProfile.MAX_COMPACT_JWT_BYTES + || handle == null + || handle.length != 32) throw unavailable(); + ByteBuffer framed = ByteBuffer.allocate(8 + compactJwt.length + handle.length); + framed.put(new byte[] {'F', 'O', 'N', '1'}); + framed.putInt(compactJwt.length); + framed.put(compactJwt); + framed.put(handle); + return framed.array(); + } + + private static OpenedProtectedResult decodeProtectedResult(byte[] exactBytes) { + if (exactBytes == null + || exactBytes.length < 8 + 1 + 32 + || exactBytes.length > GameSessionAccountDelegationProfile.MAX_COMPACT_JWT_BYTES + 40) { + throw unavailable(); + } + ByteBuffer input = ByteBuffer.wrap(exactBytes); + if (input.get() != 'F' || input.get() != 'O' || input.get() != 'N' || input.get() != '1') { + throw unavailable(); + } + int jwtLength = input.getInt(); + if (jwtLength <= 0 + || jwtLength > GameSessionAccountDelegationProfile.MAX_COMPACT_JWT_BYTES + || input.remaining() != jwtLength + 32) throw unavailable(); + byte[] jwt = new byte[jwtLength]; + byte[] handle = new byte[32]; + input.get(jwt); + input.get(handle); + for (byte value : jwt) { + if (Byte.toUnsignedInt(value) > 0x7f) { + wipe(jwt); + wipe(handle); + throw unavailable(); + } + } + return new OpenedProtectedResult(jwt, handle); + } + + private static byte[] canonicalJson(Object value) { + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } catch (Exception malformed) { + throw unavailable(); + } + } + + private static Map stringObjectMap(byte[] bytes) { + return parseJsonMap(bytes); + } + + private static Map stringStringMap(byte[] bytes) { + Map value = parseJsonMap(bytes); + Map copy = new LinkedHashMap<>(); + value.forEach( + (key, item) -> { + if (!(key instanceof String textKey) || !(item instanceof String textValue)) { + throw unavailable(); + } + copy.put(textKey, textValue); + }); + return Map.copyOf(copy); + } + + private static Map objectMap(byte[] bytes) { + return parseJsonMap(bytes); + } + + private static Map parseJsonMap(byte[] bytes) { + try { + return JSON.readValue(bytes, Map.class); + } catch (Exception malformed) { + throw unavailable(); + } + } + + private static List checkpointArray(byte[] bytes) { + try { + return JSON.readValue(bytes, List.class); + } catch (Exception malformed) { + throw unavailable(); + } + } + + private VerifiedCaller verifyCaller(String compactJwt, GrpcPeerIdentity peer) { + VerifiedCaller caller; + try { + caller = callerVerifier.verifyPresentedCompactToken(compactJwt); + } catch (RuntimeException failure) { + throw unavailable(); + } + if (!peer.uri().equals(caller.identity().callerWorkload())) throw unavailable(); + return caller; + } + + private void requireCallerMatchesLease( + VerifiedCaller caller, GrpcPeerIdentity peer, AccountGameplayAdmissionLeaseEvidence lease) { + Map carrier = lease.carrier(); + Map scope = object(carrier.get("bindingScope")); + Map token = object(carrier.get("tokenIdentityEvidence")); + if (lease.leaseKind() != AccountGameplayAdmissionLeaseEvidence.LeaseKind.NEW_BINDING + || !workloadNamespace.equals(carrier.get("targetNamespace")) + || !peer.uri().equals(carrier.get("callerWorkload")) + || !peer.uri().equals(caller.identity().callerWorkload()) + || !caller.identity().accountId().toString().equals(scope.get("accountId")) + || !caller.identity().tokenJti().toString().equals(token.get("tokenJti")) + || !caller.currentCandidate().tokenSha256().equals(token.get("tokenSHA256"))) { + throw unavailable(); + } + } + + private GrpcPeerIdentity requireGameSessionCaller() { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (peer == null + || SessionContext.hasAuthenticatedCallerContext() + || SessionContext.isInternalService() + || SessionContext.getServiceName() != null + || SessionContext.getServiceInstanceId() != null + || !GAME_SESSION_SERVICE.equals(peer.service()) + || !workloadNamespace.equals(peer.namespace()) + || !("spiffe://firemud/ns/" + workloadNamespace + "/sa/game-session-service") + .equals(peer.uri())) { + throw Status.PERMISSION_DENIED + .withDescription("Exact same-namespace Game Session workload required") + .asRuntimeException(); + } + return peer; + } + + private void requireNoAmbientSql() { + Object managed = + Objects.requireNonNull(new DataSourceTransactionManager(dataSource).getDataSource()); + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive() + || TransactionSynchronizationManager.hasResource(dataSource) + || TransactionSynchronizationManager.hasResource(managed)) { + throw Status.FAILED_PRECONDITION + .withDescription("Original-new credential owner requires no ambient Account transaction") + .asRuntimeException(); + } + } + + private T inWritableSerializableTransaction( + java.util.function.Function operation) { + DataSourceTransactionManager manager = new DataSourceTransactionManager(dataSource); + TransactionTemplate transaction = new TransactionTemplate(manager); + transaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE); + transaction.setReadOnly(false); + T result = + transaction.execute( + status -> { + if (!status.isNewTransaction()) throw unavailable(); + Object resource = + TransactionSynchronizationManager.getResource( + Objects.requireNonNull(manager.getDataSource())); + if (!(resource instanceof ConnectionHolder holder)) throw unavailable(); + var connection = holder.getConnection(); + try { + if (connection.getAutoCommit() + || connection.isReadOnly() + || connection.getTransactionIsolation() + != java.sql.Connection.TRANSACTION_SERIALIZABLE) throw unavailable(); + } catch (java.sql.SQLException failure) { + throw unavailable(); + } + return operation.apply(DSL.using(connection, SQLDialect.POSTGRES)); + }); + return Objects.requireNonNull(result); + } + + private static byte[] pendingRegistryReceiptBytes(PendingRegistrationReceipt receipt) { + Map fields = new LinkedHashMap<>(); + fields.put("domain", "account-original-new-pending-registry-receipt/v1"); + fields.put("aclIdentity", receipt.aclIdentity()); + fields.put("operationId", receipt.operationId()); + fields.put("requestId", receipt.requestId()); + fields.put("requestDigest", receipt.requestDigest()); + fields.put("accountId", receipt.accountId()); + fields.put("tokenJti", receipt.tokenJti()); + fields.put("tokenHash", receipt.tokenHash()); + fields.put("recordSha256", receipt.canonicalRecordSha256()); + fields.put("absoluteExpiryMillis", Long.toString(receipt.absoluteExpiryMillis())); + fields.put("localAofCount", Long.toString(receipt.localAofCount())); + fields.put("replicaAofCount", Long.toString(receipt.replicaAofCount())); + fields.put("registryVersion", Long.toString(receipt.registryVersion())); + return canonicalJson(fields); + } + + private static String pendingRegistryReceiptDigest(PendingRegistrationReceipt receipt) { + byte[] proof = pendingRegistryReceiptBytes(Objects.requireNonNull(receipt)); + try { + return sha256(proof); + } finally { + wipe(proof); + } + } + + private static void requireExactReceipt( + AccountGameplayAdmissionOriginalAckReceipt receipt, + AccountGameplayAdmissionLeaseOperation operation, + AccountGameplayAdmissionLeaseEvidence lease) { + if (operation == null + || receipt == null + || operation.state() != State.COMMITTED + || !operation.evidence().hasSameIdentity(lease) + || !receipt.operation().evidence().hasSameIdentity(lease) + || !receipt.bindingDecisionId().equals(operation.bindingDecisionId()) + || !receipt.evidenceSha256().equals(lease.sha256())) throw unavailable(); + } + + private static void requireSameOriginalOperation( + AccountGameplayAdmissionLeaseOperation expected, + AccountGameplayAdmissionLeaseOperation actual) { + if (expected == null + || actual == null + || expected.state() != State.COMMITTED + || actual.state() != State.COMMITTED + || !expected.evidence().hasSameIdentity(actual.evidence()) + || !Objects.equals(expected.bindingDecisionId(), actual.bindingDecisionId())) + throw unavailable(); + } + + private static void requireSameGenesisIdentity(Genesis expected, Genesis actual) { + if (expected == null + || actual == null + || !expected.lineageId().equals(actual.lineageId()) + || !expected.tokenJti().equals(actual.tokenJti()) + || !expected.requestDigest().equals(actual.requestDigest()) + || !expected.leaseId().equals(actual.leaseId()) + || expected.issuanceFence() != actual.issuanceFence()) throw unavailable(); + } + + private static UUID tenantId(AccountGameplayAdmissionLeaseEvidence lease) { + Object value = object(lease.carrier().get("bindingScope")).get("tenantId"); + if (!(value instanceof String text)) throw unavailable(); + try { + UUID parsed = UUID.fromString(text); + if (!parsed.toString().equals(text) || parsed.version() != 4 || parsed.variant() != 2) + throw unavailable(); + return parsed; + } catch (IllegalArgumentException malformed) { + throw unavailable(); + } + } + + private static UUID leaseId(AccountGameplayAdmissionLeaseEvidence lease) { + Object value = lease.carrier().get("leaseId"); + if (!(value instanceof String text)) throw unavailable(); + try { + UUID parsed = UUID.fromString(text); + if (!parsed.toString().equals(text) || parsed.version() != 4 || parsed.variant() != 2) + throw unavailable(); + return parsed; + } catch (IllegalArgumentException malformed) { + throw unavailable(); + } + } + + private static Map object(Object value) { + if (!(value instanceof Map map)) throw unavailable(); + return map; + } + + private static UUID uuid(Object value) { + if (!(value instanceof String text)) throw unavailable(); + try { + UUID parsed = UUID.fromString(text); + if (!parsed.toString().equals(text) || parsed.version() != 4 || parsed.variant() != 2) { + throw unavailable(); + } + return parsed; + } catch (IllegalArgumentException malformed) { + throw unavailable(); + } + } + + private static TokenIdentity originalNewIdentity(Genesis genesis) { + return new TokenIdentity( + genesis.accountId(), + genesis.lineageId(), + genesis.requestId(), + genesis.tokenHash(), + genesis.tokenJti(), + genesis.notBeforeEpochSecond(), + genesis.tokenGeneration(), + genesis.issuanceFence(), + SourceKind.ORIGINAL_NEW); + } + + private static String sha256(byte[] value) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value)); + } catch (NoSuchAlgorithmException impossible) { + throw unavailable(); + } + } + + private static void wipe(byte[] bytes) { + if (bytes != null) Arrays.fill(bytes, (byte) 0); + } + + private static IllegalStateException unavailable() { + return new IllegalStateException("Original-new bound gameplay credential is unavailable"); + } + + private record SourceRead( + AccountGameplayAdmissionLeaseOperation operation, AccountAuthoritySnapshot accountAuthority) { + SourceRead { + Objects.requireNonNull(operation); + Objects.requireNonNull(accountAuthority); + } + } + + private record OpenedProtectedResult(byte[] compactJwtBytes, byte[] handleBytes) {} + + /** Actual original-admission anchors returned only by the Account-side confirmation hook. */ + public static final class OriginalAdmissionConfirmation { + private final UUID lineageId; + private final UUID originalLeaseId; + private final long admissionAtMillis; + private final long continuityExpiresAtMillis; + private final String authenticatedConfirmationSha256; + + private OriginalAdmissionConfirmation( + UUID lineageId, + UUID originalLeaseId, + long admissionAtMillis, + long continuityExpiresAtMillis, + String authenticatedConfirmationSha256) { + this.lineageId = Objects.requireNonNull(lineageId); + this.originalLeaseId = Objects.requireNonNull(originalLeaseId); + if (admissionAtMillis <= 0L || continuityExpiresAtMillis <= admissionAtMillis) { + throw unavailable(); + } + this.admissionAtMillis = admissionAtMillis; + this.continuityExpiresAtMillis = continuityExpiresAtMillis; + this.authenticatedConfirmationSha256 = + Objects.requireNonNull(authenticatedConfirmationSha256); + if (!authenticatedConfirmationSha256.matches("[0-9a-f]{64}")) throw unavailable(); + } + + public UUID lineageId() { + return lineageId; + } + + public UUID originalLeaseId() { + return originalLeaseId; + } + + public long admissionAtMillis() { + return admissionAtMillis; + } + + public long continuityExpiresAtMillis() { + return continuityExpiresAtMillis; + } + + public String authenticatedConfirmationSha256() { + return authenticatedConfirmationSha256; + } + + @Override + public String toString() { + return "OriginalAdmissionConfirmation[redacted]"; + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountOriginalNewBoundGameplayIssuanceRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountOriginalNewBoundGameplayIssuanceRepository.java new file mode 100644 index 0000000000..cb4221300d --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountOriginalNewBoundGameplayIssuanceRepository.java @@ -0,0 +1,935 @@ +package net.firedevops.firemud.accountservice.repository; + +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.Objects; +import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionLeaseOperation.State; +import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionOriginalAckReceipt; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.databind.json.JsonMapper; + +/** + * Durable Account owner for the single ORIGINAL-NEW bound-token lineage attached to one committed + * Account admission lease. LOGIN issuance remains in its existing table and has no changed shape. + * + *

This repository only records exact owner-produced identity and postcondition evidence. It does + * not sign credentials, establish the Game Session final-admission result, or make a handle + * consumable without the caller's independent current-source and authenticated-read checks. + */ +public final class AccountOriginalNewBoundGameplayIssuanceRepository { + private static final String TABLE = "account_original_new_bound_gameplay_issuances"; + private static final JsonMapper JSON = JsonMapper.builder().build(); + + private final DSLContext dsl; + + public AccountOriginalNewBoundGameplayIssuanceRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl, "Account DSLContext is required"); + } + + /** + * Creates one fresh generation-1 lineage or returns that exact lineage for a matching lease. + * Generated IDs and token times are inputs used only for a new row; a retry always returns the + * originally persisted IDs and times and never starts another lineage. + */ + public Genesis beginGenesis( + AccountGameplayAdmissionLeaseEvidence lease, + AccountGameplayAdmissionOriginalAckReceipt receipt, + UUID operationId, + UUID tokenJti, + long issuedAtEpochSecond, + long notBeforeEpochSecond, + long expiresAtEpochSecond) { + requireWritableSerializableTransaction(); + Objects.requireNonNull(lease, "Exact original Account lease is required"); + Objects.requireNonNull(receipt, "Durable original Account ACK receipt is required"); + requireUuidV4(operationId); + requireUuidV4(tokenJti); + if (operationId.equals(tokenJti) + || issuedAtEpochSecond <= 0L + || notBeforeEpochSecond <= 0L + || notBeforeEpochSecond > issuedAtEpochSecond + || expiresAtEpochSecond <= issuedAtEpochSecond + || expiresAtEpochSecond - issuedAtEpochSecond + > GameSessionAccountDelegationProfile.MAX_TOKEN_LIFETIME_SECONDS) { + throw unavailable(); + } + + Map carrier = lease.carrier(); + Map scope = object(carrier.get("bindingScope")); + UUID requestId = uuid(carrier.get("requestId")); + UUID leaseId = uuid(carrier.get("leaseId")); + UUID accountId = uuid(scope.get("accountId")); + UUID bindingDecisionId = receipt.bindingDecisionId(); + long leaseFence = lease.leaseFence().longValueExact(); + long issuanceFence = positiveLong(carrier.get("issuanceFence")); + requireOriginalAck(lease, receipt, requestId, accountId, leaseId, leaseFence); + + byte[] scopeBytes = canonicalBytes(scope); + String bindingScopeSha256 = sha256(scopeBytes); + byte[] tupleBytes = canonicalBytes(carrier.get("authorityTuple")); + Map baseline = object(carrier.get("membershipBaseline")); + byte[] membershipBaselineBytes = canonicalBytes(baseline); + byte[] membershipVersionBytes = canonicalBytes(baseline.get("membershipVersion")); + byte[] checkpointsBytes = canonicalBytes(carrier.get("outboxCheckpoints")); + String requestDigest = + requestDigest( + lease, + receipt, + scopeBytes, + tupleBytes, + membershipBaselineBytes, + membershipVersionBytes, + checkpointsBytes); + try { + // Account first, then the original lease/receipt rows, then this lineage row. The trigger + // independently checks the exact committed operation and separate ACK receipt on INSERT. + dsl.fetchOne( + "SELECT account_uuid FROM accounts WHERE account_uuid = ? FOR UPDATE", accountId); + Record retained = + dsl.fetchOne("SELECT * FROM " + TABLE + " WHERE lease_id = ? FOR UPDATE", leaseId); + if (retained != null) { + Genesis exact = decode(retained); + requireSameFrozenSource( + exact, + requestId, + accountId, + leaseId, + leaseFence, + bindingDecisionId, + lease, + receipt, + requestDigest, + bindingScopeSha256, + scopeBytes, + tupleBytes, + membershipBaselineBytes, + membershipVersionBytes, + checkpointsBytes, + issuanceFence); + return exact; + } + Record priorBinding = + dsl.fetchOne( + "SELECT * FROM " + TABLE + " WHERE binding_scope_sha256 = ? FOR UPDATE", + bindingScopeSha256); + if (priorBinding != null) throw unavailable(); + + int inserted = + dsl.execute( + "INSERT INTO " + + TABLE + + " (operation_id, request_id, account_uuid, caller_workload, request_digest, " + + "lease_id, lease_fence, binding_decision_id, binding_scope_sha256, " + + "original_lease_evidence_sha256, " + + "original_ack_receipt_xid, original_ack_evidence_sha256, " + + "binding_scope_canonical_bytes, authority_tuple_canonical_bytes, " + + "membership_baseline_canonical_bytes, membership_version_canonical_bytes, " + + "outbox_checkpoints_canonical_bytes, " + + "issuance_fence, token_jti, token_generation, issued_at_epoch_second, " + + "not_before_epoch_second, expires_at_epoch_second) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, ?, ?, ?) " + + "ON CONFLICT DO NOTHING", + operationId, + requestId, + accountId, + carrier.get("callerWorkload"), + requestDigest, + leaseId, + leaseFence, + bindingDecisionId, + bindingScopeSha256, + lease.sha256(), + receipt.receiptXid(), + receipt.evidenceSha256(), + scopeBytes, + tupleBytes, + membershipBaselineBytes, + membershipVersionBytes, + checkpointsBytes, + issuanceFence, + tokenJti, + issuedAtEpochSecond, + notBeforeEpochSecond, + expiresAtEpochSecond); + if (inserted != 1) throw unavailable(); + Record readback = + dsl.fetchOne("SELECT * FROM " + TABLE + " WHERE lease_id = ? FOR UPDATE", leaseId); + if (readback == null) throw unavailable(); + Genesis created = decode(readback); + requireSameFrozenSource( + created, + requestId, + accountId, + leaseId, + leaseFence, + bindingDecisionId, + lease, + receipt, + requestDigest, + bindingScopeSha256, + scopeBytes, + tupleBytes, + membershipBaselineBytes, + membershipVersionBytes, + checkpointsBytes, + issuanceFence); + if (!created.lineageId().equals(operationId) + || !created.tokenJti().equals(tokenJti) + || created.issuedAtEpochSecond() != issuedAtEpochSecond + || created.notBeforeEpochSecond() != notBeforeEpochSecond + || created.expiresAtEpochSecond() != expiresAtEpochSecond) throw unavailable(); + return created; + } finally { + wipe(scopeBytes); + wipe(tupleBytes); + wipe(membershipBaselineBytes); + wipe(membershipVersionBytes); + wipe(checkpointsBytes); + } + } + + /** Binds the exact signed candidate, opaque-handle hash, and encrypted result once. */ + public Genesis bindSignedResult( + Genesis genesis, + String tokenHash, + String signerKid, + String signerGeneration, + byte[] canonicalPendingRegistryRecord, + String opaqueHandleHash, + byte[] encryptedResultEnvelope) { + requireWritableSerializableTransaction(); + Objects.requireNonNull(genesis); + requireSha256(tokenHash); + requireSha256(opaqueHandleHash); + if (signerKid == null || !signerKid.matches("[A-Za-z0-9_-]{1,64}")) throw unavailable(); + requirePositiveDecimal(signerGeneration); + requireBytes(canonicalPendingRegistryRecord, 16 * 1024); + requireBytes(encryptedResultEnvelope, 65_610); + String envelopeHash = sha256(encryptedResultEnvelope); + + Record prior = requireByLeaseForUpdate(genesis.leaseId()); + Genesis current = decode(prior); + requireSameGenesis(genesis, current); + if (current.tokenHash() != null) { + if (!tokenHash.equals(current.tokenHash()) + || !signerKid.equals(current.signerKid()) + || !signerGeneration.equals(current.signerGeneration()) + || !Arrays.equals(canonicalPendingRegistryRecord, current.pendingRegistryRecordBytes()) + || !opaqueHandleHash.equals(current.rebindHandleSha256()) + || !envelopeHash.equals(current.encryptedResultEnvelopeSha256()) + || !Arrays.equals(encryptedResultEnvelope, current.encryptedResultEnvelopeBytes())) { + throw unavailable(); + } + return current; + } + int changed = + dsl.execute( + "UPDATE " + + TABLE + + " SET token_hash = ?, signer_kid = ?, signer_generation = ?, " + + "pending_registry_record_bytes = ?, rebind_handle_sha256 = ?, " + + "encrypted_result_envelope_sha256 = ?, encrypted_result_envelope_bytes = ? " + + "WHERE operation_id = ? AND status = 'PENDING' AND token_hash IS NULL", + tokenHash, + signerKid, + signerGeneration, + canonicalPendingRegistryRecord, + opaqueHandleHash, + envelopeHash, + encryptedResultEnvelope, + genesis.lineageId()); + if (changed != 1) throw unavailable(); + Genesis readback = decode(requireByLeaseForUpdate(genesis.leaseId())); + requireSameGenesis(genesis, readback); + if (!tokenHash.equals(readback.tokenHash()) + || !opaqueHandleHash.equals(readback.rebindHandleSha256()) + || !envelopeHash.equals(readback.encryptedResultEnvelopeSha256()) + || !Arrays.equals(canonicalPendingRegistryRecord, readback.pendingRegistryRecordBytes()) + || !Arrays.equals(encryptedResultEnvelope, readback.encryptedResultEnvelopeBytes())) { + throw unavailable(); + } + return readback; + } + + /** Finalizes only the existing one-way issuance after exact pending-registry readback. */ + public Genesis commit(Genesis genesis, String pendingRegistryReceiptSha256) { + requireWritableSerializableTransaction(); + Objects.requireNonNull(genesis); + requireSha256(pendingRegistryReceiptSha256); + Genesis current = decode(requireByLeaseForUpdate(genesis.leaseId())); + requireSameGenesis(genesis, current); + if (current.status() == Status.COMMITTED) { + if (!pendingRegistryReceiptSha256.equals(current.committedRegistryReceiptSha256())) { + throw unavailable(); + } + return current; + } + if (current.tokenHash() == null) throw unavailable(); + int changed = + dsl.execute( + "UPDATE " + + TABLE + + " SET status = 'COMMITTED', committed_registry_receipt_sha256 = ?, " + + "committed_at = CURRENT_TIMESTAMP WHERE operation_id = ? AND status = 'PENDING' " + + "AND token_hash = ? AND rebind_handle_sha256 = ?", + pendingRegistryReceiptSha256, + genesis.lineageId(), + current.tokenHash(), + current.rebindHandleSha256()); + if (changed != 1) throw unavailable(); + Genesis committed = decode(requireByLeaseForUpdate(genesis.leaseId())); + if (committed.status() != Status.COMMITTED + || !pendingRegistryReceiptSha256.equals(committed.committedRegistryReceiptSha256())) { + throw unavailable(); + } + return committed; + } + + /** Readback by exact original lease; this does not authenticate the supplied lease or caller. */ + public Genesis readByLease(UUID leaseId) { + requireReadableTransaction(); + requireUuidV4(leaseId); + Record row = dsl.fetchOne("SELECT * FROM " + TABLE + " WHERE lease_id = ?", leaseId); + return row == null ? null : decode(row); + } + + /** Stores the actual Account-authenticated Game Session final-readback anchors once. */ + Genesis confirmFinalAdmission( + Genesis expected, + long actualAdmissionAtMillis, + long actualContinuityExpiresAtMillis, + String authenticatedReadbackSha256) { + requireWritableSerializableTransaction(); + Objects.requireNonNull(expected); + requireSha256(authenticatedReadbackSha256); + if (actualAdmissionAtMillis <= 0L || actualContinuityExpiresAtMillis <= actualAdmissionAtMillis) + throw unavailable(); + Genesis current = decode(requireByLeaseForUpdate(expected.leaseId())); + requireSameGenesis(expected, current); + if (current.status() != Status.COMMITTED) throw unavailable(); + if (current.confirmedAdmissionAtMillis() != null) { + if (current.confirmedAdmissionAtMillis() != actualAdmissionAtMillis + || current.confirmedContinuityExpiresAtMillis() != actualContinuityExpiresAtMillis + || !authenticatedReadbackSha256.equals(current.confirmationReadbackSha256())) { + throw unavailable(); + } + return current; + } + int changed = + dsl.execute( + "UPDATE " + + TABLE + + " SET confirmed_admission_at_ms = ?, confirmed_continuity_expires_at_ms = ?, " + + "confirmation_readback_sha256 = ? WHERE operation_id = ? AND status = 'COMMITTED' " + + "AND confirmed_admission_at_ms IS NULL AND handle_consumed_at_ms IS NULL", + actualAdmissionAtMillis, + actualContinuityExpiresAtMillis, + authenticatedReadbackSha256, + expected.lineageId()); + if (changed != 1) throw unavailable(); + Genesis stored = decode(requireByLeaseForUpdate(expected.leaseId())); + if (!Objects.equals(stored.confirmedAdmissionAtMillis(), actualAdmissionAtMillis) + || !Objects.equals( + stored.confirmedContinuityExpiresAtMillis(), actualContinuityExpiresAtMillis) + || !authenticatedReadbackSha256.equals(stored.confirmationReadbackSha256())) { + throw unavailable(); + } + return stored; + } + + /** Atomically consumes the Account-only handle once inside the already currentness-checked tx. */ + Genesis consumeOneUseHandle( + Genesis expected, + String presentedHandleSha256, + UUID consumptionRequestId, + long actualAdmissionAtMillis) { + requireWritableSerializableTransaction(); + Objects.requireNonNull(expected); + requireSha256(presentedHandleSha256); + requireUuidV4(consumptionRequestId); + if (actualAdmissionAtMillis <= 0L) throw unavailable(); + Genesis current = decode(requireByLeaseForUpdate(expected.leaseId())); + requireSameGenesis(expected, current); + if (current.status() != Status.COMMITTED + || current.confirmedAdmissionAtMillis() == null + || current.confirmedContinuityExpiresAtMillis() == null + || current.confirmationReadbackSha256() == null + || current.confirmedAdmissionAtMillis() != actualAdmissionAtMillis + || !presentedHandleSha256.equals(current.rebindHandleSha256())) throw unavailable(); + if (current.handleConsumedAtMillis() != null) { + if (!consumptionRequestId.equals(current.handleConsumptionRequestId()) + || current.handleConsumedAtMillis() >= current.confirmedContinuityExpiresAtMillis()) { + throw unavailable(); + } + return current; + } + int changed = + dsl.execute( + "UPDATE " + + TABLE + + " SET handle_consumed_at_ms = floor(extract(epoch FROM clock_timestamp()) * 1000)::bigint, " + + "handle_consumption_request_id = ? WHERE operation_id = ? AND status = 'COMMITTED' " + + "AND rebind_handle_sha256 = ? AND confirmed_admission_at_ms = ? " + + "AND confirmed_continuity_expires_at_ms > floor(extract(epoch FROM clock_timestamp()) * 1000) " + + "AND handle_consumed_at_ms IS NULL", + consumptionRequestId, + expected.lineageId(), + presentedHandleSha256, + actualAdmissionAtMillis); + if (changed != 1) throw unavailable(); + Genesis consumed = decode(requireByLeaseForUpdate(expected.leaseId())); + if (!consumptionRequestId.equals(consumed.handleConsumptionRequestId()) + || consumed.handleConsumedAtMillis() == null + || consumed.handleConsumedAtMillis() < actualAdmissionAtMillis + || consumed.handleConsumedAtMillis() >= consumed.confirmedContinuityExpiresAtMillis()) { + throw unavailable(); + } + return consumed; + } + + private Record requireByLeaseForUpdate(UUID leaseId) { + Record row = dsl.fetchOne("SELECT * FROM " + TABLE + " WHERE lease_id = ? FOR UPDATE", leaseId); + if (row == null) throw unavailable(); + return row; + } + + private static void requireOriginalAck( + AccountGameplayAdmissionLeaseEvidence lease, + AccountGameplayAdmissionOriginalAckReceipt receipt, + UUID requestId, + UUID accountId, + UUID leaseId, + long leaseFence) { + if (lease.leaseKind() != AccountGameplayAdmissionLeaseEvidence.LeaseKind.NEW_BINDING + || receipt.operation().state() != State.COMMITTED + || !requestId.equals(receipt.requestId()) + || !accountId.equals(receipt.accountId()) + || !leaseId.equals(receipt.leaseId()) + || leaseFence != receipt.leaseFence() + || !lease.sha256().equals(receipt.evidenceSha256()) + || !receipt.bindingDecisionId().equals(receipt.operation().bindingDecisionId()) + || !receipt.operation().evidence().hasSameIdentity(lease)) throw unavailable(); + } + + private static void requireSameFrozenSource( + Genesis genesis, + UUID requestId, + UUID accountId, + UUID leaseId, + long leaseFence, + UUID decisionId, + AccountGameplayAdmissionLeaseEvidence lease, + AccountGameplayAdmissionOriginalAckReceipt receipt, + String requestDigest, + String bindingScopeSha256, + byte[] scope, + byte[] tuple, + byte[] membershipBaseline, + byte[] membershipVersion, + byte[] checkpoints, + long issuanceFence) { + if (!genesis.requestId().equals(requestId) + || !genesis.accountId().equals(accountId) + || !genesis.leaseId().equals(leaseId) + || genesis.leaseFence() != leaseFence + || !genesis.bindingDecisionId().equals(decisionId) + || !genesis.bindingScopeSha256().equals(bindingScopeSha256) + || !genesis.originalLeaseEvidenceSha256().equals(lease.sha256()) + || !genesis.originalAckReceiptXid().equals(receipt.receiptXid()) + || !genesis.originalAckEvidenceSha256().equals(receipt.evidenceSha256()) + || !genesis.requestDigest().equals(requestDigest) + || !Arrays.equals(scope, genesis.bindingScopeCanonicalBytes()) + || !Arrays.equals(tuple, genesis.authorityTupleCanonicalBytes()) + || !Arrays.equals(membershipBaseline, genesis.membershipBaselineCanonicalBytes()) + || !Arrays.equals(membershipVersion, genesis.membershipVersionCanonicalBytes()) + || !Arrays.equals(checkpoints, genesis.outboxCheckpointsCanonicalBytes()) + || genesis.issuanceFence() != issuanceFence) throw unavailable(); + } + + private static void requireSameGenesis(Genesis expected, Genesis actual) { + if (!expected.lineageId().equals(actual.lineageId()) + || !expected.requestId().equals(actual.requestId()) + || !expected.accountId().equals(actual.accountId()) + || !expected.leaseId().equals(actual.leaseId()) + || expected.leaseFence() != actual.leaseFence() + || !expected.bindingDecisionId().equals(actual.bindingDecisionId()) + || !expected.requestDigest().equals(actual.requestDigest()) + || !expected.tokenJti().equals(actual.tokenJti()) + || expected.issuanceFence() != actual.issuanceFence()) throw unavailable(); + } + + private static Genesis decode(Record row) { + try { + return new Genesis( + row.get("operation_id", UUID.class), + row.get("request_id", UUID.class), + row.get("account_uuid", UUID.class), + row.get("caller_workload", String.class), + row.get("request_digest", String.class), + row.get("lease_id", UUID.class), + row.get("lease_fence", Long.class), + row.get("binding_decision_id", UUID.class), + row.get("binding_scope_sha256", String.class), + row.get("original_lease_evidence_sha256", String.class), + row.get("original_ack_receipt_xid", String.class), + row.get("original_ack_evidence_sha256", String.class), + row.get("binding_scope_canonical_bytes", byte[].class), + row.get("authority_tuple_canonical_bytes", byte[].class), + row.get("membership_baseline_canonical_bytes", byte[].class), + row.get("membership_version_canonical_bytes", byte[].class), + row.get("outbox_checkpoints_canonical_bytes", byte[].class), + row.get("issuance_fence", Long.class), + row.get("token_jti", UUID.class), + row.get("token_generation", Long.class), + row.get("issued_at_epoch_second", Long.class), + row.get("not_before_epoch_second", Long.class), + row.get("expires_at_epoch_second", Long.class), + Status.valueOf(row.get("status", String.class)), + row.get("token_hash", String.class), + row.get("signer_kid", String.class), + row.get("signer_generation", String.class), + row.get("pending_registry_record_bytes", byte[].class), + row.get("rebind_handle_sha256", String.class), + row.get("encrypted_result_envelope_sha256", String.class), + row.get("encrypted_result_envelope_bytes", byte[].class), + row.get("committed_registry_receipt_sha256", String.class), + row.get("confirmed_admission_at_ms", Long.class), + row.get("confirmed_continuity_expires_at_ms", Long.class), + row.get("confirmation_readback_sha256", String.class), + row.get("handle_consumed_at_ms", Long.class), + row.get("handle_consumption_request_id", UUID.class)); + } catch (RuntimeException malformed) { + throw unavailable(); + } + } + + private static byte[] canonicalBytes(Object value) { + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } catch (Exception malformed) { + throw unavailable(); + } + } + + private static String requestDigest( + AccountGameplayAdmissionLeaseEvidence lease, + AccountGameplayAdmissionOriginalAckReceipt receipt, + byte[] scope, + byte[] tuple, + byte[] membershipBaseline, + byte[] membershipVersion, + byte[] checkpoints) { + Map fields = new LinkedHashMap<>(); + fields.put("domain", "account-original-new-bound-gameplay/v1"); + fields.put("requestId", receipt.requestId().toString()); + fields.put("leaseId", receipt.leaseId().toString()); + fields.put("leaseFence", Long.toString(receipt.leaseFence())); + fields.put("bindingDecisionId", receipt.bindingDecisionId().toString()); + fields.put("leaseEvidenceSha256", lease.sha256()); + fields.put("ackReceiptXid", receipt.receiptXid()); + fields.put("ackEvidenceSha256", receipt.evidenceSha256()); + fields.put("bindingScope", decodeUtf8(scope)); + fields.put("authorityTuple", decodeUtf8(tuple)); + fields.put("membershipBaseline", decodeUtf8(membershipBaseline)); + fields.put("membershipVersion", decodeUtf8(membershipVersion)); + fields.put("outboxCheckpoints", decodeUtf8(checkpoints)); + try { + return sha256(Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(fields))); + } catch (Exception malformed) { + throw unavailable(); + } + } + + private static String decodeUtf8(byte[] value) { + return new String(value, StandardCharsets.UTF_8); + } + + private static String sha256(byte[] value) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value)); + } catch (NoSuchAlgorithmException impossible) { + throw unavailable(); + } + } + + private static void requireSha256(String value) { + if (value == null || !value.matches("[0-9a-f]{64}")) throw unavailable(); + } + + private static void requirePositiveDecimal(String value) { + if (value == null || !value.matches("[1-9][0-9]{0,18}")) throw unavailable(); + } + + private static void requireBytes(byte[] value, int maximum) { + if (value == null || value.length == 0 || value.length > maximum) throw unavailable(); + } + + private static void requireUuidV4(UUID value) { + if (value == null || value.version() != 4 || value.variant() != 2) throw unavailable(); + } + + private static UUID uuid(Object value) { + if (!(value instanceof String text)) throw unavailable(); + try { + UUID parsed = UUID.fromString(text); + if (!parsed.toString().equals(text) || parsed.version() != 4 || parsed.variant() != 2) { + throw unavailable(); + } + return parsed; + } catch (IllegalArgumentException malformed) { + throw unavailable(); + } + } + + private static long positiveLong(Object value) { + if (!(value instanceof String text) || !text.matches("[1-9][0-9]{0,18}")) throw unavailable(); + try { + return Long.parseLong(text); + } catch (NumberFormatException malformed) { + throw unavailable(); + } + } + + private static Map object(Object value) { + if (!(value instanceof Map map)) throw unavailable(); + return map; + } + + private static void wipe(byte[] bytes) { + if (bytes != null) Arrays.fill(bytes, (byte) 0); + } + + private static void requireWritableSerializableTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || !Integer.valueOf(java.sql.Connection.TRANSACTION_SERIALIZABLE) + .equals(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel())) { + throw unavailable(); + } + } + + private static void requireReadableTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive()) throw unavailable(); + } + + private static IllegalStateException unavailable() { + return new IllegalStateException("Original-new bound gameplay issuance is unavailable"); + } + + public enum Status { + PENDING, + COMMITTED + } + + /** + * Frozen non-secret token identity and protected result source; arrays are defensively copied. + */ + public static final class Genesis { + private final UUID lineageId; + private final UUID requestId; + private final UUID accountId; + private final String callerWorkload; + private final String requestDigest; + private final UUID leaseId; + private final long leaseFence; + private final UUID bindingDecisionId; + private final String bindingScopeSha256; + private final String originalLeaseEvidenceSha256; + private final String originalAckReceiptXid; + private final String originalAckEvidenceSha256; + private final byte[] bindingScopeCanonicalBytes; + private final byte[] authorityTupleCanonicalBytes; + private final byte[] membershipBaselineCanonicalBytes; + private final byte[] membershipVersionCanonicalBytes; + private final byte[] outboxCheckpointsCanonicalBytes; + private final long issuanceFence; + private final UUID tokenJti; + private final long tokenGeneration; + private final long issuedAtEpochSecond; + private final long notBeforeEpochSecond; + private final long expiresAtEpochSecond; + private final Status status; + private final String tokenHash; + private final String signerKid; + private final String signerGeneration; + private final byte[] pendingRegistryRecordBytes; + private final String rebindHandleSha256; + private final String encryptedResultEnvelopeSha256; + private final byte[] encryptedResultEnvelopeBytes; + private final String committedRegistryReceiptSha256; + private final Long confirmedAdmissionAtMillis; + private final Long confirmedContinuityExpiresAtMillis; + private final String confirmationReadbackSha256; + private final Long handleConsumedAtMillis; + private final UUID handleConsumptionRequestId; + + private Genesis( + UUID lineageId, + UUID requestId, + UUID accountId, + String callerWorkload, + String requestDigest, + UUID leaseId, + long leaseFence, + UUID bindingDecisionId, + String bindingScopeSha256, + String originalLeaseEvidenceSha256, + String originalAckReceiptXid, + String originalAckEvidenceSha256, + byte[] bindingScopeCanonicalBytes, + byte[] authorityTupleCanonicalBytes, + byte[] membershipBaselineCanonicalBytes, + byte[] membershipVersionCanonicalBytes, + byte[] outboxCheckpointsCanonicalBytes, + long issuanceFence, + UUID tokenJti, + long tokenGeneration, + long issuedAtEpochSecond, + long notBeforeEpochSecond, + long expiresAtEpochSecond, + Status status, + String tokenHash, + String signerKid, + String signerGeneration, + byte[] pendingRegistryRecordBytes, + String rebindHandleSha256, + String encryptedResultEnvelopeSha256, + byte[] encryptedResultEnvelopeBytes, + String committedRegistryReceiptSha256, + Long confirmedAdmissionAtMillis, + Long confirmedContinuityExpiresAtMillis, + String confirmationReadbackSha256, + Long handleConsumedAtMillis, + UUID handleConsumptionRequestId) { + this.lineageId = Objects.requireNonNull(lineageId); + this.requestId = Objects.requireNonNull(requestId); + this.accountId = Objects.requireNonNull(accountId); + this.callerWorkload = Objects.requireNonNull(callerWorkload); + this.requestDigest = Objects.requireNonNull(requestDigest); + this.leaseId = Objects.requireNonNull(leaseId); + this.leaseFence = leaseFence; + this.bindingDecisionId = Objects.requireNonNull(bindingDecisionId); + this.bindingScopeSha256 = Objects.requireNonNull(bindingScopeSha256); + this.originalLeaseEvidenceSha256 = Objects.requireNonNull(originalLeaseEvidenceSha256); + this.originalAckReceiptXid = Objects.requireNonNull(originalAckReceiptXid); + this.originalAckEvidenceSha256 = Objects.requireNonNull(originalAckEvidenceSha256); + this.bindingScopeCanonicalBytes = copy(bindingScopeCanonicalBytes); + this.authorityTupleCanonicalBytes = copy(authorityTupleCanonicalBytes); + this.membershipBaselineCanonicalBytes = copy(membershipBaselineCanonicalBytes); + this.membershipVersionCanonicalBytes = copy(membershipVersionCanonicalBytes); + this.outboxCheckpointsCanonicalBytes = copy(outboxCheckpointsCanonicalBytes); + this.issuanceFence = issuanceFence; + this.tokenJti = Objects.requireNonNull(tokenJti); + this.tokenGeneration = tokenGeneration; + this.issuedAtEpochSecond = issuedAtEpochSecond; + this.notBeforeEpochSecond = notBeforeEpochSecond; + this.expiresAtEpochSecond = expiresAtEpochSecond; + this.status = Objects.requireNonNull(status); + this.tokenHash = tokenHash; + this.signerKid = signerKid; + this.signerGeneration = signerGeneration; + this.pendingRegistryRecordBytes = copy(pendingRegistryRecordBytes); + this.rebindHandleSha256 = rebindHandleSha256; + this.encryptedResultEnvelopeSha256 = encryptedResultEnvelopeSha256; + this.encryptedResultEnvelopeBytes = copy(encryptedResultEnvelopeBytes); + this.committedRegistryReceiptSha256 = committedRegistryReceiptSha256; + this.confirmedAdmissionAtMillis = confirmedAdmissionAtMillis; + this.confirmedContinuityExpiresAtMillis = confirmedContinuityExpiresAtMillis; + this.confirmationReadbackSha256 = confirmationReadbackSha256; + this.handleConsumedAtMillis = handleConsumedAtMillis; + this.handleConsumptionRequestId = handleConsumptionRequestId; + if ((confirmedAdmissionAtMillis == null) != (confirmedContinuityExpiresAtMillis == null) + || (confirmedAdmissionAtMillis == null) != (confirmationReadbackSha256 == null) + || (handleConsumedAtMillis == null) != (handleConsumptionRequestId == null) + || (confirmedAdmissionAtMillis != null + && (confirmedAdmissionAtMillis <= 0L + || confirmedContinuityExpiresAtMillis <= confirmedAdmissionAtMillis + || !confirmationReadbackSha256.matches("[0-9a-f]{64}") + || status != Status.COMMITTED)) + || (handleConsumedAtMillis != null + && (handleConsumedAtMillis <= 0L + || confirmedContinuityExpiresAtMillis == null + || handleConsumedAtMillis >= confirmedContinuityExpiresAtMillis + || status != Status.COMMITTED))) { + throw unavailable(); + } + if (leaseFence <= 0L + || issuanceFence <= 0L + || tokenGeneration != 1L + || issuedAtEpochSecond <= 0L + || notBeforeEpochSecond <= 0L + || notBeforeEpochSecond > issuedAtEpochSecond + || expiresAtEpochSecond <= issuedAtEpochSecond) { + throw unavailable(); + } + } + + private static byte[] copy(byte[] value) { + return value == null ? null : value.clone(); + } + + public UUID lineageId() { + return lineageId; + } + + public UUID requestId() { + return requestId; + } + + public UUID accountId() { + return accountId; + } + + public String callerWorkload() { + return callerWorkload; + } + + public String requestDigest() { + return requestDigest; + } + + public UUID leaseId() { + return leaseId; + } + + public long leaseFence() { + return leaseFence; + } + + public UUID bindingDecisionId() { + return bindingDecisionId; + } + + public String bindingScopeSha256() { + return bindingScopeSha256; + } + + public String originalLeaseEvidenceSha256() { + return originalLeaseEvidenceSha256; + } + + public String originalAckReceiptXid() { + return originalAckReceiptXid; + } + + public String originalAckEvidenceSha256() { + return originalAckEvidenceSha256; + } + + public byte[] bindingScopeCanonicalBytes() { + return bindingScopeCanonicalBytes.clone(); + } + + public byte[] authorityTupleCanonicalBytes() { + return authorityTupleCanonicalBytes.clone(); + } + + public byte[] membershipBaselineCanonicalBytes() { + return membershipBaselineCanonicalBytes.clone(); + } + + public byte[] membershipVersionCanonicalBytes() { + return membershipVersionCanonicalBytes.clone(); + } + + public byte[] outboxCheckpointsCanonicalBytes() { + return outboxCheckpointsCanonicalBytes.clone(); + } + + public long issuanceFence() { + return issuanceFence; + } + + public UUID tokenJti() { + return tokenJti; + } + + public long tokenGeneration() { + return tokenGeneration; + } + + public long issuedAtEpochSecond() { + return issuedAtEpochSecond; + } + + public long notBeforeEpochSecond() { + return notBeforeEpochSecond; + } + + public long expiresAtEpochSecond() { + return expiresAtEpochSecond; + } + + public Status status() { + return status; + } + + public String tokenHash() { + return tokenHash; + } + + public String signerKid() { + return signerKid; + } + + public String signerGeneration() { + return signerGeneration; + } + + public byte[] pendingRegistryRecordBytes() { + return copy(pendingRegistryRecordBytes); + } + + public String rebindHandleSha256() { + return rebindHandleSha256; + } + + public String encryptedResultEnvelopeSha256() { + return encryptedResultEnvelopeSha256; + } + + public byte[] encryptedResultEnvelopeBytes() { + return copy(encryptedResultEnvelopeBytes); + } + + public String committedRegistryReceiptSha256() { + return committedRegistryReceiptSha256; + } + + public Long confirmedAdmissionAtMillis() { + return confirmedAdmissionAtMillis; + } + + public Long confirmedContinuityExpiresAtMillis() { + return confirmedContinuityExpiresAtMillis; + } + + public String confirmationReadbackSha256() { + return confirmationReadbackSha256; + } + + public Long handleConsumedAtMillis() { + return handleConsumedAtMillis; + } + + public UUID handleConsumptionRequestId() { + return handleConsumptionRequestId; + } + + @Override + public String toString() { + return "OriginalNewBoundGameplayGenesis[status=" + status + ",credential=redacted]"; + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayAdmissionLeaseGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayAdmissionLeaseGrpcService.java index 7ea03fe510..2b9222cb02 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayAdmissionLeaseGrpcService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayAdmissionLeaseGrpcService.java @@ -11,28 +11,41 @@ import net.firedevops.firemud.account.v1.AccountGameplayAdmissionLeaseResponse; import net.firedevops.firemud.account.v1.AccountGameplayAdmissionLeaseServiceGrpc; import net.firedevops.firemud.account.v1.AcquireGameplayAdmissionLeaseRequest; +import net.firedevops.firemud.account.v1.ConfirmOriginalNewGameplayAdmissionRequest; import net.firedevops.firemud.account.v1.FinalizeGameplayAdmissionLeaseRequest; +import net.firedevops.firemud.account.v1.IssueOriginalNewGameplayCredentialRequest; +import net.firedevops.firemud.account.v1.OriginalNewAdmissionConfirmationResponse; import net.firedevops.firemud.account.v1.ReadGameplayAdmissionLeaseRequest; import net.firedevops.firemud.accountservice.repository.AccountGameplayAdmissionLeaseOwner; +import net.firedevops.firemud.accountservice.repository.AccountOriginalNewBoundGameplayCredentialOwner; import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseGrpcCodec; import org.jooq.exception.DataAccessException; import org.springframework.dao.DataAccessResourceFailureException; import org.springframework.transaction.CannotCreateTransactionException; import org.springframework.transaction.support.TransactionSynchronizationManager; -/** Standalone, unregistered receiver for Account's four NEW lease operations. */ +/** Standalone, unregistered receiver for Account's NEW lease and ORIGINAL-NEW credential calls. */ public final class AccountGameplayAdmissionLeaseGrpcService extends AccountGameplayAdmissionLeaseServiceGrpc.AccountGameplayAdmissionLeaseServiceImplBase { private static final String FAILURE_DESCRIPTION = "Account gameplay admission lease operation denied or unavailable"; private final AccountGameplayAdmissionLeaseOwner owner; + private final AccountOriginalNewBoundGameplayCredentialOwner originalNewCredentialOwner; private final AccountGameplayAdmissionLeaseWorkloadGuard workloadGuard; AccountGameplayAdmissionLeaseGrpcService( AccountGameplayAdmissionLeaseOwner owner, AccountGameplayAdmissionLeaseWorkloadGuard workloadGuard) { + this(owner, null, workloadGuard); + } + + AccountGameplayAdmissionLeaseGrpcService( + AccountGameplayAdmissionLeaseOwner owner, + AccountOriginalNewBoundGameplayCredentialOwner originalNewCredentialOwner, + AccountGameplayAdmissionLeaseWorkloadGuard workloadGuard) { this.owner = Objects.requireNonNull(owner, "Account gameplay admission lease owner required"); + this.originalNewCredentialOwner = originalNewCredentialOwner; this.workloadGuard = Objects.requireNonNull(workloadGuard, "Account gameplay admission lease guard required"); } @@ -97,6 +110,103 @@ public void abortGameplayAdmissionLease( }); } + @Override + public void issueOriginalNewGameplayCredential( + IssueOriginalNewGameplayCredentialRequest request, + StreamObserver observer) { + receive( + request, + observer, + AccountGameplayAdmissionLeaseGrpcCodec.MAX_ORIGINAL_LEASE_REQUEST_WIRE_BYTES, + () -> { + var parsed = + AccountGameplayAdmissionLeaseGrpcCodec.parseIssueOriginalNewCredentialRequest( + request); + workloadGuard.requireOriginalNewCredentialNamespace(parsed); + if (originalNewCredentialOwner == null) { + throw Status.UNAVAILABLE + .withDescription("Account original-new credential owner is unavailable") + .asRuntimeException(); + } + return () -> originalNewCredentialOwner.issue(parsed); + }); + } + + @Override + public void confirmOriginalNewGameplayAdmission( + ConfirmOriginalNewGameplayAdmissionRequest request, + StreamObserver observer) { + Objects.requireNonNull(observer, "response observer is required"); + try { + workloadGuard.requireGameSessionCaller(); + } catch (StatusRuntimeException denied) { + fail(observer, denied.getStatus()); + return; + } + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + fail(observer, Status.FAILED_PRECONDITION); + return; + } + if (request == null + || request.getSerializedSize() + > AccountGameplayAdmissionLeaseGrpcCodec.MAX_ORIGINAL_LEASE_REQUEST_WIRE_BYTES) { + fail(observer, Status.INVALID_ARGUMENT); + return; + } + final AccountGameplayAdmissionLeaseGrpcCodec.OriginalFinalAdmissionConfirmationRequest parsed; + try { + parsed = + AccountGameplayAdmissionLeaseGrpcCodec.parseConfirmOriginalNewGameplayAdmissionRequest( + request); + workloadGuard.requireOriginalFinalAdmissionConfirmationNamespace(parsed); + if (originalNewCredentialOwner == null) throw new IllegalStateException(); + } catch (StatusRuntimeException rejected) { + fail(observer, rejected.getStatus()); + return; + } catch (IllegalArgumentException malformed) { + fail(observer, Status.INVALID_ARGUMENT); + return; + } catch (RuntimeException unavailable) { + fail(observer, Status.UNAVAILABLE); + return; + } + + final AccountOriginalNewBoundGameplayCredentialOwner.OriginalAdmissionConfirmation confirmed; + try { + confirmed = + originalNewCredentialOwner.confirmOriginalFinalAdmission( + parsed.presentedInitialGsACompactJwt(), parsed.originalLeaseEvidence()); + } catch (StatusRuntimeException failure) { + fail(observer, failure.getStatus()); + return; + } catch (IllegalArgumentException malformed) { + fail(observer, Status.FAILED_PRECONDITION); + return; + } catch (RuntimeException unavailable) { + fail(observer, Status.UNAVAILABLE); + return; + } + + final OriginalNewAdmissionConfirmationResponse response; + try { + response = + AccountGameplayAdmissionLeaseGrpcCodec.toConfirmOriginalNewGameplayAdmissionResponse( + parsed, + confirmed.lineageId(), + confirmed.originalLeaseId(), + parsed.originalLeaseEvidence().leaseFence().longValueExact(), + confirmed.admissionAtMillis(), + confirmed.continuityExpiresAtMillis(), + confirmed.authenticatedConfirmationSha256()); + } catch (RuntimeException invalidOwnerResult) { + fail(observer, Status.INTERNAL); + return; + } + observer.onNext(response); + observer.onCompleted(); + } + private void receive( T request, StreamObserver observer, diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayAdmissionLeaseManualFactory.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayAdmissionLeaseManualFactory.java index 8eb97c6693..569e529bc6 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayAdmissionLeaseManualFactory.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayAdmissionLeaseManualFactory.java @@ -8,6 +8,7 @@ import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.TrustManagerFactory; import net.firedevops.firemud.accountservice.repository.AccountGameplayAdmissionLeaseOwner; +import net.firedevops.firemud.accountservice.repository.AccountOriginalNewBoundGameplayCredentialOwner; import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseGrpcCodec; import net.firedevops.firemud.common.grpc.BoundedGrpcServerFactory; import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; @@ -24,6 +25,18 @@ public static AccountGameplayAdmissionLeaseGrpcService createUnregisteredReceive new AccountGameplayAdmissionLeaseWorkloadGuard(workloadNamespace)); } + /** Explicit receiver composition that enables only the exact post-COMMITTED credential method. */ + public static AccountGameplayAdmissionLeaseGrpcService createUnregisteredReceiver( + AccountGameplayAdmissionLeaseOwner owner, + AccountOriginalNewBoundGameplayCredentialOwner originalNewCredentialOwner, + String workloadNamespace) { + return new AccountGameplayAdmissionLeaseGrpcService( + Objects.requireNonNull(owner, "Account gameplay admission lease owner required"), + Objects.requireNonNull( + originalNewCredentialOwner, "Account original-new credential owner required"), + new AccountGameplayAdmissionLeaseWorkloadGuard(workloadNamespace)); + } + /** Creates an unstarted TLS server with a finite ceiling and no production registration. */ public static Server createUnregisteredServer( String address, @@ -54,4 +67,36 @@ public static Server createUnregisteredServer( new AccountGameplayAdmissionLeaseWorkloadGuard(workloadNamespace))); return factory.createServer(); } + + /** Creates an unstarted, method-guarded receiver with the ORIGINAL-NEW credential owner wired. */ + public static Server createUnregisteredServer( + String address, + KeyManagerFactory keys, + TrustManagerFactory trust, + AccountGameplayAdmissionLeaseOwner owner, + AccountOriginalNewBoundGameplayCredentialOwner originalNewCredentialOwner, + String workloadNamespace) { + Objects.requireNonNull(address, "gRPC server address required"); + Objects.requireNonNull(keys, "gRPC server key manager required"); + Objects.requireNonNull(trust, "gRPC server trust manager required"); + int transportMaximum = + Math.max( + AccountGameplayAdmissionLeaseGrpcCodec.MAX_ACQUIRE_REQUEST_WIRE_BYTES, + AccountGameplayAdmissionLeaseGrpcCodec.MAX_ORIGINAL_LEASE_REQUEST_WIRE_BYTES); + var factory = + new BoundedGrpcServerFactory( + address, + List.of(), + keys, + trust, + TlsServerCredentials.ClientAuth.REQUIRE, + GrpcRequestBytePolicy.ordinary(), + transportMaximum); + factory.addService( + ServerInterceptors.interceptForward( + createUnregisteredReceiver(owner, originalNewCredentialOwner, workloadNamespace), + new GrpcPeerIdentityInterceptor(), + new AccountGameplayAdmissionLeaseWorkloadGuard(workloadNamespace))); + return factory.createServer(); + } } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayAdmissionLeaseWorkloadGuard.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayAdmissionLeaseWorkloadGuard.java index 76aae99c5f..cd2d84a114 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayAdmissionLeaseWorkloadGuard.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayAdmissionLeaseWorkloadGuard.java @@ -78,6 +78,12 @@ private static boolean isLeaseMethod(MethodDescriptor method) { .getFullMethodName() .equals(fullMethodName) || AccountGameplayAdmissionLeaseServiceGrpc.getAbortGameplayAdmissionLeaseMethod() + .getFullMethodName() + .equals(fullMethodName) + || AccountGameplayAdmissionLeaseServiceGrpc.getIssueOriginalNewGameplayCredentialMethod() + .getFullMethodName() + .equals(fullMethodName) + || AccountGameplayAdmissionLeaseServiceGrpc.getConfirmOriginalNewGameplayAdmissionMethod() .getFullMethodName() .equals(fullMethodName); } @@ -111,6 +117,36 @@ public void requireOriginalLeaseNamespace( } } + public void requireOriginalNewCredentialNamespace( + AccountGameplayAdmissionLeaseGrpcCodec.OriginalNewCredentialRequest request) { + if (request == null) { + throw Status.INVALID_ARGUMENT + .withDescription("Malformed Account original-new credential request") + .asRuntimeException(); + } + Object targetNamespace = request.originalLeaseEvidence().carrier().get("targetNamespace"); + if (!namespace.equals(targetNamespace)) { + throw Status.PERMISSION_DENIED + .withDescription("Original-new credential lease target namespace is not authorized") + .asRuntimeException(); + } + } + + public void requireOriginalFinalAdmissionConfirmationNamespace( + AccountGameplayAdmissionLeaseGrpcCodec.OriginalFinalAdmissionConfirmationRequest request) { + if (request == null) { + throw Status.INVALID_ARGUMENT + .withDescription("Malformed Account original-new confirmation request") + .asRuntimeException(); + } + Object targetNamespace = request.originalLeaseEvidence().carrier().get("targetNamespace"); + if (!namespace.equals(targetNamespace)) { + throw Status.PERMISSION_DENIED + .withDescription("Original-new confirmation lease target namespace is not authorized") + .asRuntimeException(); + } + } + private static boolean hasSessionContext() { return SessionContext.hasAuthenticatedCallerContext() || SessionContext.isInternalService() diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisClient.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisClient.java index 108371f5e9..af2412f947 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisClient.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisClient.java @@ -28,6 +28,7 @@ import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository.CommittedCandidateVerificationData; import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository.PendingIntent; import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationPendingIdentity; +import net.firedevops.firemud.accountservice.repository.AccountOriginalNewBoundGameplayIssuanceRepository.Genesis; import net.firedevops.firemud.accountservice.service.AccountGenerationProjection; import net.firedevops.firemud.accountservice.service.AccountGenerationProjectionRedisContract; import net.firedevops.firemud.accountservice.service.session.AccountCoordinationPinnedConnectionProvider.AcknowledgementRequirements; @@ -1108,6 +1109,161 @@ private RedisScriptDescriptor requirePendingDescriptor() { return descriptor; } + /** + * Applies the original-new pending-to-active CAS after Account obtains an authenticated ORIGINAL + * final-admission readback. Exact retries retain the same record and expiry. + */ + public OriginalNewActivationReadback activateOriginalNewCommittedPending( + Genesis committedOriginalNew, long absoluteExpiryMillis) { + Objects.requireNonNull(committedOriginalNew, "Committed ORIGINAL-NEW Account row required"); + if (TransactionSynchronizationManager.isActualTransactionActive() + || committedOriginalNew.status() + != net.firedevops.firemud.accountservice.repository + .AccountOriginalNewBoundGameplayIssuanceRepository.Status.COMMITTED + || committedOriginalNew.committedRegistryReceiptSha256() == null + || absoluteExpiryMillis <= 0L) throw unavailable(); + byte[] exactPendingBytes = null; + byte[] activeBytes = null; + byte[] scriptSource = null; + byte[] key = null; + byte[] deadline = null; + byte[] currentBytes = null; + byte[] activeReadback = null; + StatefulRedisConnection connection = null; + + try { + exactPendingBytes = committedOriginalNew.pendingRegistryRecordBytes(); + GameSessionAccountDelegationRegistryRecord pendingRecord = + GameSessionAccountDelegationRegistryRecord.decode(exactPendingBytes, maxRecordBytes); + requireOriginalNewPendingMatches(committedOriginalNew, pendingRecord, exactPendingBytes); + activeBytes = activeRecordBytes(pendingRecord); + String tokenHash = committedOriginalNew.tokenHash(); + if (tokenHash == null) throw unavailable(); + RedisScriptDescriptor descriptor = requireActiveTransitionDescriptor(); + scriptSource = readScriptSource(descriptor); + if (!descriptor.sha256().equals(sha256(scriptSource))) throw unavailable(); + key = ascii(TOKEN_KEY_PREFIX + tokenHash); + deadline = Long.toString(absoluteExpiryMillis).getBytes(StandardCharsets.US_ASCII); + connection = connectionProvider.openPinnedConnection(); + if (connection == null) throw unavailable(); + RedisCommands commands = requirePinnedCommands(connection); + requireAccountAclIdentity(commands); + String loadedSha = commands.scriptLoad(scriptSource); + if (loadedSha == null + || !SHA1.matcher(loadedSha).matches() + || !sha1(scriptSource).equals(loadedSha)) throw unavailable(); + currentBytes = commands.get(key); + Long currentExpiry = commands.pexpiretime(key); + if (currentBytes == null || currentExpiry == null || currentExpiry != absoluteExpiryMillis) { + throw unavailable(); + } + GameSessionAccountDelegationRegistryRecord currentRecord = + GameSessionAccountDelegationRegistryRecord.decode(currentBytes, maxRecordBytes); + byte[] expectedCurrent; + if ("pending".equals(currentRecord.state()) && currentRecord.registryVersion() == 1L) { + expectedCurrent = exactPendingBytes; + } else if ("active".equals(currentRecord.state()) && currentRecord.registryVersion() == 2L) { + expectedCurrent = activeBytes; + } else { + throw unavailable(); + } + if (!Arrays.equals(expectedCurrent, currentBytes)) throw unavailable(); + Long transition = + commands.evalsha( + loadedSha, + ScriptOutputType.INTEGER, + new byte[][] {key}, + exactPendingBytes, + activeBytes, + deadline); + if (transition == null || (transition != 0L && transition != 1L)) throw unavailable(); + Acknowledgement acknowledgement = requireDurabilityAcknowledgement(commands); + activeReadback = commands.get(key); + Long activeExpiry = commands.pexpiretime(key); + if (!Arrays.equals(activeBytes, activeReadback) + || activeExpiry == null + || activeExpiry != absoluteExpiryMillis) throw unavailable(); + GameSessionAccountDelegationRegistryRecord active = + GameSessionAccountDelegationRegistryRecord.decode(activeReadback, maxRecordBytes); + if (!"active".equals(active.state()) + || active.registryVersion() != 2L + || !active.tokenHash().equals(tokenHash)) throw unavailable(); + return new OriginalNewActivationReadback( + tokenHash, + committedOriginalNew.accountId().toString(), + committedOriginalNew.lineageId().toString(), + committedOriginalNew.tokenJti().toString(), + sha256(activeReadback), + absoluteExpiryMillis, + acknowledgement.localAofCount(), + acknowledgement.replicaAofCount()); + } catch (RuntimeException failure) { + if (failure instanceof AccountCoordinationRedisException) throw failure; + throw unavailable(); + } finally { + wipe(exactPendingBytes); + wipe(activeBytes); + wipe(currentBytes); + wipe(activeReadback); + wipe(scriptSource); + wipe(key); + wipe(deadline); + if (connection != null) { + try { + connection.close(); + } catch (RuntimeException failure) { + throw unavailable(); + } + } + } + } + + /** Exact read-only ACTIVE check for a retained original-new lineage after confirmation. */ + public ActiveRegistryReadback requireExactOriginalNewActiveRecord( + Genesis committedOriginalNew, long absoluteExpiryMillis) { + Objects.requireNonNull(committedOriginalNew); + if (TransactionSynchronizationManager.isActualTransactionActive() + || committedOriginalNew.status() + != net.firedevops.firemud.accountservice.repository + .AccountOriginalNewBoundGameplayIssuanceRepository.Status.COMMITTED + || absoluteExpiryMillis <= 0L) throw unavailable(); + ActiveRegistryReadback active = readActiveRecord(committedOriginalNew.tokenHash()); + byte[] pendingRecordBytes = committedOriginalNew.pendingRegistryRecordBytes(); + try { + if (!active.tokenHash().equals(committedOriginalNew.tokenHash()) + || !active.accountId().equals(committedOriginalNew.accountId().toString()) + || !active.jti().equals(committedOriginalNew.tokenJti().toString()) + || active.tokenExpiryEpochSecond() != committedOriginalNew.expiresAtEpochSecond() + || active.absoluteExpiryMillis() != absoluteExpiryMillis + || !active.canonicalPendingRecordSha256().equals(sha256(pendingRecordBytes))) { + throw unavailable(); + } + return active; + } finally { + wipe(pendingRecordBytes); + } + } + + private void requireOriginalNewPendingMatches( + Genesis genesis, GameSessionAccountDelegationRegistryRecord record, byte[] recordBytes) { + if (!"pending".equals(record.state()) + || record.registryVersion() != 1L + || !record.tokenHash().equals(genesis.tokenHash()) + || !record.kid().equals(genesis.signerKid()) + || !record.signerGeneration().equals(genesis.signerGeneration()) + || !record.operationId().equals(genesis.lineageId().toString()) + || !record.requestId().equals(genesis.requestId().toString()) + || !record.requestDigest().equals(genesis.requestDigest()) + || !record.accountId().equals(genesis.accountId().toString()) + || !record.jti().equals(genesis.tokenJti().toString()) + || record.issuedAtEpochSecond() != genesis.issuedAtEpochSecond() + || record.notBeforeEpochSecond() != genesis.notBeforeEpochSecond() + || record.expiresAtEpochSecond() != genesis.expiresAtEpochSecond() + || !Long.toString(genesis.tokenGeneration()).equals(record.fields().get("tokenGeneration")) + || record.issuanceFence() != genesis.issuanceFence() + || !Arrays.equals(recordBytes, genesis.pendingRegistryRecordBytes())) throw unavailable(); + } + private RedisScriptDescriptor requireActiveTransitionDescriptor() { RedisScriptDescriptor descriptor = scriptCatalog.require(ACTIVE_TRANSITION_SCRIPT_ID); if (!ACTIVE_TRANSITION_SCRIPT_ID.equals(descriptor.scriptId()) @@ -1271,6 +1427,10 @@ private static boolean canonicalMapEquals(Object value, Map expe } } + private static void wipe(byte[] value) { + if (value != null) Arrays.fill(value, (byte) 0); + } + private static byte[] canonicalJson(Object value) { try { return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); @@ -1669,6 +1829,86 @@ public enum ActiveRegistrationOutcome { EXACT_RETRY } + /** Redacted pinned-Redis/AOF result for one original-new active transition or exact retry. */ + public static final class OriginalNewActivationReadback { + private final String tokenHash; + private final String accountId; + private final String lineageId; + private final String tokenJti; + private final String activeRecordSha256; + private final long absoluteExpiryMillis; + private final long localAofCount; + private final long replicaAofCount; + + private OriginalNewActivationReadback( + String tokenHash, + String accountId, + String lineageId, + String tokenJti, + String activeRecordSha256, + long absoluteExpiryMillis, + long localAofCount, + long replicaAofCount) { + if (tokenHash == null + || !SHA256.matcher(tokenHash).matches() + || accountId == null + || lineageId == null + || tokenJti == null + || activeRecordSha256 == null + || !SHA256.matcher(activeRecordSha256).matches() + || absoluteExpiryMillis <= 0L + || localAofCount < 1L + || replicaAofCount < 1L) { + throw unavailable(); + } + this.tokenHash = tokenHash; + this.accountId = accountId; + this.lineageId = lineageId; + this.tokenJti = tokenJti; + this.activeRecordSha256 = activeRecordSha256; + this.absoluteExpiryMillis = absoluteExpiryMillis; + this.localAofCount = localAofCount; + this.replicaAofCount = replicaAofCount; + } + + public String tokenHash() { + return tokenHash; + } + + public String accountId() { + return accountId; + } + + public String lineageId() { + return lineageId; + } + + public String tokenJti() { + return tokenJti; + } + + public String activeRecordSha256() { + return activeRecordSha256; + } + + public long absoluteExpiryMillis() { + return absoluteExpiryMillis; + } + + public long localAofCount() { + return localAofCount; + } + + public long replicaAofCount() { + return replicaAofCount; + } + + @Override + public String toString() { + return "OriginalNewActivationReadback[redacted]"; + } + } + /** * Private-constructor metadata for an exact ACTIVE registry readback. This value is not a token * credential and is not proof of player admission, response recovery, or current signer state diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationSigner.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationSigner.java index 9cb048ccf9..1150798d8f 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationSigner.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationSigner.java @@ -26,6 +26,7 @@ import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.CommittedSignerEvidence; import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.CustodyMode; import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.TrustFence; +import net.firedevops.firemud.accountservice.repository.AccountOriginalNewBoundGameplayIssuanceRepository.Genesis; import net.firedevops.firemud.common.security.AccountAsymmetricJwtVerifier; import net.firedevops.firemud.common.security.AccountAsymmetricJwtVerifier.ExplicitRouteProfilePolicy; import net.firedevops.firemud.common.security.AccountAsymmetricJwtVerifier.VerifiedClaims; @@ -315,6 +316,235 @@ CandidateOutcome signPendingCandidate(UUID requestId) { } } + /** + * Signs and locally verifies the distinct tenant-bound ORIGINAL-NEW credential for one frozen + * Account lineage. It reuses the current Account signer/trust/JWKS sources, but does not enter or + * alter the unscoped LOGIN issuance row or its token-identity invariant. + */ + public OriginalNewBoundSignedCandidate signOriginalNewBoundCandidate( + Genesis genesis, + AccountAuthoritySnapshot accountAuthority, + String tenantId, + Map exactAuthorityTuple, + Map exactMembershipVersion) { + Objects.requireNonNull(genesis); + Objects.requireNonNull(accountAuthority); + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) throw unavailable(); + byte[] firstJwksBytes = null; + byte[] finalJwksBytes = null; + AtomicReference compactTokenCapture = new AtomicReference<>(); + byte[] transientCompactJwt = null; + try { + CurrentSigner initial = accountTransaction.execute(status -> currentCommittedSigner()); + if (initial == null || !accountAuthority.accountId().equals(genesis.accountId())) { + throw unavailable(); + } + SourceIdentity sourcePin = trustedJwksSource.sourceIdentity(); + firstJwksBytes = requireExactTrustedSnapshot(initial, sourcePin, trustedJwksSource.load()); + byte[] pinnedJwks = firstJwksBytes; + AccountPublicJwksCache keyCache = + new AccountPublicJwksCache( + () -> { + PublicJwksSnapshot observed = trustedJwksSource.load(); + byte[] observedBytes = requireExactTrustedSnapshot(initial, sourcePin, observed); + try { + if (!Arrays.equals(pinnedJwks, observedBytes)) { + throw new AccountPublicJwksCache.InvalidJwksException(); + } + return observed; + } finally { + wipe(observedBytes); + } + }, + sourcePin, + clock, + PUBLIC_KEY_CACHE_AGE); + keyCache.keyFor(initial.expectedIdentity().kid()); + + var bound = + new AccountMountedJwtSignerBundle.BoundDelegationClaims( + tenantId, exactAuthorityTuple, exactMembershipVersion); + var signingSpec = + new AccountMountedJwtSignerBundle.OriginalNewBoundDelegationSigningSpec( + genesis.lineageId(), + genesis.requestId(), + genesis.accountId(), + genesis.tokenJti(), + genesis.issuedAtEpochSecond(), + genesis.notBeforeEpochSecond(), + genesis.expiresAtEpochSecond(), + genesis.issuanceFence(), + accountAuthority, + bound); + AccountMountedJwtSignerBundle.SignedDelegationDigest digest = + AccountMountedJwtSignerBundle.signOriginalNewBoundGameplayDelegationDigest( + privateMountRoot, + privateBundlePath, + publicMountRoot, + publicJwksPath, + initial.expectedIdentity(), + signingSpec, + (signed, exactCompactJwt) -> { + if (!genesis.lineageId().equals(signed.issuanceOperationId()) + || !genesis.requestId().equals(signed.requestId()) + || !genesis.tokenJti().equals(signed.jti()) + || !initial.expectedIdentity().operationId().equals(signed.signerOperationId()) + || !initial.expectedIdentity().generation().equals(signed.signerGeneration()) + || !initial.expectedIdentity().kid().equals(signed.kid()) + || !initial + .expectedIdentity() + .publicKeyFingerprint() + .equals(signed.publicKeyFingerprint()) + || signed.issuedAtEpochSecond() != genesis.issuedAtEpochSecond() + || signed.notBeforeEpochSecond() != genesis.notBeforeEpochSecond() + || signed.expiresAtEpochSecond() != genesis.expiresAtEpochSecond() + || !genesis.requestDigest().matches("[0-9a-f]{64}")) { + throw unavailable(); + } + byte[] copy = exactCompactJwt.clone(); + if (!compactTokenCapture.compareAndSet(null, copy)) { + wipe(copy); + throw unavailable(); + } + }); + transientCompactJwt = compactTokenCapture.getAndSet(null); + if (transientCompactJwt == null + || !sha256(transientCompactJwt).equals(digest.compactTokenSha256())) throw unavailable(); + String compact = exactAscii(transientCompactJwt); + VerifiedClaims verified = + new AccountAsymmetricJwtVerifier(keyCache, clock).verify(compact, GSA_SIGNING_POLICY); + Map claims = verified.claims(); + if (!GameSessionAccountDelegationProfile.PROFILE.equals(verified.profile()) + || !GameSessionAccountDelegationProfile.TYPE.equals(verified.tokenType()) + || !initial.expectedIdentity().kid().equals(verified.keyId()) + || !genesis.accountId().toString().equals(claims.get("sub")) + || !genesis.accountId().toString().equals(claims.get("accountId")) + || !genesis.tokenJti().toString().equals(claims.get("jti")) + || !tenantId.equals(claims.get("tenantId")) + || decimalCounterClaim(claims, "tokenGeneration") != 1L + || numberClaim(claims, "iat") != genesis.issuedAtEpochSecond() + || numberClaim(claims, "nbf") != genesis.notBeforeEpochSecond() + || numberClaim(claims, "exp") != genesis.expiresAtEpochSecond() + || decimalCounterClaim(claims, "issuanceFence") != genesis.issuanceFence() + || !exactAuthorityTuple.equals(claims.get("authorityTuple")) + || !exactMembershipVersion.equals(claims.get("membershipVersion")) + || claims.containsKey("globalRoles") + || claims.containsKey("scopedRoles") + || !sha256(transientCompactJwt).equals(digest.compactTokenSha256())) { + throw unavailable(); + } + finalJwksBytes = requireExactTrustedSnapshot(initial, sourcePin, trustedJwksSource.load()); + if (!Arrays.equals(firstJwksBytes, finalJwksBytes)) throw unavailable(); + CurrentSigner observed = accountTransaction.execute(status -> currentCommittedSigner()); + if (observed == null) throw unavailable(); + requireSameCommittedSigner(initial, observed); + return new OriginalNewBoundSignedCandidate( + transientCompactJwt, + digest.compactTokenSha256(), + digest.kid(), + digest.signerGeneration(), + digest.publicKeyFingerprint()); + } catch (RuntimeException failure) { + throw unavailable(); + } finally { + wipe(firstJwksBytes); + wipe(finalJwksBytes); + wipe(compactTokenCapture.getAndSet(null)); + wipe(transientCompactJwt); + } + } + + /** Verifies one exact Account-owned ORIGINAL-NEW JWT under the current mounted signer/JWKS. */ + public VerifiedOriginalNewBoundCredential verifyOriginalNewBoundCredential( + String compactJwt, + Genesis genesis, + AccountAuthoritySnapshot accountAuthority, + String tenantId, + Map exactAuthorityTuple, + Map exactMembershipVersion) { + Objects.requireNonNull(compactJwt); + Objects.requireNonNull(genesis); + Objects.requireNonNull(accountAuthority); + Objects.requireNonNull(exactAuthorityTuple); + Objects.requireNonNull(exactMembershipVersion); + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) throw unavailable(); + byte[] jwtBytes = null; + byte[] initialJwks = null; + byte[] finalJwks = null; + try { + CurrentSigner initial = accountTransaction.execute(status -> currentCommittedSigner()); + if (initial == null + || !genesis.accountId().equals(accountAuthority.accountId()) + || !genesis.signerKid().equals(initial.expectedIdentity().kid()) + || !genesis.signerGeneration().equals(initial.expectedIdentity().generation())) + throw unavailable(); + SourceIdentity pin = trustedJwksSource.sourceIdentity(); + initialJwks = requireExactTrustedSnapshot(initial, pin, trustedJwksSource.load()); + byte[] pinned = initialJwks; + AccountPublicJwksCache keyCache = + new AccountPublicJwksCache( + () -> { + PublicJwksSnapshot observed = trustedJwksSource.load(); + byte[] observedBytes = requireExactTrustedSnapshot(initial, pin, observed); + try { + if (!Arrays.equals(pinned, observedBytes)) { + throw new AccountPublicJwksCache.InvalidJwksException(); + } + return observed; + } finally { + wipe(observedBytes); + } + }, + pin, + clock, + PUBLIC_KEY_CACHE_AGE); + keyCache.keyFor(genesis.signerKid()); + VerifiedClaims verified = + new AccountAsymmetricJwtVerifier(keyCache, clock).verify(compactJwt, GSA_SIGNING_POLICY); + Map claims = verified.claims(); + jwtBytes = compactJwt.getBytes(StandardCharsets.US_ASCII); + if (!exactAscii(jwtBytes).equals(compactJwt) + || jwtBytes.length > GameSessionAccountDelegationProfile.MAX_COMPACT_JWT_BYTES + || !sha256(jwtBytes).equals(genesis.tokenHash()) + || !GameSessionAccountDelegationProfile.PROFILE.equals(verified.profile()) + || !GameSessionAccountDelegationProfile.TYPE.equals(verified.tokenType()) + || !genesis.signerKid().equals(verified.keyId()) + || !genesis.accountId().toString().equals(claims.get("sub")) + || !genesis.accountId().toString().equals(claims.get("accountId")) + || !genesis.tokenJti().toString().equals(claims.get("jti")) + || !tenantId.equals(claims.get("tenantId")) + || decimalCounterClaim(claims, "tokenGeneration") != 1L + || numberClaim(claims, "iat") != genesis.issuedAtEpochSecond() + || numberClaim(claims, "nbf") != genesis.notBeforeEpochSecond() + || numberClaim(claims, "exp") != genesis.expiresAtEpochSecond() + || decimalCounterClaim(claims, "issuanceFence") != genesis.issuanceFence() + || !exactAuthorityTuple.equals(claims.get("authorityTuple")) + || !exactMembershipVersion.equals(claims.get("membershipVersion")) + || claims.containsKey("globalRoles") + || claims.containsKey("scopedRoles")) throw unavailable(); + finalJwks = requireExactTrustedSnapshot(initial, pin, trustedJwksSource.load()); + if (!Arrays.equals(initialJwks, finalJwks)) throw unavailable(); + CurrentSigner observed = accountTransaction.execute(status -> currentCommittedSigner()); + if (observed == null) throw unavailable(); + requireSameCommittedSigner(initial, observed); + return new VerifiedOriginalNewBoundCredential( + genesis.lineageId(), + genesis.accountId(), + genesis.tokenJti(), + genesis.tokenHash(), + genesis.issuanceFence(), + genesis.expiresAtEpochSecond()); + } catch (RuntimeException failure) { + throw unavailable(); + } finally { + wipe(jwtBytes); + wipe(initialJwks); + wipe(finalJwks); + } + } + /** * Revalidates signer-owned candidate evidence inside the caller's writable Account transaction. * This method performs no signing, external JWKS/API request, mutation, or authorization effect. @@ -1553,4 +1783,82 @@ private SigningUnavailableException() { super("Account gameplay delegation candidate is unavailable or ambiguous"); } } + + /** Signature/profile verification result with no compact JWT or handle bytes. */ + public record VerifiedOriginalNewBoundCredential( + UUID lineageId, + UUID accountId, + UUID tokenJti, + String tokenSha256, + long issuanceFence, + long expiresAtEpochSecond) { + public VerifiedOriginalNewBoundCredential { + Objects.requireNonNull(lineageId); + Objects.requireNonNull(accountId); + Objects.requireNonNull(tokenJti); + if (tokenSha256 == null + || !tokenSha256.matches("[0-9a-f]{64}") + || issuanceFence <= 0L + || expiresAtEpochSecond <= 0L) throw unavailable(); + } + + @Override + public String toString() { + return "VerifiedOriginalNewBoundCredential[redacted]"; + } + } + + /** Transient signed bytes owned by this Account signer invocation; diagnostics redact them. */ + public static final class OriginalNewBoundSignedCandidate implements AutoCloseable { + private byte[] compactJwtBytes; + private final String tokenHash; + private final String signerKid; + private final String signerGeneration; + private final String publicKeyFingerprint; + + private OriginalNewBoundSignedCandidate( + byte[] compactJwtBytes, + String tokenHash, + String signerKid, + String signerGeneration, + String publicKeyFingerprint) { + this.compactJwtBytes = compactJwtBytes.clone(); + this.tokenHash = Objects.requireNonNull(tokenHash); + this.signerKid = Objects.requireNonNull(signerKid); + this.signerGeneration = Objects.requireNonNull(signerGeneration); + this.publicKeyFingerprint = Objects.requireNonNull(publicKeyFingerprint); + } + + public byte[] compactJwtBytes() { + if (compactJwtBytes == null) throw unavailable(); + return compactJwtBytes.clone(); + } + + public String tokenHash() { + return tokenHash; + } + + public String signerKid() { + return signerKid; + } + + public String signerGeneration() { + return signerGeneration; + } + + public String publicKeyFingerprint() { + return publicKeyFingerprint; + } + + @Override + public void close() { + wipe(compactJwtBytes); + compactJwtBytes = null; + } + + @Override + public String toString() { + return "OriginalNewBoundSignedCandidate[credential=redacted]"; + } + } } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationTokenRegistry.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationTokenRegistry.java index 29e1c6acc7..d5bd93a51d 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationTokenRegistry.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationTokenRegistry.java @@ -1,12 +1,14 @@ package net.firedevops.firemud.accountservice.service.session; import java.time.Clock; +import java.util.Arrays; import java.util.Map; import java.util.Objects; import java.util.UUID; import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository; import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository.CommittedCandidateVerificationData; import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository.PendingRegistryCandidate; +import net.firedevops.firemud.accountservice.repository.AccountOriginalNewBoundGameplayIssuanceRepository.Genesis; import net.firedevops.firemud.common.security.AccountJwtExactValues; import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; import net.firedevops.firemud.common.security.GameSessionAccountDelegationRegistryRecord; @@ -133,6 +135,123 @@ public AccountGameplayDelegationRedisClient.PendingRegistrationReceipt registerP return receipt; } + /** + * Registers the exact immutable Account-owned ORIGINAL-NEW pending projection. Its lineage row + * was already committed with the signed token hash and record bytes; this method only repeats + * that record under the same fixed expiry and requires the real pinned-Redis WAITAOF receipt. + */ + public AccountGameplayDelegationRedisClient.PendingRegistrationReceipt registerOriginalNewPending( + Genesis genesis) { + Objects.requireNonNull(genesis, "Account-owned ORIGINAL-NEW genesis is required"); + requireNoAccountTransaction( + "ORIGINAL-NEW pending registry work must not join an Account transaction"); + byte[] recordBytes = genesis.pendingRegistryRecordBytes(); + if (recordBytes == null || recordBytes.length == 0 || recordBytes.length > maxEncodedBytes) { + throw new IllegalStateException("Durable ORIGINAL-NEW registry record is unavailable"); + } + try { + GameSessionAccountDelegationRegistryRecord record = + GameSessionAccountDelegationRegistryRecord.decode(recordBytes, maxEncodedBytes); + if (!"pending".equals(record.state()) + || record.registryVersion() != 1L + || !genesis.tokenHash().equals(record.tokenHash()) + || !genesis.signerKid().equals(record.kid()) + || !genesis.signerGeneration().equals(record.signerGeneration()) + || !genesis.lineageId().toString().equals(record.operationId()) + || !genesis.requestId().toString().equals(record.requestId()) + || !genesis.requestDigest().equals(record.requestDigest()) + || !genesis.accountId().toString().equals(record.accountId()) + || !genesis.tokenJti().toString().equals(record.jti()) + || genesis.issuedAtEpochSecond() != record.issuedAtEpochSecond() + || genesis.notBeforeEpochSecond() != record.notBeforeEpochSecond() + || genesis.expiresAtEpochSecond() != record.expiresAtEpochSecond() + || !Long.toString(genesis.tokenGeneration()) + .equals(record.fields().get("tokenGeneration")) + || genesis.issuanceFence() != record.issuanceFence()) { + throw new IllegalStateException( + "Persisted ORIGINAL-NEW registry record differs from the frozen lineage"); + } + + long nowMillis = clock.millis(); + if (nowMillis <= 0L) throw new IllegalStateException("Clock returned an invalid instant"); + long absoluteExpiryMillis; + try { + absoluteExpiryMillis = Math.multiplyExact(genesis.expiresAtEpochSecond(), 1_000L); + absoluteExpiryMillis = Math.addExact(absoluteExpiryMillis, cleanupMarginMillis); + if (absoluteExpiryMillis <= nowMillis) { + throw new IllegalStateException("Original-new registry deadline has elapsed"); + } + } catch (ArithmeticException malformed) { + throw new IllegalStateException("Original-new registry deadline is unavailable"); + } + + AccountGameplayDelegationRedisClient.PendingRegistrationReceipt receipt = + coordinationRedis.registerPending(genesis.tokenHash(), recordBytes, absoluteExpiryMillis); + if (receipt == null + || !receipt + .tokenKey() + .equals(AccountGameplayDelegationRedisClient.TOKEN_KEY_PREFIX + genesis.tokenHash()) + || !AccountGameplayDelegationRedisClient.REQUIRED_ACL_IDENTITY.equals( + receipt.aclIdentity()) + || !receipt.canonicalRecordSha256().equals(sha256(recordBytes)) + || !receipt.operationId().equals(genesis.lineageId().toString()) + || !receipt.requestId().equals(genesis.requestId().toString()) + || !receipt.requestDigest().equals(genesis.requestDigest()) + || !receipt.accountId().equals(genesis.accountId().toString()) + || !receipt.tokenJti().equals(genesis.tokenJti().toString()) + || !receipt.tokenHash().equals(genesis.tokenHash()) + || !receipt.kid().equals(genesis.signerKid()) + || !receipt.signerGeneration().equals(genesis.signerGeneration()) + || receipt.issuedAtEpochSecond() != genesis.issuedAtEpochSecond() + || receipt.notBeforeEpochSecond() != genesis.notBeforeEpochSecond() + || receipt.expiresAtEpochSecond() != genesis.expiresAtEpochSecond() + || receipt.issuanceFence() != genesis.issuanceFence() + || receipt.registryVersion() != 1L + || receipt.absoluteExpiryMillis() != absoluteExpiryMillis + || receipt.localAofCount() < 1L + || receipt.replicaAofCount() < 1L) { + throw new IllegalStateException("ORIGINAL-NEW pending registry receipt is inconsistent"); + } + return receipt; + } finally { + Arrays.fill(recordBytes, (byte) 0); + } + } + + /** + * Activates one exact committed ORIGINAL-NEW projection after Account's authenticated GS read. + */ + public AccountGameplayDelegationRedisClient.OriginalNewActivationReadback + activateOriginalNewCommittedPending(Genesis genesis) { + Objects.requireNonNull(genesis, "Committed Account ORIGINAL-NEW source required"); + requireNoAccountTransaction("ORIGINAL-NEW activation must not hold Account SQL locks"); + long absoluteExpiryMillis = originalNewAbsoluteExpiry(genesis); + long nowMillis = clock.millis(); + if (nowMillis <= 0L || absoluteExpiryMillis <= nowMillis) throw unavailable(); + return coordinationRedis.activateOriginalNewCommittedPending(genesis, absoluteExpiryMillis); + } + + /** Requires the exact already-active ORIGINAL-NEW projection and its original absolute expiry. */ + public AccountGameplayDelegationRedisClient.ActiveRegistryReadback + requireExactOriginalNewActiveRecord(Genesis genesis) { + Objects.requireNonNull(genesis, "Committed Account ORIGINAL-NEW source required"); + requireNoAccountTransaction("ORIGINAL-NEW registry reads must not hold Account SQL locks"); + if (clock.millis() <= 0L) throw unavailable(); + return coordinationRedis.requireExactOriginalNewActiveRecord( + genesis, originalNewAbsoluteExpiry(genesis)); + } + + private long originalNewAbsoluteExpiry(Genesis genesis) { + try { + long tokenExpiryMillis = Math.multiplyExact(genesis.expiresAtEpochSecond(), 1_000L); + long absoluteExpiryMillis = Math.addExact(tokenExpiryMillis, cleanupMarginMillis); + if (absoluteExpiryMillis <= 0L) throw unavailable(); + return absoluteExpiryMillis; + } catch (ArithmeticException malformed) { + throw unavailable(); + } + } + /** * Requires the exact ACTIVE Redis projection for an already-current COMMITTED Account owner read. * This read grants no authority by itself and performs no registry activation. @@ -263,4 +382,8 @@ private static String sha256(byte[] value) { throw new IllegalStateException("SHA-256 is unavailable"); } } + + private static IllegalStateException unavailable() { + return new IllegalStateException("Original-new Account token registry is unavailable"); + } } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountMountedJwtSignerBundle.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountMountedJwtSignerBundle.java index a46894c1a8..8eeb666209 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountMountedJwtSignerBundle.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountMountedJwtSignerBundle.java @@ -348,6 +348,121 @@ static SignedDelegationDigest signCommittedGameplayDelegationDigest( } } + /** + * Signs the purpose-bound tenant credential for one Account-owned ORIGINAL-NEW lineage. The + * supplied operation identity is the lineage identity; the new row has generation 1 and a + * distinct JTI. It is separate from the immutable unscoped LOGIN claim shape. + */ + static SignedDelegationDigest signOriginalNewBoundGameplayDelegationDigest( + Path privateMountRoot, + Path privateBundlePath, + Path publicMountRoot, + Path publicJwksPath, + ExpectedIdentity expectedIdentity, + OriginalNewBoundDelegationSigningSpec spec, + DelegationCandidateConsumer candidateConsumer) { + Objects.requireNonNull(spec, "Original-new bound signing specification is required"); + Objects.requireNonNull(candidateConsumer, "Gameplay delegation owner callback is required"); + VerifiedMountedSigner mounted = + readAndVerifyMounted( + privateMountRoot, privateBundlePath, publicMountRoot, publicJwksPath, expectedIdentity); + if (!mounted.observation().expectedIdentity().equals(expectedIdentity) + || !spec.accountAuthority().accountId().equals(spec.accountId()) + || spec.accountAuthority().issuanceFence() != spec.issuanceFence() + || spec.operationId().equals(spec.tokenJti())) { + throw invalid(); + } + + byte[] header = null; + byte[] claims = null; + byte[] encodedHeader = null; + byte[] encodedClaims = null; + byte[] signingInput = null; + byte[] signatureBytes = null; + byte[] encodedSignature = null; + byte[] compactBytes = null; + byte[] tokenDigest = null; + byte[] callbackBytes = null; + try { + Map headerFields = new LinkedHashMap<>(); + headerFields.put("alg", ALGORITHM); + headerFields.put("kid", expectedIdentity.kid()); + headerFields.put("typ", "JWT"); + header = canonicalJsonBytes(headerFields); + Map delegation = new LinkedHashMap<>(); + delegation.put("iss", GameSessionAccountDelegationProfile.ISSUER); + delegation.put("sub", spec.accountId().toString()); + delegation.put("jti", spec.tokenJti().toString()); + delegation.put("accountId", spec.accountId().toString()); + delegation.put("aud", GameSessionAccountDelegationProfile.AUDIENCE); + delegation.put("iat", spec.issuedAtEpochSecond()); + delegation.put("nbf", spec.notBeforeEpochSecond()); + delegation.put("exp", spec.expiresAtEpochSecond()); + delegation.put("tokenGeneration", "1"); + delegation.put( + "authorityTuple", mergeBoundAuthorityTuple(spec.accountAuthority(), spec.bound())); + delegation.put("membershipVersion", spec.bound().membershipVersion()); + delegation.put("issuanceFence", Long.toString(spec.issuanceFence())); + delegation.put("tenantId", spec.bound().tenantId()); + net.firedevops.firemud.common.security.GameSessionAccountDelegationJwtProfileValidator + .validateClaims(delegation); + claims = canonicalJsonBytes(delegation); + encodedHeader = Base64.getUrlEncoder().withoutPadding().encode(header); + encodedClaims = Base64.getUrlEncoder().withoutPadding().encode(claims); + signingInput = joinCompactParts(encodedHeader, encodedClaims, null); + + Signature signer = Signature.getInstance("SHA256withRSA"); + signer.initSign(mounted.privateKey()); + signer.update(signingInput); + signatureBytes = signer.sign(); + + Signature verifier = Signature.getInstance("SHA256withRSA"); + verifier.initVerify(mounted.publicKey()); + verifier.update(signingInput); + if (!verifier.verify(signatureBytes)) throw invalid(); + encodedSignature = Base64.getUrlEncoder().withoutPadding().encode(signatureBytes); + compactBytes = joinCompactParts(encodedHeader, encodedClaims, encodedSignature); + if (compactBytes.length > MAX_DELEGATION_COMPACT_JWT_BYTES) throw invalid(); + tokenDigest = MessageDigest.getInstance("SHA-256").digest(compactBytes); + SignedDelegationDigest digest = + new SignedDelegationDigest( + spec.operationId(), + spec.requestId(), + spec.tokenJti(), + expectedIdentity.operationId(), + expectedIdentity.generation(), + expectedIdentity.kid(), + expectedIdentity.publicKeyFingerprint(), + spec.issuedAtEpochSecond(), + spec.notBeforeEpochSecond(), + spec.expiresAtEpochSecond(), + java.util.HexFormat.of().formatHex(tokenDigest)); + callbackBytes = compactBytes.clone(); + try { + candidateConsumer.bindExactCandidate(digest, callbackBytes); + } catch (RuntimeException failure) { + throw invalid(); + } + if (!sha256(callbackBytes).equals(digest.compactTokenSha256())) throw invalid(); + return digest; + } catch (InvalidMountedSignerBundleException ex) { + throw ex; + } catch (Exception ex) { + throw invalid(); + } finally { + wipe(header); + wipe(claims); + wipe(encodedHeader); + wipe(encodedClaims); + wipe(signingInput); + wipe(signatureBytes); + wipe(encodedSignature); + wipe(compactBytes); + wipe(tokenDigest); + wipe(callbackBytes); + } + } + /** * Distinct control-ui entry, available only to the Account owner. The owner must have retained * genuine primary authentication and exact committed signer evidence before calling outside SQL @@ -1142,6 +1257,45 @@ record BoundDelegationClaims( } } + record OriginalNewBoundDelegationSigningSpec( + UUID operationId, + UUID requestId, + UUID accountId, + UUID tokenJti, + long issuedAtEpochSecond, + long notBeforeEpochSecond, + long expiresAtEpochSecond, + long issuanceFence, + AccountAuthoritySnapshot accountAuthority, + BoundDelegationClaims bound) { + OriginalNewBoundDelegationSigningSpec { + Objects.requireNonNull(operationId); + Objects.requireNonNull(requestId); + Objects.requireNonNull(accountId); + Objects.requireNonNull(tokenJti); + Objects.requireNonNull(accountAuthority); + Objects.requireNonNull(bound); + if (operationId.version() != 4 + || requestId.version() != 4 + || tokenJti.version() != 4 + || operationId.variant() != 2 + || requestId.variant() != 2 + || tokenJti.variant() != 2 + || operationId.equals(tokenJti) + || !accountAuthority.accountId().equals(accountId) + || issuedAtEpochSecond <= 0L + || notBeforeEpochSecond <= 0L + || notBeforeEpochSecond > issuedAtEpochSecond + || expiresAtEpochSecond <= issuedAtEpochSecond + || expiresAtEpochSecond - issuedAtEpochSecond + > GameSessionAccountDelegationProfile.MAX_TOKEN_LIFETIME_SECONDS + || issuanceFence <= 0L + || accountAuthority.issuanceFence() != issuanceFence) { + throw invalid(); + } + } + } + @FunctionalInterface interface DelegationCandidateConsumer { /** The caller persists the exact candidate before any internal transient handoff. */ diff --git a/services/account-service/src/main/resources/db/migration/V161__account_original_new_bound_gameplay_credentials.sql b/services/account-service/src/main/resources/db/migration/V161__account_original_new_bound_gameplay_credentials.sql new file mode 100644 index 0000000000..92acbbd693 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V161__account_original_new_bound_gameplay_credentials.sql @@ -0,0 +1,370 @@ +-- Purpose-bound ORIGINAL-NEW Account delegation lineage and protected rebind handle. +-- The existing LOGIN issuance rows, their unscoped claim invariant, and their retained bytes are +-- not rewritten. This row family has one fresh generation-1 lineage per exact original NEW lease. +CREATE TABLE account_original_new_bound_gameplay_issuances ( + operation_id UUID PRIMARY KEY, + request_id UUID NOT NULL UNIQUE, + account_uuid UUID NOT NULL REFERENCES accounts (account_uuid) ON DELETE RESTRICT, + caller_workload VARCHAR(256) NOT NULL, + request_digest VARCHAR(64) NOT NULL, + lease_id UUID NOT NULL UNIQUE, + lease_fence BIGINT NOT NULL, + binding_decision_id UUID NOT NULL UNIQUE, + binding_scope_sha256 VARCHAR(64) NOT NULL UNIQUE, + original_lease_evidence_sha256 VARCHAR(64) NOT NULL, + original_ack_receipt_xid VARCHAR(32) NOT NULL, + original_ack_evidence_sha256 VARCHAR(64) NOT NULL, + binding_scope_canonical_bytes BYTEA NOT NULL, + authority_tuple_canonical_bytes BYTEA NOT NULL, + membership_baseline_canonical_bytes BYTEA NOT NULL, + membership_version_canonical_bytes BYTEA NOT NULL, + outbox_checkpoints_canonical_bytes BYTEA NOT NULL, + issuance_fence BIGINT NOT NULL, + token_jti UUID NOT NULL UNIQUE, + token_generation BIGINT NOT NULL DEFAULT 1, + issued_at_epoch_second BIGINT NOT NULL, + not_before_epoch_second BIGINT NOT NULL, + expires_at_epoch_second BIGINT NOT NULL, + status VARCHAR(16) NOT NULL DEFAULT 'PENDING', + token_hash VARCHAR(64), + signer_kid VARCHAR(64), + signer_generation VARCHAR(19), + pending_registry_record_bytes BYTEA, + rebind_handle_sha256 VARCHAR(64) UNIQUE, + encrypted_result_envelope_sha256 VARCHAR(64), + encrypted_result_envelope_bytes BYTEA, + committed_registry_receipt_sha256 VARCHAR(64), + confirmed_admission_at_ms BIGINT, + confirmed_continuity_expires_at_ms BIGINT, + confirmation_readback_sha256 VARCHAR(64), + handle_consumed_at_ms BIGINT, + handle_consumption_request_id UUID, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + committed_at TIMESTAMPTZ, + CONSTRAINT account_original_new_bound_identity_check CHECK ( + operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + 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 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 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 lease_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 binding_decision_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}$' + AND operation_id <> token_jti), + CONSTRAINT account_original_new_bound_caller_check CHECK ( + caller_workload ~ '^spiffe://firemud/ns/[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?/sa/game-session-service$' + AND request_digest ~ '^[0-9a-f]{64}$'), + CONSTRAINT account_original_new_bound_fence_check CHECK ( + lease_fence > 0 AND issuance_fence > 0 AND token_generation = 1), + CONSTRAINT account_original_new_bound_source_check CHECK ( + binding_scope_sha256 ~ '^[0-9a-f]{64}$' + AND binding_scope_sha256 = encode(sha256(binding_scope_canonical_bytes), 'hex') + AND + original_lease_evidence_sha256 ~ '^[0-9a-f]{64}$' + AND original_ack_evidence_sha256 ~ '^[0-9a-f]{64}$' + AND original_ack_receipt_xid ~ '^[1-9][0-9]{0,19}$' + AND octet_length(binding_scope_canonical_bytes) BETWEEN 1 AND 4096 + AND jsonb_typeof(convert_from(binding_scope_canonical_bytes, 'UTF8')::jsonb) = 'object' + AND octet_length(authority_tuple_canonical_bytes) BETWEEN 1 AND 4096 + AND jsonb_typeof(convert_from(authority_tuple_canonical_bytes, 'UTF8')::jsonb) = 'object' + AND octet_length(membership_baseline_canonical_bytes) BETWEEN 1 AND 4096 + AND jsonb_typeof(convert_from(membership_baseline_canonical_bytes, 'UTF8')::jsonb) = 'object' + AND octet_length(membership_version_canonical_bytes) BETWEEN 1 AND 4096 + AND jsonb_typeof(convert_from(membership_version_canonical_bytes, 'UTF8')::jsonb) = 'object' + AND convert_from(membership_version_canonical_bytes, 'UTF8') <> '{}' + AND octet_length(outbox_checkpoints_canonical_bytes) BETWEEN 1 AND 8192 + AND jsonb_typeof(convert_from(outbox_checkpoints_canonical_bytes, 'UTF8')::jsonb) = 'array'), + CONSTRAINT account_original_new_bound_time_check CHECK ( + issued_at_epoch_second > 0 AND not_before_epoch_second > 0 + AND not_before_epoch_second <= issued_at_epoch_second + AND expires_at_epoch_second > issued_at_epoch_second + AND expires_at_epoch_second - issued_at_epoch_second <= 300), + CONSTRAINT account_original_new_bound_state_check CHECK (status IN ('PENDING', 'COMMITTED')), + CONSTRAINT account_original_new_bound_candidate_check CHECK ( + (token_hash IS NULL AND signer_kid IS NULL AND signer_generation IS NULL + AND pending_registry_record_bytes IS NULL AND rebind_handle_sha256 IS NULL + AND encrypted_result_envelope_sha256 IS NULL AND encrypted_result_envelope_bytes IS NULL + AND committed_registry_receipt_sha256 IS NULL AND committed_at IS NULL) + OR (token_hash IS NOT NULL AND token_hash ~ '^[0-9a-f]{64}$' + AND signer_kid IS NOT NULL AND signer_kid ~ '^[A-Za-z0-9_-]{1,64}$' + AND signer_generation IS NOT NULL AND signer_generation ~ '^[1-9][0-9]{0,18}$' + AND pending_registry_record_bytes IS NOT NULL + AND octet_length(pending_registry_record_bytes) BETWEEN 1 AND 16384 + AND rebind_handle_sha256 IS NOT NULL AND rebind_handle_sha256 ~ '^[0-9a-f]{64}$' + AND encrypted_result_envelope_sha256 IS NOT NULL + AND encrypted_result_envelope_sha256 ~ '^[0-9a-f]{64}$' + AND encrypted_result_envelope_bytes IS NOT NULL + AND octet_length(encrypted_result_envelope_bytes) BETWEEN 1 AND 65610 + AND ((status = 'PENDING' AND committed_registry_receipt_sha256 IS NULL AND committed_at IS NULL) + OR (status = 'COMMITTED' AND committed_registry_receipt_sha256 IS NOT NULL + AND committed_registry_receipt_sha256 ~ '^[0-9a-f]{64}$' + AND committed_at IS NOT NULL)))), + CONSTRAINT account_original_new_bound_confirmation_check CHECK ( + (confirmed_admission_at_ms IS NULL AND confirmed_continuity_expires_at_ms IS NULL + AND confirmation_readback_sha256 IS NULL) + OR (confirmed_admission_at_ms IS NOT NULL AND confirmed_admission_at_ms > 0 + AND status = 'COMMITTED' AND token_hash IS NOT NULL + AND confirmed_continuity_expires_at_ms IS NOT NULL + AND confirmed_continuity_expires_at_ms > confirmed_admission_at_ms + AND confirmation_readback_sha256 IS NOT NULL + AND confirmation_readback_sha256 ~ '^[0-9a-f]{64}$')), + CONSTRAINT account_original_new_bound_consumption_check CHECK ( + (handle_consumed_at_ms IS NULL AND handle_consumption_request_id IS NULL) + OR (handle_consumed_at_ms IS NOT NULL AND handle_consumed_at_ms > 0 + AND status = 'COMMITTED' AND confirmed_admission_at_ms IS NOT NULL + AND handle_consumed_at_ms >= confirmed_admission_at_ms + AND confirmed_continuity_expires_at_ms IS NOT NULL + AND handle_consumed_at_ms < confirmed_continuity_expires_at_ms + AND handle_consumption_request_id IS NOT NULL + AND handle_consumption_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}$')) +); + +-- A row is admitted only when the exact original lease and its independently committed ACK receipt +-- already exist. Their source bytes remain untouched and are compared by digest here and in Java. +-- [jooq ignore start] +CREATE FUNCTION account_original_new_bound_gameplay_issuance_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + original RECORD; + receipt RECORD; +BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'Original-new gameplay issuance evidence cannot be deleted' USING ERRCODE = '23514'; + END IF; + PERFORM account_uuid FROM accounts WHERE account_uuid = NEW.account_uuid FOR UPDATE; + IF NOT FOUND THEN + RAISE EXCEPTION 'Original-new Account source is absent' USING ERRCODE = '23514'; + END IF; + SELECT request_id, account_uuid, lease_id, lease_fence, binding_decision_id, + evidence_sha256, evidence_json, expires_at_ms, status + INTO original FROM account_gameplay_admission_lease_operations + WHERE request_id = NEW.request_id AND lease_id = NEW.lease_id FOR SHARE; + SELECT request_id, account_uuid, lease_id, lease_fence, binding_decision_id, + evidence_sha256, receipt_xid + INTO receipt FROM account_gameplay_admission_original_commit_ack_receipts + WHERE request_id = NEW.request_id FOR SHARE; + IF original.request_id IS NULL OR original.status <> 'COMMITTED' + OR original.account_uuid <> NEW.account_uuid OR original.lease_id <> NEW.lease_id + OR original.lease_fence <> NEW.lease_fence + OR original.binding_decision_id <> NEW.binding_decision_id + OR original.evidence_sha256 <> NEW.original_lease_evidence_sha256 + OR original.evidence_json::jsonb -> 'bindingScope' + IS DISTINCT FROM convert_from(NEW.binding_scope_canonical_bytes, 'UTF8')::jsonb + OR original.evidence_json::jsonb -> 'authorityTuple' + IS DISTINCT FROM convert_from(NEW.authority_tuple_canonical_bytes, 'UTF8')::jsonb + OR original.evidence_json::jsonb -> 'membershipBaseline' + IS DISTINCT FROM convert_from(NEW.membership_baseline_canonical_bytes, 'UTF8')::jsonb + OR original.evidence_json::jsonb -> 'membershipBaseline' -> 'membershipVersion' + IS DISTINCT FROM convert_from(NEW.membership_version_canonical_bytes, 'UTF8')::jsonb + OR original.evidence_json::jsonb -> 'outboxCheckpoints' + IS DISTINCT FROM convert_from(NEW.outbox_checkpoints_canonical_bytes, 'UTF8')::jsonb + OR original.evidence_json::jsonb ->> 'issuanceFence' IS DISTINCT FROM NEW.issuance_fence::text + OR receipt.request_id IS NULL OR receipt.account_uuid <> NEW.account_uuid + OR receipt.lease_id <> NEW.lease_id OR receipt.lease_fence <> NEW.lease_fence + OR receipt.binding_decision_id <> NEW.binding_decision_id + OR receipt.evidence_sha256 <> NEW.original_ack_evidence_sha256 + OR receipt.receipt_xid <> NEW.original_ack_receipt_xid THEN + RAISE EXCEPTION 'Original-new credential requires the exact committed lease and ACK' + USING ERRCODE = '23514', CONSTRAINT = 'account_original_new_bound_original_commit_required'; + END IF; + IF TG_OP = 'INSERT' THEN + IF NEW.status <> 'PENDING' OR NEW.token_hash IS NOT NULL + OR NEW.signer_kid IS NOT NULL OR NEW.signer_generation IS NOT NULL + OR NEW.pending_registry_record_bytes IS NOT NULL OR NEW.rebind_handle_sha256 IS NOT NULL + OR NEW.encrypted_result_envelope_sha256 IS NOT NULL + OR NEW.encrypted_result_envelope_bytes IS NOT NULL + OR NEW.committed_registry_receipt_sha256 IS NOT NULL OR NEW.committed_at IS NOT NULL + OR NEW.confirmed_admission_at_ms IS NOT NULL + OR NEW.confirmed_continuity_expires_at_ms IS NOT NULL + OR NEW.confirmation_readback_sha256 IS NOT NULL + OR NEW.handle_consumed_at_ms IS NOT NULL + OR NEW.handle_consumption_request_id IS NOT NULL THEN + RAISE EXCEPTION 'Original-new lineage must start as unbound PENDING' + USING ERRCODE = '23514', CONSTRAINT = 'account_original_new_bound_initial_pending_only'; + END IF; + RETURN NEW; + END IF; + IF ROW(NEW.operation_id, NEW.request_id, NEW.account_uuid, NEW.caller_workload, + NEW.request_digest, NEW.lease_id, NEW.lease_fence, NEW.binding_decision_id, + NEW.binding_scope_sha256, + NEW.original_lease_evidence_sha256, NEW.original_ack_receipt_xid, + NEW.original_ack_evidence_sha256, NEW.binding_scope_canonical_bytes, + NEW.authority_tuple_canonical_bytes, NEW.membership_baseline_canonical_bytes, + NEW.membership_version_canonical_bytes, + NEW.outbox_checkpoints_canonical_bytes, NEW.issuance_fence, NEW.token_jti, + NEW.token_generation, NEW.issued_at_epoch_second, NEW.not_before_epoch_second, + NEW.expires_at_epoch_second, NEW.created_at) + IS DISTINCT FROM ROW(OLD.operation_id, OLD.request_id, OLD.account_uuid, OLD.caller_workload, + OLD.request_digest, OLD.lease_id, OLD.lease_fence, OLD.binding_decision_id, + OLD.binding_scope_sha256, + OLD.original_lease_evidence_sha256, OLD.original_ack_receipt_xid, + OLD.original_ack_evidence_sha256, OLD.binding_scope_canonical_bytes, + OLD.authority_tuple_canonical_bytes, OLD.membership_baseline_canonical_bytes, + OLD.membership_version_canonical_bytes, + OLD.outbox_checkpoints_canonical_bytes, OLD.issuance_fence, OLD.token_jti, + OLD.token_generation, OLD.issued_at_epoch_second, OLD.not_before_epoch_second, + OLD.expires_at_epoch_second, OLD.created_at) THEN + RAISE EXCEPTION 'Original-new lineage identity and frozen claims are immutable' + USING ERRCODE = '23514', CONSTRAINT = 'account_original_new_bound_identity_immutable'; + END IF; + IF OLD.token_hash IS NULL THEN + IF NEW.token_hash IS NULL OR NEW.signer_kid IS NULL OR NEW.signer_generation IS NULL + OR NEW.pending_registry_record_bytes IS NULL OR NEW.rebind_handle_sha256 IS NULL + OR NEW.encrypted_result_envelope_sha256 IS NULL + OR NEW.encrypted_result_envelope_bytes IS NULL + OR NEW.status <> 'PENDING' OR NEW.committed_registry_receipt_sha256 IS NOT NULL + OR NEW.committed_at IS NOT NULL THEN + RAISE EXCEPTION 'Original-new signed identity must bind once before commit' + USING ERRCODE = '23514', CONSTRAINT = 'account_original_new_bound_candidate_one_way'; + END IF; + ELSIF ROW(NEW.token_hash, NEW.signer_kid, NEW.signer_generation, + NEW.pending_registry_record_bytes, NEW.rebind_handle_sha256, + NEW.encrypted_result_envelope_sha256, NEW.encrypted_result_envelope_bytes) + IS DISTINCT FROM ROW(OLD.token_hash, OLD.signer_kid, OLD.signer_generation, + OLD.pending_registry_record_bytes, OLD.rebind_handle_sha256, + OLD.encrypted_result_envelope_sha256, OLD.encrypted_result_envelope_bytes) THEN + RAISE EXCEPTION 'Original-new signed identity and encrypted result are immutable' + USING ERRCODE = '23514', CONSTRAINT = 'account_original_new_bound_candidate_immutable'; + END IF; + IF OLD.status = 'PENDING' AND NEW.status = 'COMMITTED' + AND OLD.token_hash IS NOT NULL AND NEW.committed_registry_receipt_sha256 ~ '^[0-9a-f]{64}$' + AND NEW.committed_at IS NOT NULL + AND ROW(NEW.confirmed_admission_at_ms, NEW.confirmed_continuity_expires_at_ms, + NEW.confirmation_readback_sha256, NEW.handle_consumed_at_ms, + NEW.handle_consumption_request_id) + IS NOT DISTINCT FROM ROW(OLD.confirmed_admission_at_ms, OLD.confirmed_continuity_expires_at_ms, + OLD.confirmation_readback_sha256, OLD.handle_consumed_at_ms, + OLD.handle_consumption_request_id) THEN + RETURN NEW; + END IF; + IF NEW.status IS DISTINCT FROM OLD.status + OR NEW.committed_registry_receipt_sha256 IS DISTINCT FROM OLD.committed_registry_receipt_sha256 + OR NEW.committed_at IS DISTINCT FROM OLD.committed_at THEN + RAISE EXCEPTION 'Original-new issuance lifecycle transition conflicts' + USING ERRCODE = '23514', CONSTRAINT = 'account_original_new_bound_commit_once'; + END IF; + IF OLD.confirmed_admission_at_ms IS NOT NULL + AND ROW(NEW.confirmed_admission_at_ms, NEW.confirmed_continuity_expires_at_ms, + NEW.confirmation_readback_sha256) + IS DISTINCT FROM ROW(OLD.confirmed_admission_at_ms, OLD.confirmed_continuity_expires_at_ms, + OLD.confirmation_readback_sha256) THEN + RAISE EXCEPTION 'Original-new final-admission confirmation is immutable' + USING ERRCODE = '23514', CONSTRAINT = 'account_original_new_bound_confirmation_immutable'; + END IF; + IF OLD.confirmed_admission_at_ms IS NULL AND NEW.confirmed_admission_at_ms IS NOT NULL + AND (OLD.status <> 'COMMITTED' OR NEW.status <> 'COMMITTED' + OR OLD.token_hash IS NULL OR OLD.rebind_handle_sha256 IS NULL + OR OLD.encrypted_result_envelope_bytes IS NULL) THEN + RAISE EXCEPTION 'Original-new confirmation requires the committed protected result' + USING ERRCODE = '23514', CONSTRAINT = 'account_original_new_bound_confirmation_after_commit'; + END IF; + IF OLD.handle_consumed_at_ms IS NOT NULL + AND ROW(NEW.handle_consumed_at_ms, NEW.handle_consumption_request_id) + IS DISTINCT FROM ROW(OLD.handle_consumed_at_ms, OLD.handle_consumption_request_id) THEN + RAISE EXCEPTION 'Original-new rebind handle consumption is immutable' + USING ERRCODE = '23514', CONSTRAINT = 'account_original_new_bound_consumption_immutable'; + END IF; + IF OLD.handle_consumed_at_ms IS NULL AND NEW.handle_consumed_at_ms IS NOT NULL + AND (OLD.status <> 'COMMITTED' OR NEW.status <> 'COMMITTED' + OR OLD.confirmed_admission_at_ms IS NULL + OR OLD.confirmed_continuity_expires_at_ms IS NULL + OR NEW.handle_consumed_at_ms < OLD.confirmed_admission_at_ms + OR NEW.handle_consumed_at_ms >= OLD.confirmed_continuity_expires_at_ms) THEN + RAISE EXCEPTION 'Original-new handle consumption requires prior current admission confirmation' + USING ERRCODE = '23514', CONSTRAINT = 'account_original_new_bound_consumption_after_confirmation'; + END IF; + RETURN NEW; +END; +$$; +CREATE TRIGGER account_original_new_bound_gameplay_issuance_guard +BEFORE INSERT OR UPDATE OR DELETE ON account_original_new_bound_gameplay_issuances +FOR EACH ROW EXECUTE FUNCTION account_original_new_bound_gameplay_issuance_guard(); + +CREATE FUNCTION account_original_new_bound_gameplay_issuance_no_truncate() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + IF EXISTS (SELECT 1 FROM account_original_new_bound_gameplay_issuances) THEN + RAISE EXCEPTION 'Original-new gameplay issuance evidence cannot be truncated' USING ERRCODE = '23514'; + END IF; + RETURN NULL; +END; +$$; +CREATE TRIGGER account_original_new_bound_gameplay_issuance_no_truncate +BEFORE TRUNCATE ON account_original_new_bound_gameplay_issuances +FOR EACH STATEMENT EXECUTE FUNCTION account_original_new_bound_gameplay_issuance_no_truncate(); +-- [jooq ignore stop] + +-- Extend the existing token-identity fence with an explicit purpose arm. Existing rows are LOGIN +-- and retain their old source predicate; ORIGINAL_NEW fences require the separate immutable +-- Account-owned ORIGINAL-NEW issuance row above to be COMMITTED. +-- PostgreSQL supplies this name for the original inline foreign key; the jOOQ H2 +-- interpreter assigns a different generated name. The real migration must remove it. +-- [jooq ignore start] +ALTER TABLE account_gameplay_token_identity_fences + DROP CONSTRAINT account_gameplay_token_identity_fences_operation_id_fkey; +-- [jooq ignore stop] +ALTER TABLE account_gameplay_token_identity_fences + ADD COLUMN source_kind VARCHAR(16) NOT NULL DEFAULT 'LOGIN'; +ALTER TABLE account_gameplay_token_identity_fences + ADD CONSTRAINT account_gameplay_token_identity_source_kind_check + CHECK (source_kind IN ('LOGIN', 'ORIGINAL_NEW')); + +-- [jooq ignore start] +CREATE OR REPLACE 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; + IF NEW.source_kind = 'LOGIN' THEN + 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; + ELSIF NEW.source_kind = 'ORIGINAL_NEW' THEN + PERFORM operation_id FROM account_original_new_bound_gameplay_issuances + 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; + ELSE + RAISE EXCEPTION 'Account token fence purpose is unsupported' USING ERRCODE = '23514'; + END IF; + IF NOT FOUND THEN + RAISE EXCEPTION 'Account token fence requires exact COMMITTED purpose-bound 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.source_kind, 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.source_kind, 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; +$$; +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V162__account_original_ack_pg18_historical_recovery.sql b/services/account-service/src/main/resources/db/migration/V162__account_original_ack_pg18_historical_recovery.sql new file mode 100644 index 0000000000..67c22cbe7b --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V162__account_original_ack_pg18_historical_recovery.sql @@ -0,0 +1,142 @@ +-- Qualify PostgreSQL 18 historical original-ACK recovery through the existing canonical reader. +-- Preserve V144/V146 and every original receipt/operation byte. PostgreSQL 16 remains supported; +-- other majors remain denied. This read observes durability and never reconstructs the original +-- physical-COMMIT acknowledgement, restamps its clock bound, writes a marker or forces WAL flush. +-- The private owner ends capture before observing coverage, without lowering or recapturing +-- the fence. The legacy direct SQL reader remains strict while holding its capture locks. +-- PostgreSQL 18 retains the required read-only WAL insert/flush observations, top-level XID +-- semantics and SERIALIZABLE snapshot isolation: +-- https://www.postgresql.org/docs/18/functions-admin.html#FUNCTIONS-ADMIN-BACKUP +-- https://www.postgresql.org/docs/18/functions-info.html#FUNCTIONS-TXID-SNAPSHOT +-- https://www.postgresql.org/docs/18/transaction-iso.html#XACT-SERIALIZABLE +-- [jooq ignore start] +CREATE FUNCTION account_gameplay_admission_capture_original_ack_receipt( + requested_request_id UUID, expected_sha TEXT, expected_decision UUID) +RETURNS TABLE ( + captured_receipt account_gameplay_admission_original_commit_ack_receipts, + wal_upper_fence pg_lsn, + capture_snapshot pg_snapshot, + capture_own_xid TEXT, + capture_initial_flush pg_lsn) +LANGUAGE plpgsql AS $$ +DECLARE + operation account_gameplay_admission_lease_operations%ROWTYPE; + receipt account_gameplay_admission_original_commit_ack_receipts%ROWTYPE; + locked_operation account_gameplay_admission_lease_operations%ROWTYPE; + locked_receipt account_gameplay_admission_original_commit_ack_receipts%ROWTYPE; + own_xid TEXT; + fixed_snapshot pg_snapshot; + insert_fence pg_lsn; + initial_flush_fence pg_lsn; +BEGIN + IF current_setting('transaction_isolation') IS DISTINCT FROM 'serializable' + OR current_setting('transaction_read_only') IS DISTINCT FROM 'off' THEN + RAISE EXCEPTION 'Writable SERIALIZABLE Account acknowledgement receipt read required' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_original_ack_receipt_transaction_required'; + END IF; + IF NOT ((current_setting('server_version_num')::integer >= 160000 + AND current_setting('server_version_num')::integer < 170000) + OR (current_setting('server_version_num')::integer >= 180000 + AND current_setting('server_version_num')::integer < 190000)) + OR pg_is_in_recovery() OR current_setting('fsync') IS DISTINCT FROM 'on' THEN + RAISE EXCEPTION 'Supported durable PostgreSQL 16 or 18 primary required for Account acknowledgement receipt read' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_original_ack_receipt_durable_primary'; + END IF; + -- Establish one fixed snapshot and its WAL upper fence before any heap read or row lock. + -- A receipt visible in this snapshot committed independently before this fence. + fixed_snapshot := pg_current_snapshot(); + own_xid := pg_current_xact_id_if_assigned()::text; + insert_fence := pg_current_wal_insert_lsn(); + initial_flush_fence := pg_current_wal_flush_lsn(); + IF insert_fence IS NULL OR insert_fence <= '0/0'::pg_lsn THEN + RAISE EXCEPTION 'Original Account acknowledgement receipt WAL coverage unavailable' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_original_ack_receipt_wal_coverage'; + END IF; + + SELECT * INTO operation FROM account_gameplay_admission_lease_operations + WHERE request_id = requested_request_id; + IF NOT FOUND THEN + RAISE EXCEPTION 'Original Account acknowledgement operation missing' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_original_ack_receipt_operation_required'; + END IF; + SELECT * INTO receipt FROM account_gameplay_admission_original_commit_ack_receipts + WHERE request_id = requested_request_id; + IF NOT FOUND OR operation.status IS DISTINCT FROM 'COMMITTED' + OR operation.finalization_xid IS NULL + OR expected_sha IS DISTINCT FROM operation.evidence_sha256 + OR expected_decision IS DISTINCT FROM operation.binding_decision_id + OR receipt.schema_version IS DISTINCT FROM 1 + OR receipt.account_uuid IS DISTINCT FROM operation.account_uuid + OR receipt.lease_id IS DISTINCT FROM operation.lease_id + OR receipt.lease_fence IS DISTINCT FROM operation.lease_fence + OR receipt.evidence_sha256 IS DISTINCT FROM operation.evidence_sha256 + OR receipt.binding_decision_id IS DISTINCT FROM operation.binding_decision_id + OR receipt.expires_at_ms IS DISTINCT FROM operation.expires_at_ms + OR receipt.finalization_xid IS DISTINCT FROM operation.finalization_xid + OR receipt.committed_before_ms <= 0 + OR receipt.committed_before_ms >= operation.expires_at_ms THEN + RAISE EXCEPTION 'Exact durable original Account acknowledgement receipt required' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_original_ack_receipt_required'; + END IF; + -- receipt_xid is the database-stamped top-level XID, so this excludes the current transaction + -- and any released subtransaction while retaining an independently committed historical row. + IF receipt.receipt_xid = own_xid THEN + RAISE EXCEPTION 'Original Account acknowledgement receipt requires independent commit' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_original_ack_receipt_independent'; + END IF; + + PERFORM 1 FROM accounts WHERE account_uuid = operation.account_uuid FOR UPDATE; + IF NOT FOUND THEN + RAISE EXCEPTION 'Original Account acknowledgement owner missing' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_original_ack_receipt_owner_required'; + END IF; + SELECT * INTO locked_operation FROM account_gameplay_admission_lease_operations + WHERE request_id = requested_request_id FOR UPDATE; + IF NOT FOUND OR locked_operation IS DISTINCT FROM operation THEN + RAISE EXCEPTION 'Exact durable original Account acknowledgement receipt required' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_original_ack_receipt_required'; + END IF; + SELECT * INTO locked_receipt FROM account_gameplay_admission_original_commit_ack_receipts + WHERE request_id = requested_request_id FOR UPDATE; + IF NOT FOUND OR locked_receipt IS DISTINCT FROM receipt THEN + RAISE EXCEPTION 'Exact durable original Account acknowledgement receipt required' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_original_ack_receipt_required'; + END IF; + + -- This is pending evidence only. The private owner must independently observe durable + -- coverage of this exact frozen fence after the capture transaction successfully completes. + RETURN QUERY SELECT receipt, insert_fence, fixed_snapshot, own_xid, initial_flush_fence; +END; +$$; + +CREATE OR REPLACE FUNCTION account_gameplay_admission_read_original_ack_receipt_durably( + requested_request_id UUID, expected_sha TEXT, expected_decision UUID) +RETURNS SETOF account_gameplay_admission_original_commit_ack_receipts LANGUAGE plpgsql AS $$ +DECLARE + captured RECORD; + receipt account_gameplay_admission_original_commit_ack_receipts%ROWTYPE; + flush_fence pg_lsn; + observation INTEGER; +BEGIN + SELECT * INTO STRICT captured FROM account_gameplay_admission_capture_original_ack_receipt( + requested_request_id, expected_sha, expected_decision); + receipt := captured.captured_receipt; + -- Direct SQL callers retain the strict in-transaction proof. A capture by itself is never a + -- durable result; private owner continuation observes this same fence outside its SQL locks. + FOR observation IN 1..50 LOOP + flush_fence := pg_current_wal_flush_lsn(); + EXIT WHEN flush_fence IS NOT NULL AND flush_fence >= captured.wal_upper_fence; + IF observation = 50 THEN + RAISE EXCEPTION 'Original Account acknowledgement receipt WAL coverage unavailable' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_original_ack_receipt_wal_coverage', + DETAIL = format('snapshot=%s own_xid_if_assigned=%s finalization_xid=%s receipt_xid=%s insert_fence=%s initial_flush=%s final_flush=%s unchanged_expiry_ms=%s', + captured.capture_snapshot, captured.capture_own_xid, + receipt.finalization_xid, receipt.receipt_xid, captured.wal_upper_fence, + captured.capture_initial_flush, flush_fence, receipt.expires_at_ms); + END IF; + PERFORM pg_sleep(0.01); + END LOOP; + RETURN NEXT receipt; +END; +$$; +-- [jooq ignore stop] diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java index 537621aa6b..d8a54ecc18 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java @@ -5,9 +5,13 @@ import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import integration.net.firedevops.firemud.accountservice.repository.AccountPostgresIntegrationFixture; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; import java.sql.Connection; import java.sql.SQLException; import java.time.Instant; +import java.util.HexFormat; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @@ -15,6 +19,9 @@ import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionOriginalAckReceipt; +import net.firedevops.firemud.accountservice.dto.AccountGameplayTokenIdentityFence.SourceKind; +import net.firedevops.firemud.accountservice.dto.AccountGameplayTokenIdentityFence.TokenIdentity; import net.firedevops.firemud.accountservice.entity.Account; import net.firedevops.firemud.accountservice.repository.AccountGameplayAdmissionOriginalCommitExecutor.OriginalCommitAcknowledgement; import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; @@ -34,13 +41,14 @@ import org.springframework.transaction.support.TransactionTemplate; /** - * PostgreSQL 18 proof for fresh original-ACK storage only. + * PostgreSQL 18 proof for fresh and historical original-ACK and bounded ORIGINAL-NEW storage. * *

Tests exercise the original operation's physical COMMIT, its opaque pre-expiry - * acknowledgement, and a separate physical receipt COMMIT. PostgreSQL 18 does not enable the - * retained historical durability reader or lost-acknowledgement recovery. SQL and JVM storage proof - * establish no authentication, current ownership, admission, production privilege adoption, or - * gameplay. + * acknowledgement, and a separate physical receipt COMMIT. The lineage test uses controlled token, + * registry and encrypted-envelope artifacts to prove immutable generation and one-use storage; it + * does not claim production signing, Redis acknowledgement, current caller authority, final + * admission, production privilege adoption, or gameplay. Historical recovery observes WAL coverage + * without reconstructing the original acknowledgement or changing its clock bound. */ @Execution(ExecutionMode.SAME_THREAD) class AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest { @@ -313,7 +321,7 @@ void ownFinalizationAndReleasedSubtransactionCannotSupplyIndependentOriginal() { } @Test - void historicalDurableReadRemainsDeniedOnPostgres18AfterReceiptInsert() { + void ownReceiptAndReleasedSubtransactionCannotSupplyHistoricalDurability() { for (boolean subtransaction : List.of(false, true)) { var context = context(); var ack = finalized(context, 15000); @@ -329,11 +337,172 @@ void historicalDurableReadRemainsDeniedOnPostgres18AfterReceiptInsert() { context.dsl().execute("RELEASE SAVEPOINT receipt_creation"); repository(context).readDurably(ack.evidence(), ack.decisionId()); })) - .hasMessageContaining("Supported durable PostgreSQL 16 primary required"); + .hasMessageContaining("requires independent commit"); assertThat(context.dsl().fetchCount(DSL.table(RECEIPTS))).isZero(); } } + @Test + void historicalCaptureFreezesItsFenceBeforeLocksAndObservesCoverageAfterCompletion() { + var context = context(); + var ack = finalized(context, 15000); + var expected = + new AccountGameplayAdmissionOriginalAckReceiptCommitExecutor(context.admin()).confirm(ack); + var storageBefore = ackStorageSnapshot(context); + var sourcesBefore = sourceSnapshot(context); + var pending = + java.util.Objects.requireNonNull( + context + .transaction() + .execute( + status -> { + var captured = + repository(context).captureHistorical(ack.evidence(), ack.decisionId()); + assertThat(captured.receipt()).isEqualTo(expected); + // Actual capture locks append WAL after the original frozen upper fence. + // That later insert position must never replace the SQL-issued proof fence. + assertThat( + context + .dsl() + .fetchSingle( + "SELECT pg_current_wal_insert_lsn() > ?::pg_lsn", + captured.walUpperFence()) + .get(0, Boolean.class)) + .isTrue(); + return captured; + })); + String exactFrozenFence = pending.walUpperFence(); + // No SQL transaction/row lock remains open. Completion itself is not accepted as proof; + // positively observe durable WAL coverage of precisely the captured fence. + assertThat( + context + .dsl() + .fetchSingle("SELECT pg_current_wal_flush_lsn() >= ?::pg_lsn", exactFrozenFence) + .get(0, Boolean.class)) + .isTrue(); + assertThat(pending.walUpperFence()).isEqualTo(exactFrozenFence); + AccountGameplayAdmissionOriginalAckReceipt independentReadback = + context + .transaction() + .execute(status -> repository(context).readExact(ack.evidence(), ack.decisionId())); + assertThat(independentReadback).isEqualTo(pending.receipt()); + assertThat( + new AccountGameplayAdmissionOriginalAckReceiptCommitExecutor(context.admin()) + .read(ack.evidence(), ack.decisionId())) + .isEqualTo(expected); + assertThat(ackStorageSnapshot(context)).isEqualTo(storageBefore); + assertThat(sourceSnapshot(context)).isEqualTo(sourcesBefore); + } + + @Test + void historicalRecoveryRefusesChangedDigestDecisionAndMissingOperationWithoutChangingRows() { + var context = context(); + var ack = finalized(context, 15000); + var expected = + new AccountGameplayAdmissionOriginalAckReceiptCommitExecutor(context.admin()).confirm(ack); + var storageBefore = ackStorageSnapshot(context); + var sourcesBefore = sourceSnapshot(context); + for (boolean changedDigest : List.of(false, true)) { + assertThatThrownBy( + () -> + context + .transaction() + .executeWithoutResult( + status -> + context + .dsl() + .fetch( + "SELECT * FROM account_gameplay_admission_read_original_ack_receipt_durably(?, ?, ?)", + request(ack.evidence()), + changedDigest ? "0".repeat(64) : ack.evidence().sha256(), + changedDigest ? ack.decisionId() : UUID.randomUUID()))) + .hasMessageContaining("Exact durable original Account acknowledgement receipt required"); + } + assertThatThrownBy( + () -> + context + .transaction() + .executeWithoutResult( + status -> + context + .dsl() + .fetch( + "SELECT * FROM account_gameplay_admission_read_original_ack_receipt_durably(?, ?, ?)", + UUID.randomUUID(), + ack.evidence().sha256(), + ack.decisionId()))) + .hasMessageContaining("Original Account acknowledgement operation missing"); + assertThat( + new AccountGameplayAdmissionOriginalAckReceiptCommitExecutor(context.admin()) + .read(ack.evidence(), ack.decisionId())) + .isEqualTo(expected); + assertThat(ackStorageSnapshot(context)).isEqualTo(storageBefore); + assertThat(sourceSnapshot(context)).isEqualTo(sourcesBefore); + } + + @Test + void historicalRecoveryCannotSeeReceiptCommittedAfterItsFixedSnapshot() throws Exception { + var context = context(); + var ack = finalized(context, 15000); + try (var stale = context.admin().getConnection()) { + stale.setAutoCommit(false); + stale.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE); + DSL.using(stale).fetchSingle("SELECT pg_current_snapshot()"); + var expected = + new AccountGameplayAdmissionOriginalAckReceiptCommitExecutor(context.admin()) + .confirm(ack); + var storageBefore = ackStorageSnapshot(context); + assertThatThrownBy( + () -> + DSL.using(stale) + .fetch( + "SELECT * FROM account_gameplay_admission_read_original_ack_receipt_durably(?, ?, ?)", + request(ack.evidence()), + ack.evidence().sha256(), + ack.decisionId())) + .hasMessageContaining("Exact durable original Account acknowledgement receipt required"); + stale.rollback(); + assertThat( + new AccountGameplayAdmissionOriginalAckReceiptCommitExecutor(context.admin()) + .read(ack.evidence(), ack.decisionId())) + .isEqualTo(expected); + assertThat(ackStorageSnapshot(context)).isEqualTo(storageBefore); + } + } + + @Test + void v162QualifiesRetainedPg18ReceiptWithoutChangingHistoricalStorage() { + var context = context("161"); + var ack = finalized(context, 15000); + var expected = + new AccountGameplayAdmissionOriginalAckReceiptCommitExecutor(context.admin()).confirm(ack); + var storageBefore = ackStorageSnapshot(context); + var sourcesBefore = sourceSnapshot(context); + assertThatThrownBy( + () -> + context + .transaction() + .execute( + status -> + repository(context).readDurably(ack.evidence(), ack.decisionId()))) + .hasMessageContaining("Supported durable PostgreSQL 16 primary required"); + Flyway.configure() + .dataSource(context.admin()) + .schemas(context.schema()) + .defaultSchema(context.schema()) + .placeholders(Map.of("serviceSchema", context.schema())) + .locations("classpath:db/migration") + .target("162") + .load() + .migrate(); + assertThat( + new AccountGameplayAdmissionOriginalAckReceiptCommitExecutor(context.admin()) + .read(ack.evidence(), ack.decisionId())) + .isEqualTo(expected); + assertThat(ackStorageSnapshot(context)).isEqualTo(storageBefore); + assertThat(sourceSnapshot(context)).isEqualTo(sourcesBefore); + } + @Test void staleSnapshotBeforeOriginalCommitCannotCreateAcknowledgementReceipt() throws Exception { var context = context(); @@ -654,7 +823,7 @@ void acknowledgementFromAnotherPostgresDataSourceCannotCreateReceipt() { } @Test - void lostReceiptCommitAcknowledgementDoesNotReconstructFreshReceiptDurability() { + void lostReceiptCommitAcknowledgementRecoversHistoricallyWithoutReconstructingOriginal() { var context = context(); var evidence = pending(context, 15000); UUID decision = UUID.randomUUID(); @@ -690,10 +859,17 @@ void lostReceiptCommitAcknowledgementDoesNotReconstructFreshReceiptDurability() assertThat(retained.get("receipt_xid")).isNotEqualTo(ack.finalizationXid()); assertThat(operation(context, evidence)).isEqualTo(operationBefore); - // PostgreSQL 18 deliberately cannot recover a retained receipt from its retry COMMIT. - assertThatThrownBy( - () -> new AccountGameplayAdmissionOriginalAckReceiptCommitExecutor(source).confirm(ack)) - .hasMessageContaining("Supported durable PostgreSQL 16 primary required"); + var storageBefore = ackStorageSnapshot(context); + // A replacement executor proves the retained receipt through the canonical historical reader; + // it never reruns the original finalizer or substitutes its later COMMIT for original timing. + var replacement = new AccountGameplayAdmissionOriginalAckReceiptCommitExecutor(context.admin()); + var recovered = replacement.read(evidence, decision); + assertThat(recovered.receiptXid()).isEqualTo(retained.get("receipt_xid")); + assertThat(recovered.committedBeforeMs()).isEqualTo(ack.committedBeforeMs()); + assertThat(recovered.finalizationXid()).isEqualTo(ack.finalizationXid()); + assertThat(new AccountGameplayAdmissionOriginalAckReceiptCommitExecutor(source).confirm(ack)) + .isEqualTo(recovered); + assertThat(ackStorageSnapshot(context)).isEqualTo(storageBefore); assertThat(receipt(context)).isEqualTo(retained); assertThat(operation(context, evidence)).isEqualTo(operationBefore); assertThat(sourceSnapshot(context)).isEqualTo(sourcesBefore); @@ -712,7 +888,7 @@ void returnedCommitFaultConnectionClosesItsPhysicalConnection() throws SQLExcept } @Test - void retainedCommittedRetryCannotMintFreshAckAndHistoricalReceiptRecoveryStaysDenied() { + void retainedCommittedRetryCannotMintFreshAckAndHistoricalReceiptRecoveryPreservesOriginal() { var context = context(); var ack = finalized(context, 15000); var receiptExecutor = @@ -720,6 +896,8 @@ void retainedCommittedRetryCannotMintFreshAckAndHistoricalReceiptRecoveryStaysDe var receipt = receiptExecutor.confirm(ack); var operationBefore = operation(context, ack.evidence()); var receiptBefore = receipt(context); + var storageBefore = ackStorageSnapshot(context); + var sourcesBefore = sourceSnapshot(context); assertThat(receipt.finalizationXid()).isEqualTo(ack.finalizationXid()); assertThat(receipt.receiptXid()).isNotEqualTo(ack.finalizationXid()); @@ -728,12 +906,17 @@ void retainedCommittedRetryCannotMintFreshAckAndHistoricalReceiptRecoveryStaysDe new AccountGameplayAdmissionOriginalCommitExecutor(context.admin()) .execute(ack.evidence(), ack.decisionId())) .hasMessageContaining("Fresh owned Account original COMMIT required"); - assertThatThrownBy(() -> receiptExecutor.read(ack.evidence(), ack.decisionId())) - .hasMessageContaining("Supported durable PostgreSQL 16 primary required"); - // A retained receipt's retry COMMIT is not historical durability proof on PostgreSQL 18. - assertThatThrownBy(() -> receiptExecutor.confirm(ack)) - .hasMessageContaining("Supported durable PostgreSQL 16 primary required"); - + assertThat(receiptExecutor.read(ack.evidence(), ack.decisionId())).isEqualTo(receipt); + assertThat(receiptExecutor.confirm(ack)).isEqualTo(receipt); + // A new executor, after the original lease expires, observes the same historical evidence. + // This supplies neither renewed admission authority nor a fresh original acknowledgement. + waitPastExpiry(context, ack); + assertThat( + new AccountGameplayAdmissionOriginalAckReceiptCommitExecutor(context.admin()) + .read(ack.evidence(), ack.decisionId())) + .isEqualTo(receipt); + assertThat(ackStorageSnapshot(context)).isEqualTo(storageBefore); + assertThat(sourceSnapshot(context)).isEqualTo(sourcesBefore); assertThat(operation(context, ack.evidence())).isEqualTo(operationBefore); assertThat(receipt(context)).isEqualTo(receiptBefore); assertThat(context.dsl().fetchCount(DSL.table(RECEIPTS))).isOne(); @@ -846,7 +1029,241 @@ void genuineAckSqlEntryRequiresWritableSerializableTransactionAndKeepsFinalizerS assertThat(context.dsl().fetchCount(DSL.table(RECEIPTS))).isZero(); } + @Test + void originalNewLineageFreezesGenerationAndHandleUntilAuthenticatedAdmissionConfirmation() { + var context = context(); + var ack = finalized(context, 15000, 1L); + var receipt = + new AccountGameplayAdmissionOriginalAckReceiptCommitExecutor(context.admin()).confirm(ack); + var repository = new AccountOriginalNewBoundGameplayIssuanceRepository(context.dsl()); + long nowSeconds = Instant.now().getEpochSecond(); + UUID lineageId = UUID.randomUUID(); + UUID tokenJti = UUID.randomUUID(); + + var created = + context + .transaction() + .execute( + status -> + repository.beginGenesis( + ack.evidence(), + receipt, + lineageId, + tokenJti, + nowSeconds, + nowSeconds, + nowSeconds + 300L)); + assertThat(created.tokenGeneration()).isEqualTo(1L); + assertThat(created.status()) + .isEqualTo(AccountOriginalNewBoundGameplayIssuanceRepository.Status.PENDING); + assertThat(created.lineageId()).isEqualTo(lineageId); + assertThat(created.tokenJti()).isEqualTo(tokenJti); + assertThat(new String(created.membershipBaselineCanonicalBytes(), StandardCharsets.UTF_8)) + .contains("\"membershipLifecycleState\":\"ACTIVE\""); + assertThat(new String(created.outboxCheckpointsCanonicalBytes(), StandardCharsets.UTF_8)) + .contains("account:auth-authority:v1:account/"); + assertThat(created.tokenHash()).isNull(); + assertThat(created.rebindHandleSha256()).isNull(); + assertThat(created.confirmedAdmissionAtMillis()).isNull(); + + // A lost reply supplies fresh proposed IDs and times; the durable owner returns the original + // lineage and frozen claims rather than opening another generation or signing identity. + var retry = + context + .transaction() + .execute( + status -> + repository.beginGenesis( + ack.evidence(), + receipt, + UUID.randomUUID(), + UUID.randomUUID(), + nowSeconds + 1L, + nowSeconds + 1L, + nowSeconds + 301L)); + assertThat(retry.lineageId()).isEqualTo(created.lineageId()); + assertThat(retry.tokenJti()).isEqualTo(created.tokenJti()); + assertThat(retry.issuedAtEpochSecond()).isEqualTo(created.issuedAtEpochSecond()); + assertThat(retry.notBeforeEpochSecond()).isEqualTo(created.notBeforeEpochSecond()); + assertThat(retry.expiresAtEpochSecond()).isEqualTo(created.expiresAtEpochSecond()); + assertThat(retry.membershipBaselineCanonicalBytes()) + .containsExactly(created.membershipBaselineCanonicalBytes()); + assertThat(retry.membershipVersionCanonicalBytes()) + .containsExactly(created.membershipVersionCanonicalBytes()); + assertThat(retry.outboxCheckpointsCanonicalBytes()) + .containsExactly(created.outboxCheckpointsCanonicalBytes()); + assertThat(context.dsl().fetchCount(DSL.table("account_original_new_bound_gameplay_issuances"))) + .isOne(); + + byte[] registryRecord = "controlled-pending-record".getBytes(StandardCharsets.UTF_8); + byte[] protectedEnvelope = "controlled-encrypted-result".getBytes(StandardCharsets.UTF_8); + byte[] opaqueHandle = new byte[32]; + java.util.Arrays.fill(opaqueHandle, (byte) 0x2a); + String tokenHash = "a".repeat(64); + String handleHash = sha256(opaqueHandle); + var bound = + context + .transaction() + .execute( + status -> + repository.bindSignedResult( + retry, + tokenHash, + "controlled-test-kid", + "1", + registryRecord, + handleHash, + protectedEnvelope)); + assertThat(bound.status()) + .isEqualTo(AccountOriginalNewBoundGameplayIssuanceRepository.Status.PENDING); + assertThat(bound.rebindHandleSha256()).isEqualTo(handleHash); + assertThat(bound.confirmedAdmissionAtMillis()).isNull(); + assertThat(bound.handleConsumedAtMillis()).isNull(); + assertThatThrownBy( + () -> + context + .transaction() + .execute( + status -> + repository.bindSignedResult( + bound, + "c".repeat(64), + "controlled-test-kid", + "1", + registryRecord, + handleHash, + protectedEnvelope))) + .hasMessageContaining("Original-new bound gameplay issuance is unavailable"); + assertThat(repositoryRead(context, repository, ack.evidence()).tokenHash()) + .isEqualTo(tokenHash); + + String pendingRegistryReceipt = "d".repeat(64); + var committed = + context.transaction().execute(status -> repository.commit(bound, pendingRegistryReceipt)); + assertThat(committed.status()) + .isEqualTo(AccountOriginalNewBoundGameplayIssuanceRepository.Status.COMMITTED); + assertThat(committed.committedRegistryReceiptSha256()).isEqualTo(pendingRegistryReceipt); + TokenIdentity tokenIdentity = + new TokenIdentity( + committed.accountId(), + committed.lineageId(), + committed.requestId(), + committed.tokenHash(), + committed.tokenJti(), + committed.notBeforeEpochSecond(), + committed.tokenGeneration(), + committed.issuanceFence(), + SourceKind.ORIGINAL_NEW); + var activeTokenFence = + context + .transaction() + .execute( + status -> + new AccountGameplayTokenIdentityFenceRepository(context.dsl()) + .registerCommittedOriginalNewIssuance(tokenIdentity)); + assertThat(activeTokenFence.identity().sourceKind()).isEqualTo(SourceKind.ORIGINAL_NEW); + assertThat(activeTokenFence.tokenIdentityFence()).isEqualTo(1L); + var recoveredActiveTokenFence = + context + .transaction() + .execute( + status -> + new AccountGameplayTokenIdentityFenceRepository(context.dsl()) + .requireActiveForUpdate(tokenIdentity)); + assertThat(recoveredActiveTokenFence).isEqualTo(activeTokenFence); + UUID consumeRequest = UUID.randomUUID(); + assertThatThrownBy( + () -> + context + .transaction() + .execute( + status -> + repository.consumeOneUseHandle( + committed, handleHash, consumeRequest, 1L))) + .hasMessageContaining("Original-new bound gameplay issuance is unavailable"); + + long databaseNow = + context + .dsl() + .fetchSingle("SELECT floor(extract(epoch FROM clock_timestamp()) * 1000)::bigint") + .get(0, Long.class); + long actualAdmissionAt = databaseNow - 1L; + long continuityExpiresAt = actualAdmissionAt + 300000L; + String authenticatedReadback = + sha256("authenticated-final-readback".getBytes(StandardCharsets.UTF_8)); + var confirmed = + context + .transaction() + .execute( + status -> + repository.confirmFinalAdmission( + committed, actualAdmissionAt, continuityExpiresAt, authenticatedReadback)); + assertThat(confirmed.confirmedAdmissionAtMillis()).isEqualTo(actualAdmissionAt); + assertThat(confirmed.confirmedContinuityExpiresAtMillis()).isEqualTo(continuityExpiresAt); + assertThat(confirmed.confirmationReadbackSha256()).isEqualTo(authenticatedReadback); + var sameConfirmationRetry = + context + .transaction() + .execute( + status -> + repository.confirmFinalAdmission( + confirmed, actualAdmissionAt, continuityExpiresAt, authenticatedReadback)); + assertThat(sameConfirmationRetry.confirmedAdmissionAtMillis()).isEqualTo(actualAdmissionAt); + assertThat(sameConfirmationRetry.confirmationReadbackSha256()).isEqualTo(authenticatedReadback); + assertThatThrownBy( + () -> + context + .transaction() + .execute( + status -> + repository.confirmFinalAdmission( + confirmed, + actualAdmissionAt + 1L, + continuityExpiresAt + 1L, + authenticatedReadback))) + .hasMessageContaining("Original-new bound gameplay issuance is unavailable"); + + var consumed = + context + .transaction() + .execute( + status -> + repository.consumeOneUseHandle( + confirmed, handleHash, consumeRequest, actualAdmissionAt)); + assertThat(consumed.handleConsumptionRequestId()).isEqualTo(consumeRequest); + assertThat(consumed.handleConsumedAtMillis()).isBetween(actualAdmissionAt, continuityExpiresAt); + var sameConsumeRetry = + context + .transaction() + .execute( + status -> + repository.consumeOneUseHandle( + consumed, handleHash, consumeRequest, actualAdmissionAt)); + assertThat(sameConsumeRetry.handleConsumedAtMillis()) + .isEqualTo(consumed.handleConsumedAtMillis()); + assertThatThrownBy( + () -> + context + .transaction() + .execute( + status -> + repository.consumeOneUseHandle( + sameConsumeRetry, + handleHash, + UUID.randomUUID(), + actualAdmissionAt))) + .hasMessageContaining("Original-new bound gameplay issuance is unavailable"); + + java.util.Arrays.fill(registryRecord, (byte) 0); + java.util.Arrays.fill(protectedEnvelope, (byte) 0); + java.util.Arrays.fill(opaqueHandle, (byte) 0); + } + private static Context context() { + return context("latest"); + } + + private static Context context(String target) { String schema = "protected_" + UUID.randomUUID().toString().replace("-", ""); var admin = POSTGRES.dataSource(schema); Flyway.configure() @@ -855,6 +1272,7 @@ private static Context context() { .defaultSchema(schema) .placeholders(Map.of("serviceSchema", schema)) .locations("classpath:db/migration") + .target(target) .load() .migrate(); var transaction = new TransactionTemplate(new DataSourceTransactionManager(admin)); @@ -866,6 +1284,26 @@ private static Context context() { transaction); } + private static AccountOriginalNewBoundGameplayIssuanceRepository.Genesis repositoryRead( + Context context, + AccountOriginalNewBoundGameplayIssuanceRepository repository, + AccountGameplayAdmissionLeaseEvidence evidence) { + return context + .transaction() + .execute( + status -> + repository.readByLease( + UUID.fromString((String) evidence.carrier().get("leaseId")))); + } + + private static String sha256(byte[] value) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value)); + } catch (NoSuchAlgorithmException impossible) { + throw new AssertionError(impossible); + } + } + private static javax.sql.DataSource loseCommitAcknowledgementAfter( javax.sql.DataSource delegate, java.util.concurrent.atomic.AtomicInteger physicalCommits, @@ -915,7 +1353,12 @@ public Connection getConnection() throws SQLException { } private static OriginalCommitAcknowledgement finalized(Context context, long lifetime) { - var evidence = pending(context, lifetime); + return finalized(context, lifetime, 7L); + } + + private static OriginalCommitAcknowledgement finalized( + Context context, long lifetime, long issuanceFence) { + var evidence = pending(context, lifetime, issuanceFence); long startedAtNanos = System.nanoTime(); try { return new AccountGameplayAdmissionOriginalCommitExecutor(context.admin()) @@ -962,6 +1405,11 @@ private static OriginalCommitAcknowledgement finalized(Context context, long lif } private static AccountGameplayAdmissionLeaseEvidence pending(Context context, long lifetime) { + return pending(context, lifetime, 7L); + } + + private static AccountGameplayAdmissionLeaseEvidence pending( + Context context, long lifetime, long issuanceFence) { return context .transaction() .execute( @@ -988,14 +1436,17 @@ private static AccountGameplayAdmissionLeaseEvidence pending(Context context, lo .fetchSingle( "SELECT floor(extract(epoch FROM clock_timestamp()) * 1000)::bigint") .get(0, Long.class); - var evidence = evidence(allocation, lifetime, databaseNow); + var evidence = evidence(allocation, lifetime, databaseNow, issuanceFence); repository.beginPending(evidence); return evidence; }); } private static AccountGameplayAdmissionLeaseEvidence evidence( - AccountGameplayAdmissionLeaseRepository.Allocation allocation, long lifetime, long now) { + AccountGameplayAdmissionLeaseRepository.Allocation allocation, + long lifetime, + long now, + long issuanceFence) { String account = allocation.accountId().toString(); Map carrier = new LinkedHashMap<>(); carrier.put("schema", AccountGameplayAdmissionLeaseEvidence.SCHEMA); @@ -1038,7 +1489,7 @@ private static AccountGameplayAdmissionLeaseEvidence evidence( Map.of(TENANT, "1"), "privateRealmGrantVersions", List.of())); - carrier.put("issuanceFence", "7"); + carrier.put("issuanceFence", Long.toString(issuanceFence)); carrier.put( "membershipBaseline", Map.of( @@ -1071,7 +1522,7 @@ private static AccountGameplayAdmissionLeaseEvidence evidence( token.put("tokenSHA256", "a".repeat(64)); token.put("tokenProfile", "game-session-account-delegation"); token.put("tokenGeneration", "1"); - token.put("issuanceFence", "7"); + token.put("issuanceFence", Long.toString(issuanceFence)); token.put("tokenIdentityFence", "9"); token.put("issuedAt", Long.toString(now / 1000 - 1)); token.put("notBefore", Long.toString(now / 1000 - 1)); @@ -1126,6 +1577,21 @@ private static Map sourceSnapshot(Context context) { return snapshot; } + private static Map ackStorageSnapshot(Context context) { + return Map.of( + "operation", + context + .dsl() + .fetchSingle( + "SELECT *, xmin::text AS original_xmin FROM account_gameplay_admission_lease_operations") + .intoMap(), + "receipt", + context + .dsl() + .fetchSingle("SELECT *, xmin::text AS original_xmin FROM " + RECEIPTS) + .intoMap()); + } + private static Map receipt(Context context) { return context.dsl().fetchSingle("SELECT * FROM " + RECEIPTS).intoMap(); } diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountOriginalNewBoundGameplayCredentialOwnerIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountOriginalNewBoundGameplayCredentialOwnerIntegrationTest.java new file mode 100644 index 0000000000..ca69e100a5 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountOriginalNewBoundGameplayCredentialOwnerIntegrationTest.java @@ -0,0 +1,693 @@ +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.when; + +import com.fasterxml.jackson.databind.ObjectMapper; +import io.grpc.Context; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.MessageDigest; +import java.time.Clock; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Base64; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.accountservice.client.AccountOriginalNewFinalAdmissionReadClient; +import net.firedevops.firemud.accountservice.client.AccountOriginalNewFinalAdmissionReadClient.AuthenticatedFinalAdmissionReadback; +import net.firedevops.firemud.accountservice.client.AccountOriginalNewFinalAdmissionReadClient.ExpectedOriginalAdmission; +import net.firedevops.firemud.accountservice.dto.AccountGameplayTokenIdentityFence.SourceKind; +import net.firedevops.firemud.accountservice.dto.AccountGameplayTokenIdentityFence.TokenIdentity; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationResponseEnvelopeRepository.CallerIdentity; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationResponseEnvelopeRepository.RecoveredCredential; +import net.firedevops.firemud.accountservice.repository.AccountOriginalNewBoundGameplayIssuanceRepository.Genesis; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayAdmissionCallerVerifier; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationRedisClient.ActiveRegistryReadback; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationTokenRegistry; +import net.firedevops.firemud.accountservice.service.session.AccountResponseEnvelopeCryptography; +import net.firedevops.firemud.accountservice.service.session.AccountResponseEnvelopeKeyring; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseGrpcCodec.OriginalNewCredential; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +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.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.api.parallel.Execution; +import org.junit.jupiter.api.parallel.ExecutionMode; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Actual Account ORIGINAL_NEW owner proof over the existing current-source PostgreSQL fixture and + * its primary/replica Redis fixture. + * + *

The first LOGIN credential, current Account sources, original NEW lease COMMIT and durable ACK + * receipt, Account ORIGINAL_NEW signer operation, encrypted result recovery, token identity fence, + * and Redis pending/active transition use their existing owners. The signer fixture retains its + * controlled signer-custody/materializer inputs. The explicitly controlled Game Session final-read + * callback supplies schema-v2 COMPLETE results and exercises Account's activation and durable + * confirmation owner; it is not evidence of a real Game Session final CAS or protected final-result + * reader. + */ +@Execution(ExecutionMode.SAME_THREAD) +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +class AccountOriginalNewBoundGameplayCredentialOwnerIntegrationTest { + private static final String NAMESPACE = "test"; + private static final String GAME_SESSION_WORKLOAD = + "spiffe://firemud/ns/test/sa/game-session-service"; + private static final String CONFIRMATION_FAULT_FUNCTION = + "account_original_new_test_fail_confirmation_update"; + private static final String CONFIRMATION_FAULT_TRIGGER = + "account_original_new_test_confirmation_update_failure"; + private static final long SESSION_DURATION_MILLIS = 120_000L; + private static final long REDIS_CLEANUP_MARGIN_MILLIS = 30_000L; + private static final ObjectMapper JSON = new ObjectMapper(); + + @TempDir Path temporaryDirectory; + private AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest fixtureHarness; + private AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.Fixture sourceFixture; + private AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.PhysicalRedisFixture + redisFixture; + + @BeforeAll + static void startPostgres() { + AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.startPostgres(); + } + + @AfterAll + static void stopPostgres() { + AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.stopPostgres(); + } + + @BeforeEach + void createActualSourceFixture() throws Exception { + fixtureHarness = new AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest(); + fixtureHarness.temporaryDirectory = temporaryDirectory; + redisFixture = + AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.PhysicalRedisFixture.start(); + sourceFixture = fixtureHarness.newFixture(redisFixture.client()); + } + + @AfterEach + void cleanOwnedFixture() { + if (redisFixture != null) redisFixture.close(); + if (fixtureHarness != null) fixtureHarness.dropRunOwnedSchemas(); + } + + @Test + void lostSqlConfirmationRecoversOnlyAfterFreshExactControlledFinalReadback() throws Exception { + DSLContext dsl = + DSL.using( + new TransactionAwareDataSourceProxy(sourceFixture.dataSource), SQLDialect.POSTGRES); + DataSourceTransactionManager transactionManager = + new DataSourceTransactionManager(sourceFixture.dataSource); + TransactionTemplate serializable = new TransactionTemplate(transactionManager); + serializable.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE); + var initialIdentity = sourceFixture.committedCandidate.identity(); + CallerIdentity recoveryCaller = + new CallerIdentity(initialIdentity.callerWorkload(), initialIdentity.callerContextId()); + RecoveredCredential recoveredLogin = + sourceFixture.responseRecoveryOwner.recoverInitialLoginResponse( + initialIdentity.requestId(), initialIdentity.accountId(), recoveryCaller); + byte[] loginJwtBytes = recoveredLogin.compactJwtBytes(); + String loginJwt = new String(loginJwtBytes, StandardCharsets.US_ASCII); + Arrays.fill(loginJwtBytes, (byte) 0); + + var authorityGenerations = new AccountAuthorityGenerationRepository(dsl); + var authorityOutbox = new AccountAuthorityOutboxRepository(dsl); + var sourceEvidence = + new AccountAuthoritySourceEvidenceRepository(dsl, authorityGenerations, authorityOutbox); + var authEvidenceBundles = + new AccountAuthEvidenceBundleRepository(dsl, authorityGenerations, authorityOutbox); + var issuanceRepository = + new AccountGameplayDelegationIssuanceRepository(dsl, sourceEvidence, authEvidenceBundles); + var tokenRegistry = + new AccountGameplayDelegationTokenRegistry( + issuanceRepository, + transactionManager, + redisFixture.client(), + Clock.systemUTC(), + GameSessionAccountDelegationProfile.MAX_REGISTRY_RECORD_BYTES, + REDIS_CLEANUP_MARGIN_MILLIS); + AccountResponseEnvelopeCryptography responseCryptography = + testResponseCryptography(temporaryDirectory.resolve("original-new-response-keyring")); + AtomicInteger finalReadCalls = new AtomicInteger(); + AtomicReference expectedAdmission = new AtomicReference<>(); + AtomicReference finalReadMode = new AtomicReference<>(FinalReadMode.EXACT); + List finalReadExpectations = new ArrayList<>(); + List observedFinalReadModes = new ArrayList<>(); + List finalReadResults = new ArrayList<>(); + long controlledAdmissionAtMillis = System.currentTimeMillis() - 100L; + AccountOriginalNewFinalAdmissionReadClient controlledFinalReadback = + expected -> { + finalReadCalls.incrementAndGet(); + expectedAdmission.set(expected); + finalReadExpectations.add(expected); + FinalReadMode mode = finalReadMode.get(); + observedFinalReadModes.add(mode); + if (mode == FinalReadMode.UNAVAILABLE) { + throw new IllegalStateException("controlled Game Session final read unavailable"); + } + AuthenticatedFinalAdmissionReadback readback = + mock(AuthenticatedFinalAdmissionReadback.class); + when(readback.sessionSchemaVersion()).thenReturn(2); + when(readback.admissionState()).thenReturn("COMPLETE"); + when(readback.anchors()) + .thenReturn(mode == FinalReadMode.CHANGED ? changedTokenHash(expected) : expected); + when(readback.admissionAtMillis()).thenReturn(controlledAdmissionAtMillis); + when(readback.continuityExpiresAtMillis()) + .thenReturn(controlledAdmissionAtMillis + SESSION_DURATION_MILLIS); + when(readback.canonicalSessionDurationMillis()).thenReturn(SESSION_DURATION_MILLIS); + when(readback.canonicalReadbackSha256()).thenReturn("f".repeat(64)); + finalReadResults.add(readback); + return readback; + }; + var owner = + new AccountOriginalNewBoundGameplayCredentialOwner( + sourceFixture.dataSource, + NAMESPACE, + new AccountGameplayAdmissionCallerVerifier( + sourceFixture.signerFixture.trustedJwksSource(), + sourceFixture.committedIssuanceOwner, + Clock.systemUTC()), + sourceFixture.signerFixture.signer(), + tokenRegistry, + responseCryptography, + Clock.systemUTC(), + controlledFinalReadback); + GrpcPeerIdentity peer = GrpcPeerIdentity.parseUri(GAME_SESSION_WORKLOAD).orElseThrow(); + AccountGameplayAdmissionLeaseEvidence originalLease = + commitActualOriginalNewLease(dsl, serializable); + UUID originalRequestId = UUID.fromString((String) originalLease.carrier().get("requestId")); + UUID originalDecisionId = + dsl.fetchSingle( + "SELECT binding_decision_id FROM account_gameplay_admission_lease_operations " + + "WHERE request_id = ?", + originalRequestId) + .get(0, UUID.class); + if (originalDecisionId == null) throw new IllegalStateException("Original decision is absent"); + String originalEvidenceSha256 = originalLease.sha256(); + + OriginalNewCredential first = + Context.current() + .withValue(GrpcPeerIdentity.CONTEXT_KEY, peer) + .call(() -> owner.issue(loginJwt, originalLease)); + OriginalNewCredential lostReplyRetry = + Context.current() + .withValue(GrpcPeerIdentity.CONTEXT_KEY, peer) + .call(() -> owner.issue(loginJwt, originalLease)); + try (first; + lostReplyRetry) { + Genesis committed = readGenesis(dsl, serializable, originalLease); + byte[] firstHandle = first.opaqueRebindHandle(); + byte[] retryHandle = lostReplyRetry.opaqueRebindHandle(); + byte[] pendingRecord = committed.pendingRegistryRecordBytes(); + byte[] encryptedResult = committed.encryptedResultEnvelopeBytes(); + try { + assertThat(committed.status()) + .isEqualTo(AccountOriginalNewBoundGameplayIssuanceRepository.Status.COMMITTED); + assertThat(committed.tokenGeneration()).isEqualTo(1L); + assertThat(committed.originalLeaseEvidenceSha256()).isEqualTo(originalEvidenceSha256); + assertThat(committed.bindingDecisionId()).isEqualTo(originalDecisionId); + assertThat(committed.issuanceFence()) + .isEqualTo(Long.parseLong((String) originalLease.carrier().get("issuanceFence"))); + assertExactLeaseSource(committed, originalLease, "authorityTuple"); + assertExactLeaseSource(committed, originalLease, "membershipBaseline"); + assertExactLeaseSource(committed, originalLease, "outboxCheckpoints"); + assertThat(committed.lineageId()).isEqualTo(first.lineageId()); + assertThat(committed.tokenJti()).isEqualTo(first.tokenJti()); + assertThat(first.lineageId()).isNotEqualTo(first.tokenJti()); + assertThat(first.tokenJti()).isNotEqualTo(initialIdentity.tokenJti()); + assertThat(first.originalLeaseId()) + .isEqualTo(UUID.fromString((String) originalLease.carrier().get("leaseId"))); + assertThat(first.originalLeaseFence()) + .isEqualTo(originalLease.leaseFence().longValueExact()); + assertThat(first.issuanceFence()).isEqualTo(committed.issuanceFence()); + assertThat(first.tokenSha256()).isEqualTo(committed.tokenHash()); + assertThat(first.checkpointsSha256()) + .isEqualTo(sha256AndWipe(committed.outboxCheckpointsCanonicalBytes())); + assertThat(sha256(firstHandle)).isEqualTo(committed.rebindHandleSha256()); + assertThat(MessageDigest.isEqual(firstHandle, retryHandle)).isTrue(); + assertThat(lostReplyRetry.tokenSha256()).isEqualTo(first.tokenSha256()); + assertThat(lostReplyRetry.lineageId()).isEqualTo(first.lineageId()); + assertThat(lostReplyRetry.tokenJti()).isEqualTo(first.tokenJti()); + assertThat(lostReplyRetry.issuanceFence()).isEqualTo(first.issuanceFence()); + assertThat(lostReplyRetry.originalAckReceiptXid()).isEqualTo(first.originalAckReceiptXid()); + assertThat(lostReplyRetry.checkpointsSha256()).isEqualTo(first.checkpointsSha256()); + assertThat(committed.confirmedAdmissionAtMillis()).isNull(); + assertThat(committed.handleConsumedAtMillis()).isNull(); + assertThat(encryptedResult.length > 0).isTrue(); + assertThat(first.toString()) + .isEqualTo("AccountGameplayAdmissionLeaseGrpcCodec.OriginalNewCredential[redacted]"); + redisFixture + .client() + .requirePendingRecord( + committed.tokenHash(), + pendingRecord, + Math.addExact( + Math.multiplyExact(committed.expiresAtEpochSecond(), 1_000L), + REDIS_CLEANUP_MARGIN_MILLIS)); + TokenIdentity registeredIdentity = activeIdentity(dsl, committed); + assertThat(registeredIdentity.sourceKind()).isEqualTo(SourceKind.ORIGINAL_NEW); + assertThat(registeredIdentity.operationId()).isEqualTo(committed.lineageId()); + assertThat(registeredIdentity.tokenJti()).isEqualTo(first.tokenJti()); + assertThat(registeredIdentity.tokenSha256()).isEqualTo(first.tokenSha256()); + assertThat(registeredIdentity.tokenGeneration()).isEqualTo(1L); + assertThat(registeredIdentity.issuanceFence()).isEqualTo(committed.issuanceFence()); + assertThat(dsl.fetchCount(DSL.table("account_original_new_bound_gameplay_issuances"))) + .isOne(); + } finally { + Arrays.fill(firstHandle, (byte) 0); + Arrays.fill(retryHandle, (byte) 0); + Arrays.fill(pendingRecord, (byte) 0); + Arrays.fill(encryptedResult, (byte) 0); + } + + long exactRedisExpiryMillis = + Math.addExact( + Math.multiplyExact(committed.expiresAtEpochSecond(), 1_000L), + REDIS_CLEANUP_MARGIN_MILLIS); + installOwnedConfirmationUpdateFailure(dsl); + try { + assertThatThrownBy( + () -> + Context.current() + .withValue(GrpcPeerIdentity.CONTEXT_KEY, peer) + .call(() -> owner.confirmOriginalFinalAdmission(loginJwt, originalLease))) + .isInstanceOf(RuntimeException.class) + .hasMessageContaining("controlled owned original-new confirmation SQL fault"); + } finally { + removeOwnedConfirmationUpdateFailure(dsl); + } + Genesis afterLostConfirmation = assertUnconfirmed(dsl, serializable, originalLease); + assertThat(afterLostConfirmation.tokenHash()).isEqualTo(first.tokenSha256()); + var activeAfterLostConfirmation = + tokenRegistry.requireExactOriginalNewActiveRecord(afterLostConfirmation); + assertThat(activeAfterLostConfirmation.absoluteExpiryMillis()) + .isEqualTo(exactRedisExpiryMillis); + assertThat(finalReadCalls.get()).isEqualTo(1); + + // ACTIVE Redis state cannot substitute for a new authenticated Game Session final read. + finalReadMode.set(FinalReadMode.CHANGED); + assertFinalConfirmationUnavailable(owner, peer, loginJwt, originalLease); + Genesis afterChangedRead = assertUnconfirmed(dsl, serializable, originalLease); + assertSameActiveRegistryReadback( + activeAfterLostConfirmation, + tokenRegistry.requireExactOriginalNewActiveRecord(afterChangedRead)); + + finalReadMode.set(FinalReadMode.UNAVAILABLE); + assertFinalConfirmationUnavailable(owner, peer, loginJwt, originalLease); + Genesis afterUnavailableRead = assertUnconfirmed(dsl, serializable, originalLease); + assertSameActiveRegistryReadback( + activeAfterLostConfirmation, + tokenRegistry.requireExactOriginalNewActiveRecord(afterUnavailableRead)); + + // Recovery makes a fresh read of the same controlled final result and confirms the same + // frozen lineage, token, anchors, continuity deadline, and physical registry expiry. + finalReadMode.set(FinalReadMode.EXACT); + var confirmed = confirm(owner, peer, loginJwt, originalLease); + assertThat(confirmed.lineageId()).isEqualTo(first.lineageId()); + assertThat(confirmed.originalLeaseId()) + .isEqualTo(UUID.fromString((String) originalLease.carrier().get("leaseId"))); + assertThat(confirmed.admissionAtMillis()).isEqualTo(controlledAdmissionAtMillis); + assertThat(confirmed.continuityExpiresAtMillis()) + .isEqualTo(controlledAdmissionAtMillis + SESSION_DURATION_MILLIS); + assertThat(expectedAdmission.get()).isNotNull(); + assertThat(expectedAdmission.get().tokenSha256()).isEqualTo(first.tokenSha256()); + assertThat(expectedAdmission.get().lineageId()).isEqualTo(first.lineageId()); + assertThat(expectedAdmission.get().tokenJti()).isEqualTo(first.tokenJti()); + assertThat(expectedAdmission.get().originalLeaseEvidenceSha256()) + .isEqualTo(originalEvidenceSha256); + assertThat(expectedAdmission.get().tokenGeneration()).isEqualTo(1L); + assertThat(expectedAdmission.get().issuanceFence()).isEqualTo(committed.issuanceFence()); + assertThat(expectedAdmission.get().bindingScopeSha256()) + .isEqualTo(committed.bindingScopeSha256()); + assertThat(expectedAdmission.get().membershipBaselineSha256()) + .isEqualTo(sha256AndWipe(committed.membershipBaselineCanonicalBytes())); + assertThat(expectedAdmission.get().checkpointsSha256()) + .isEqualTo(sha256AndWipe(committed.outboxCheckpointsCanonicalBytes())); + assertThat(expectedAdmission.get().rebindHandleSha256()) + .isEqualTo(committed.rebindHandleSha256()); + assertThat(finalReadCalls.get()).isEqualTo(4); + assertThat(observedFinalReadModes) + .containsExactly( + FinalReadMode.EXACT, + FinalReadMode.CHANGED, + FinalReadMode.UNAVAILABLE, + FinalReadMode.EXACT); + assertThat(finalReadExpectations).hasSize(4).containsOnly(expectedAdmission.get()); + assertThat(finalReadResults).hasSize(3); + assertThat(finalReadResults.get(0).anchors()).isEqualTo(finalReadResults.get(2).anchors()); + assertThat(finalReadResults.get(0).admissionAtMillis()) + .isEqualTo(finalReadResults.get(2).admissionAtMillis()); + assertThat(finalReadResults.get(0).continuityExpiresAtMillis()) + .isEqualTo(finalReadResults.get(2).continuityExpiresAtMillis()); + assertThat(finalReadResults.get(0).canonicalSessionDurationMillis()) + .isEqualTo(finalReadResults.get(2).canonicalSessionDurationMillis()); + assertThat(finalReadResults.get(0).canonicalReadbackSha256()) + .isEqualTo(finalReadResults.get(2).canonicalReadbackSha256()); + + Genesis confirmedGenesis = readGenesis(dsl, serializable, originalLease); + assertThat(confirmedGenesis.lineageId()).isEqualTo(first.lineageId()); + assertThat(confirmedGenesis.tokenJti()).isEqualTo(first.tokenJti()); + assertThat(confirmedGenesis.tokenHash()).isEqualTo(first.tokenSha256()); + assertThat(confirmedGenesis.expiresAtEpochSecond()) + .isEqualTo(committed.expiresAtEpochSecond()); + assertThat(confirmedGenesis.confirmedAdmissionAtMillis()) + .isEqualTo(controlledAdmissionAtMillis); + assertThat(confirmedGenesis.confirmedContinuityExpiresAtMillis()) + .isEqualTo(controlledAdmissionAtMillis + SESSION_DURATION_MILLIS); + assertSameActiveRegistryReadback( + activeAfterLostConfirmation, + tokenRegistry.requireExactOriginalNewActiveRecord(confirmedGenesis)); + + var sameConfirmation = confirm(owner, peer, loginJwt, originalLease); + assertThat(sameConfirmation.lineageId()).isEqualTo(confirmed.lineageId()); + assertThat(sameConfirmation.authenticatedConfirmationSha256()) + .isEqualTo(confirmed.authenticatedConfirmationSha256()); + assertThat(finalReadCalls.get()).isEqualTo(4); + + OriginalNewCredential committedRetry = + Context.current() + .withValue(GrpcPeerIdentity.CONTEXT_KEY, peer) + .call(() -> owner.issue(loginJwt, originalLease)); + try (committedRetry) { + assertThat(committedRetry.tokenSha256()).isEqualTo(first.tokenSha256()); + assertThat(committedRetry.lineageId()).isEqualTo(first.lineageId()); + assertThat(committedRetry.tokenJti()).isEqualTo(first.tokenJti()); + assertThat(committedRetry.issuanceFence()).isEqualTo(first.issuanceFence()); + assertThat(committedRetry.originalAckReceiptXid()).isEqualTo(first.originalAckReceiptXid()); + assertThat(finalReadCalls.get()).isEqualTo(4); + } + assertOriginalLeaseAndAckRemainExact(dsl, originalLease, originalEvidenceSha256); + } + } + + private AccountGameplayAdmissionLeaseEvidence commitActualOriginalNewLease( + DSLContext dsl, TransactionTemplate serializable) { + UUID accountId = sourceFixture.committedCandidate.identity().accountId(); + UUID tenantId = + dsl.fetchSingle( + "SELECT membership.tenant_uuid FROM account_tenant_membership membership " + + "JOIN accounts account ON account.id = membership.account_id " + + "WHERE account.account_uuid = ? AND membership.tenant_uuid IS NOT NULL", + accountId) + .get(0, UUID.class); + if (tenantId == null) + throw new IllegalStateException("Current-source fixture tenant is absent"); + + AccountGameplayAdmissionLeaseEvidence evidence = + serializable.execute( + status -> { + var current = + AccountGameplayAdmissionCurrentSources.bind(dsl, NAMESPACE) + .readCurrentPublicProductionNew( + tenantId, + sourceFixture.committedCandidate.identity().tokenJti(), + sourceFixture.committedCandidate); + UUID requestId = UUID.randomUUID(); + UUID leaseId = UUID.randomUUID(); + var leaseRepository = new AccountGameplayAdmissionLeaseRepository(dsl); + var allocation = leaseRepository.allocate(accountId, requestId, leaseId); + long evaluatedAt = + dsl.fetchSingle( + "SELECT floor(extract(epoch FROM clock_timestamp()) * 1000)::bigint") + .get(0, Long.class); + long maxLeaseExpiry = + Math.addExact( + evaluatedAt, AccountGameplayAdmissionLeaseEvidence.MAX_DURATION_MILLIS); + long initialTokenExpiry = + Math.multiplyExact( + sourceFixture.committedCandidate.identity().expiresAtEpochSecond(), 1_000L); + Map carrier = new LinkedHashMap<>(); + carrier.put("schema", AccountGameplayAdmissionLeaseEvidence.SCHEMA); + carrier.put("schemaVersion", "1"); + carrier.put("mode", "PUBLIC_PRODUCTION"); + carrier.put("targetNamespace", NAMESPACE); + carrier.put("callerWorkload", GAME_SESSION_WORKLOAD); + carrier.put("requestId", allocation.requestId().toString()); + carrier.put("leaseId", allocation.leaseId().toString()); + carrier.put("leaseFence", Long.toString(allocation.leaseFence())); + carrier.put("leaseKind", "NEW_BINDING"); + carrier.put( + "bindingScope", + Map.ofEntries( + Map.entry("accountId", accountId.toString()), + Map.entry("tenantId", tenantId.toString()), + Map.entry("realmId", UUID.randomUUID().toString()), + Map.entry("worldSlug", "world"), + Map.entry("realmSlug", "realm"), + Map.entry("playableStateNamespaceId", UUID.randomUUID().toString()), + Map.entry("playableStateScope", "SHARED"), + Map.entry("gameInstanceId", UUID.randomUUID().toString()), + Map.entry("characterId", UUID.randomUUID().toString()), + Map.entry("sessionId", UUID.randomUUID().toString()), + Map.entry("bindingGeneration", "1"), + Map.entry("catalogRevision", "1"), + Map.entry("pointerVersion", "1"), + Map.entry("regionId", UUID.randomUUID().toString()), + Map.entry("regionEpoch", "1"))); + carrier.putAll(current.leaseSourceFields()); + carrier.put("evaluatedAt", Long.toString(evaluatedAt)); + carrier.put("expiresAt", Long.toString(Math.min(maxLeaseExpiry, initialTokenExpiry))); + var originalLease = AccountGameplayAdmissionLeaseEvidence.fromCarrier(carrier); + leaseRepository.beginPending(originalLease); + return originalLease; + }); + + UUID decisionId = UUID.randomUUID(); + var acknowledgement = + new AccountGameplayAdmissionOriginalCommitExecutor(sourceFixture.dataSource) + .executeWithCurrentSources( + evidence, decisionId, NAMESPACE, sourceFixture.committedCandidate); + var receipt = + new AccountGameplayAdmissionOriginalAckReceiptCommitExecutor(sourceFixture.dataSource) + .confirm(acknowledgement); + assertThat(receipt.evidenceSha256()).isEqualTo(evidence.sha256()); + assertThat(receipt.bindingDecisionId()).isEqualTo(decisionId); + return evidence; + } + + private static Genesis readGenesis( + DSLContext dsl, + TransactionTemplate transaction, + AccountGameplayAdmissionLeaseEvidence originalLease) { + return transaction.execute( + status -> + new AccountOriginalNewBoundGameplayIssuanceRepository(dsl) + .readByLease(UUID.fromString((String) originalLease.carrier().get("leaseId")))); + } + + private static AccountOriginalNewBoundGameplayCredentialOwner.OriginalAdmissionConfirmation + confirm( + AccountOriginalNewBoundGameplayCredentialOwner owner, + GrpcPeerIdentity peer, + String loginJwt, + AccountGameplayAdmissionLeaseEvidence originalLease) + throws Exception { + return Context.current() + .withValue(GrpcPeerIdentity.CONTEXT_KEY, peer) + .call(() -> owner.confirmOriginalFinalAdmission(loginJwt, originalLease)); + } + + private static void assertFinalConfirmationUnavailable( + AccountOriginalNewBoundGameplayCredentialOwner owner, + GrpcPeerIdentity peer, + String loginJwt, + AccountGameplayAdmissionLeaseEvidence originalLease) + throws Exception { + assertThatThrownBy(() -> confirm(owner, peer, loginJwt, originalLease)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Original-new bound gameplay credential is unavailable"); + } + + private static Genesis assertUnconfirmed( + DSLContext dsl, + TransactionTemplate transaction, + AccountGameplayAdmissionLeaseEvidence originalLease) { + Genesis unconfirmed = readGenesis(dsl, transaction, originalLease); + assertThat(unconfirmed.confirmedAdmissionAtMillis()).isNull(); + assertThat(unconfirmed.confirmedContinuityExpiresAtMillis()).isNull(); + assertThat(unconfirmed.confirmationReadbackSha256()).isNull(); + return unconfirmed; + } + + private static void assertSameActiveRegistryReadback( + ActiveRegistryReadback expected, ActiveRegistryReadback actual) { + assertThat(actual.tokenHash()).isEqualTo(expected.tokenHash()); + assertThat(actual.accountId()).isEqualTo(expected.accountId()); + assertThat(actual.jti()).isEqualTo(expected.jti()); + assertThat(actual.tokenExpiryEpochSecond()).isEqualTo(expected.tokenExpiryEpochSecond()); + assertThat(actual.absoluteExpiryMillis()).isEqualTo(expected.absoluteExpiryMillis()); + assertThat(actual.canonicalPendingRecordSha256()) + .isEqualTo(expected.canonicalPendingRecordSha256()); + } + + private static ExpectedOriginalAdmission changedTokenHash(ExpectedOriginalAdmission expected) { + String changedTokenHash = + (expected.tokenSha256().startsWith("0") ? "1" : "0") + expected.tokenSha256().substring(1); + return new ExpectedOriginalAdmission( + expected.requestId(), + expected.accountId(), + expected.tenantId(), + expected.sessionId(), + expected.bindingDecisionId(), + expected.originalLeaseId(), + expected.originalLeaseFence(), + expected.originalLeaseEvidenceSha256(), + expected.lineageId(), + expected.tokenJti(), + changedTokenHash, + expected.tokenGeneration(), + expected.issuanceFence(), + expected.bindingScopeSha256(), + expected.membershipBaselineSha256(), + expected.checkpointsSha256(), + expected.rebindHandleSha256()); + } + + private static void installOwnedConfirmationUpdateFailure(DSLContext dsl) { + dsl.execute( + "CREATE FUNCTION " + + CONFIRMATION_FAULT_FUNCTION + + "() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN " + + "RAISE EXCEPTION 'controlled owned original-new confirmation SQL fault'; " + + "RETURN NEW; END; $$"); + dsl.execute( + "CREATE TRIGGER " + + CONFIRMATION_FAULT_TRIGGER + + " BEFORE UPDATE ON account_original_new_bound_gameplay_issuances " + + "FOR EACH ROW WHEN (OLD.confirmed_admission_at_ms IS NULL " + + "AND NEW.confirmed_admission_at_ms IS NOT NULL) EXECUTE FUNCTION " + + CONFIRMATION_FAULT_FUNCTION + + "()"); + } + + private static void removeOwnedConfirmationUpdateFailure(DSLContext dsl) { + dsl.execute( + "DROP TRIGGER " + + CONFIRMATION_FAULT_TRIGGER + + " ON account_original_new_bound_gameplay_issuances"); + dsl.execute("DROP FUNCTION " + CONFIRMATION_FAULT_FUNCTION + "()"); + } + + private static TokenIdentity activeIdentity(DSLContext dsl, Genesis genesis) { + TokenIdentity exact = + new TokenIdentity( + genesis.accountId(), + genesis.lineageId(), + genesis.requestId(), + genesis.tokenHash(), + genesis.tokenJti(), + genesis.notBeforeEpochSecond(), + genesis.tokenGeneration(), + genesis.issuanceFence(), + SourceKind.ORIGINAL_NEW); + return new AccountGameplayTokenIdentityFenceRepository(dsl) + .requireActiveReadback(exact) + .identity(); + } + + private static void assertExactLeaseSource( + Genesis genesis, AccountGameplayAdmissionLeaseEvidence lease, String field) throws Exception { + byte[] actual = + switch (field) { + case "authorityTuple" -> genesis.authorityTupleCanonicalBytes(); + case "membershipBaseline" -> genesis.membershipBaselineCanonicalBytes(); + case "outboxCheckpoints" -> genesis.outboxCheckpointsCanonicalBytes(); + default -> throw new IllegalArgumentException("Unsupported original lease source field"); + }; + byte[] expected = canonicalBytes(lease.carrier().get(field)); + try { + assertThat(actual).containsExactly(expected); + } finally { + Arrays.fill(actual, (byte) 0); + Arrays.fill(expected, (byte) 0); + } + } + + private static void assertOriginalLeaseAndAckRemainExact( + DSLContext dsl, + AccountGameplayAdmissionLeaseEvidence originalLease, + String originalEvidenceSha256) { + UUID requestId = UUID.fromString((String) originalLease.carrier().get("requestId")); + var operation = + dsl.fetchSingle( + "SELECT evidence_sha256, evidence_json, status " + + "FROM account_gameplay_admission_lease_operations WHERE request_id = ?", + requestId); + assertThat(operation.get("evidence_sha256", String.class)).isEqualTo(originalEvidenceSha256); + assertThat(operation.get("evidence_json", String.class)) + .isEqualTo(originalLease.canonicalJson()); + assertThat(operation.get("status", String.class)).isEqualTo("COMMITTED"); + var receipt = + dsl.fetchSingle( + "SELECT evidence_sha256, lease_id, lease_fence FROM " + + "account_gameplay_admission_original_commit_ack_receipts WHERE request_id = ?", + requestId); + assertThat(receipt.get("evidence_sha256", String.class)).isEqualTo(originalEvidenceSha256); + assertThat(receipt.get("lease_id", UUID.class)) + .isEqualTo(UUID.fromString((String) originalLease.carrier().get("leaseId"))); + assertThat(receipt.get("lease_fence", Long.class)) + .isEqualTo(originalLease.leaseFence().longValueExact()); + } + + private static AccountResponseEnvelopeCryptography testResponseCryptography(Path keyringRoot) + throws Exception { + Files.createDirectories(keyringRoot); + byte[] key = new byte[32]; + for (int index = 0; index < key.length; index++) key[index] = (byte) (index + 1); + try { + String encoded = Base64.getUrlEncoder().withoutPadding().encodeToString(key); + Files.writeString( + keyringRoot.resolve("keyring"), + "firemud-account-response-envelope-keyring-v1\nactive integration-key " + encoded + "\n", + StandardCharsets.US_ASCII); + return new AccountResponseEnvelopeCryptography( + new AccountResponseEnvelopeKeyring(keyringRoot.toString())); + } finally { + Arrays.fill(key, (byte) 0); + } + } + + private static String sha256(byte[] bytes) throws Exception { + return java.util.HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } + + private static byte[] canonicalBytes(Object value) throws Exception { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } + + private static String sha256AndWipe(byte[] bytes) throws Exception { + try { + return sha256(bytes); + } finally { + Arrays.fill(bytes, (byte) 0); + } + } + + private enum FinalReadMode { + EXACT, + CHANGED, + UNAVAILABLE + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptCommitExecutorTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptCommitExecutorTest.java index b3bba74e0b..09b34f2311 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptCommitExecutorTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptCommitExecutorTest.java @@ -18,6 +18,7 @@ import java.sql.Connection; import java.sql.DatabaseMetaData; +import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; @@ -42,6 +43,11 @@ * JDBC/repository/opaque-ACK doubles; not PostgreSQL durability, authentication or admission proof. */ class AccountGameplayAdmissionOriginalAckReceiptCommitExecutorTest { + private static final String WAL_UPPER_FENCE = "0/16B6C50"; + private static final String WAL_COVERAGE_SQL = + "SELECT current_setting('server_version_num')::integer, pg_is_in_recovery(), " + + "current_setting('fsync'), pg_current_wal_flush_lsn() >= ?::pg_lsn"; + @AfterEach void clearTransaction() { for (Object key : TransactionSynchronizationManager.getResourceMap().keySet()) { @@ -86,6 +92,15 @@ void creationApiAcceptsOnlyOpaqueAcknowledgement() { .containsExactly(java.util.List.of(OriginalCommitAcknowledgement.class)); } + @Test + void historicalPendingReceiptConstructorRemainsPrivate() { + var constructors = + AccountGameplayAdmissionOriginalAckReceiptRepository.PendingHistoricalReceipt.class + .getDeclaredConstructors(); + assertThat(constructors).hasSize(1); + assertThat(java.lang.reflect.Modifier.isPrivate(constructors[0].getModifiers())).isTrue(); + } + @Test void anotherDataSourceIsRejectedBeforeAnyConnection() throws Exception { var fixture = new Fixture(); @@ -126,33 +141,42 @@ void changedOriginalProofRollsBackWithoutIndependentRead(String fault) throws Ex } @Test - void retryCommitCannotSubstituteForUnavailableHistoricalDurability() throws Exception { + void retryCommitCannotSubstituteForUnavailableHistoricalFenceCoverage() throws Exception { var fixture = new Fixture(); fixture.inserted = false; - fixture.failRead = true; + fixture.flush.covered = false; + fixture.prepareHistoricalRead(true); try (var repositories = fixture.repositories()) { assertThatThrownBy(() -> fixture.executor.confirm(fixture.acknowledgement)) - .hasMessage("read unavailable"); + .hasMessageContaining("WAL coverage unavailable"); verify(fixture.first.connection).commit(); - verify(repositories.constructed().get(1)).readDurably(fixture.evidence, fixture.decision); + verify(repositories.constructed().get(1)) + .captureHistorical(fixture.evidence, fixture.decision); + verify(repositories.constructed().get(1), never()).readExact(any(), any()); verify(repositories.constructed().get(1), never()).create(any()); - verify(fixture.second.connection, never()).commit(); + verify(repositories.constructed().get(1), never()).readDurably(any(), any()); + assertThat(repositories.constructed()).hasSize(2); + verify(fixture.second.connection).commit(); + verify(fixture.second.connection).close(); + verify(fixture.flush.connection).close(); + verifyNoInteractions(fixture.fourth.connection); } } @Test - void retainedReceiptUsesHistoricalDurabilityRatherThanRetryCommitProof() throws Exception { + void retainedReceiptUsesFrozenFenceCoverageAndExactReread() throws Exception { var fixture = new Fixture(); fixture.inserted = false; + fixture.prepareHistoricalRead(true); try (var repositories = fixture.repositories()) { assertThat(fixture.executor.confirm(fixture.acknowledgement)).isSameAs(fixture.receipt); - var read = repositories.constructed().get(1); - verify(read).readDurably(fixture.evidence, fixture.decision); - verify(read, never()).readExact(any(), any()); + var capture = repositories.constructed().get(1); + var read = repositories.constructed().get(2); + verify(capture).captureHistorical(fixture.evidence, fixture.decision); + verify(read).readExact(fixture.evidence, fixture.decision); + verify(capture, never()).readDurably(any(), any()); verify(read, never()).create(any()); - int[] closes = invocationSequences(fixture.first.connection, "close"); - int[] reads = invocationSequences(read, "readDurably"); - assertThat(reads[0]).isGreaterThan(closes[0]); + assertHistoricalReadSequence(fixture, capture, read, true); } } @@ -240,14 +264,76 @@ void poolMayReuseConnectionAfterCompletedCommitAndCleanup() throws Exception { @Test void readOnlyValidatesExistingReceipt() throws Exception { var fixture = new Fixture(); + fixture.prepareHistoricalRead(false); try (var repositories = fixture.repositories()) { assertThat(fixture.executor.read(fixture.evidence, fixture.decision)) .isSameAs(fixture.receipt); - verify(repositories.constructed().getFirst(), never()).create(any()); + var capture = repositories.constructed().getFirst(); + var read = repositories.constructed().get(1); + verify(capture, never()).create(any()); + verify(capture).captureHistorical(fixture.evidence, fixture.decision); + verify(read).readExact(fixture.evidence, fixture.decision); + verify(capture, never()).readDurably(any(), any()); + verify(fixture.first.connection).commit(); + assertHistoricalReadSequence(fixture, capture, read, false); + } + } + + @ParameterizedTest + @ValueSource(strings = {"coverage", "sql", "version", "recovery", "fsync", "autocommit"}) + void historicalReadDoesNotReachExactRereadWithoutValidFenceCoverage(String fault) + throws Exception { + var fixture = new Fixture(); + fixture.prepareHistoricalRead(false); + switch (fault) { + case "coverage" -> fixture.flush.covered = false; + case "sql" -> fixture.flush.failFenceQuery = true; + case "version" -> when(fixture.flush.fenceResult.getInt(1)).thenReturn(160000); + case "recovery" -> when(fixture.flush.fenceResult.getBoolean(2)).thenReturn(true); + case "fsync" -> when(fixture.flush.fenceResult.getString(3)).thenReturn("off"); + case "autocommit" -> when(fixture.flush.connection.getAutoCommit()).thenReturn(false); + default -> throw new IllegalArgumentException(fault); + } + try (var repositories = fixture.repositories()) { + assertThatThrownBy(() -> fixture.executor.read(fixture.evidence, fixture.decision)) + .isInstanceOf(RuntimeException.class); + assertThat(repositories.constructed()).hasSize(1); + verify(repositories.constructed().getFirst()) + .captureHistorical(fixture.evidence, fixture.decision); verify(repositories.constructed().getFirst(), never()).readExact(any(), any()); - verify(repositories.constructed().getFirst()).readDurably(fixture.evidence, fixture.decision); verify(fixture.first.connection).commit(); - verifyNoInteractions(fixture.second.connection); + verify(fixture.first.connection).close(); + verify(fixture.flush.connection).close(); + verifyNoInteractions(fixture.third.connection); + } + } + + @Test + void historicalReadDoesNotExposeReceiptWhenIndependentExactRereadChanges() throws Exception { + var fixture = new Fixture(); + fixture.prepareHistoricalRead(false); + var r = fixture.receipt; + fixture.readReceipt = + new AccountGameplayAdmissionOriginalAckReceipt( + r.operation(), + r.schemaVersion(), + r.requestId(), + r.accountId(), + r.leaseId(), + r.leaseFence(), + r.evidenceSha256(), + r.bindingDecisionId(), + r.expiresAtMs(), + r.finalizationXid(), + r.committedBeforeMs(), + "123458"); + try (var repositories = fixture.repositories()) { + assertThatThrownBy(() -> fixture.executor.read(fixture.evidence, fixture.decision)) + .hasMessageContaining("Fresh owned"); + assertThat(repositories.constructed()).hasSize(2); + verify(repositories.constructed().get(1)).readExact(fixture.evidence, fixture.decision); + verify(fixture.third.connection).commit(); + verify(fixture.third.connection, never()).rollback(); } } @@ -333,6 +419,47 @@ private static void assertIndependentAcquisition( assertThat(acquisitions[1]).isLessThan(reads[0]); } + private static void assertHistoricalReadSequence( + Fixture fixture, + AccountGameplayAdmissionOriginalAckReceiptRepository capture, + AccountGameplayAdmissionOriginalAckReceiptRepository read, + boolean creationPrecededCapture) + throws SQLException { + Jdbc captureJdbc = creationPrecededCapture ? fixture.second : fixture.first; + Jdbc flushJdbc = fixture.flush; + Jdbc finalReadJdbc = creationPrecededCapture ? fixture.fourth : fixture.third; + int[] captureCalls = invocationSequences(capture, "captureHistorical"); + int[] captureCommits = invocationSequences(captureJdbc.connection, "commit"); + int[] captureCloses = invocationSequences(captureJdbc.connection, "close"); + int[] fenceQueries = invocationSequences(flushJdbc.connection, "prepareStatement"); + int[] fenceParameters = invocationSequences(flushJdbc.fenceStatement, "setString"); + int[] fenceExecutions = invocationSequences(flushJdbc.fenceStatement, "executeQuery"); + int[] fenceCloses = invocationSequences(flushJdbc.connection, "close"); + int[] exactReads = invocationSequences(read, "readExact"); + int[] finalCommits = invocationSequences(finalReadJdbc.connection, "commit"); + + assertThat(captureCalls).hasSize(1); + assertThat(captureCommits).hasSize(1); + assertThat(captureCloses).hasSize(1); + assertThat(fenceQueries).hasSize(1); + assertThat(fenceParameters).hasSize(1); + assertThat(fenceExecutions).hasSize(1); + assertThat(fenceCloses).hasSize(1); + assertThat(exactReads).hasSize(1); + assertThat(finalCommits).hasSize(1); + assertThat(captureCalls[0]).isLessThan(captureCommits[0]); + assertThat(captureCommits[0]).isLessThan(captureCloses[0]); + assertThat(captureCloses[0]).isLessThan(fenceQueries[0]); + assertThat(fenceQueries[0]).isLessThan(fenceParameters[0]); + assertThat(fenceParameters[0]).isLessThan(fenceExecutions[0]); + assertThat(fenceExecutions[0]).isLessThan(fenceCloses[0]); + assertThat(fenceCloses[0]).isLessThan(exactReads[0]); + assertThat(exactReads[0]).isLessThan(finalCommits[0]); + verify(capture).captureHistorical(fixture.evidence, fixture.decision); + verify(fixture.pending).walUpperFence(); + verify(flushJdbc.fenceStatement).setString(1, WAL_UPPER_FENCE); + } + private static int[] invocationSequences(Object mock, String method) { return mockingDetails(mock).getInvocations().stream() .filter(invocation -> invocation.getMethod().getName().equals(method)) @@ -344,6 +471,9 @@ private static final class Fixture { private final DataSource source = mock(DataSource.class); private final Jdbc first = new Jdbc(); private final Jdbc second = new Jdbc(); + private final Jdbc third = new Jdbc(); + private final Jdbc fourth = new Jdbc(); + private final Jdbc flush = new Jdbc(); private Connection readConnection = second.connection; private final AccountGameplayAdmissionLeaseEvidence evidence = AccountGameplayAdmissionOriginalAckReceiptTestFixtures.fixture(); @@ -351,15 +481,26 @@ private static final class Fixture { private final OriginalCommitAcknowledgement acknowledgement = mock(OriginalCommitAcknowledgement.class); private final AccountGameplayAdmissionOriginalAckReceipt receipt = receipt(evidence, decision); + // Unit-only mock of the private pending capability; the production constructor is asserted + // private by historicalPendingReceiptConstructorRemainsPrivate. + private final AccountGameplayAdmissionOriginalAckReceiptRepository.PendingHistoricalReceipt + pending = + mock( + AccountGameplayAdmissionOriginalAckReceiptRepository.PendingHistoricalReceipt + .class); private boolean inserted = true; private AccountGameplayAdmissionOriginalAckReceipt readReceipt = receipt; private boolean failRead; private String creationFault; + private boolean historicalRead; + private boolean historicalAfterCreate; private final AccountGameplayAdmissionOriginalAckReceiptCommitExecutor executor = new AccountGameplayAdmissionOriginalAckReceiptCommitExecutor(source); private Fixture() throws SQLException { when(source.getConnection()).thenReturn(first.connection, second.connection); + when(pending.receipt()).thenReturn(receipt); + when(pending.walUpperFence()).thenReturn(WAL_UPPER_FENCE); when(acknowledgement.belongsTo(source)).thenReturn(true); when(acknowledgement.evidence()).thenReturn(evidence); when(acknowledgement.decisionId()).thenReturn(decision); @@ -367,6 +508,18 @@ private Fixture() throws SQLException { when(acknowledgement.committedBeforeMs()).thenReturn(receipt.committedBeforeMs()); } + private void prepareHistoricalRead(boolean afterCreate) throws SQLException { + historicalRead = true; + historicalAfterCreate = afterCreate; + if (afterCreate) { + when(source.getConnection()) + .thenReturn(first.connection, second.connection, flush.connection, fourth.connection); + } else { + when(source.getConnection()) + .thenReturn(first.connection, flush.connection, third.connection); + } + } + private MockedConstruction repositories() { return mockConstruction( @@ -374,8 +527,7 @@ private Fixture() throws SQLException { (repository, context) -> { DSLContext dsl = (DSLContext) context.arguments().getFirst(); Connection enlisted = dsl.connectionResult(value -> value); - assertThat(enlisted) - .isSameAs(context.getCount() == 1 ? first.connection : readConnection); + assertThat(enlisted).isSameAs(repositoryConnection(context.getCount())); assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); assertThat(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel()) @@ -406,9 +558,27 @@ yield receipt( }); when(repository.readExact(evidence, decision)).thenAnswer(ignored -> readResult()); when(repository.readDurably(evidence, decision)).thenAnswer(ignored -> readResult()); + when(repository.captureHistorical(evidence, decision)).thenReturn(pending); }); } + private Connection repositoryConnection(int count) { + if (!historicalRead) return count == 1 ? first.connection : readConnection; + if (historicalAfterCreate) { + return switch (count) { + case 1 -> first.connection; + case 2 -> second.connection; + case 3 -> fourth.connection; + default -> throw new IllegalArgumentException("Unexpected repository " + count); + }; + } + return switch (count) { + case 1 -> first.connection; + case 2 -> third.connection; + default -> throw new IllegalArgumentException("Unexpected repository " + count); + }; + } + private AccountGameplayAdmissionOriginalAckReceipt readResult() { if (failRead) throw new IllegalStateException("read unavailable"); return readReceipt; @@ -423,6 +593,19 @@ private static AccountGameplayAdmissionOriginalAckReceipt receipt( private static final class Jdbc { private final DatabaseMetaData metadata = mock(DatabaseMetaData.class); private final ResultSet settings = mock(ResultSet.class); + private final ResultSet fenceResult = mock(ResultSet.class); + private boolean covered = true; + private boolean failFenceQuery; + private final PreparedStatement fenceStatement = + mock( + PreparedStatement.class, + invocation -> { + if (invocation.getMethod().getName().equals("executeQuery")) { + if (failFenceQuery) throw new SQLException("flush observation unavailable"); + return fenceResult; + } + return Answers.RETURNS_DEFAULTS.answer(invocation); + }); private final Statement statement = mock( Statement.class, @@ -437,9 +620,11 @@ private static final class Jdbc { mock( Connection.class, invocation -> - invocation.getMethod().getName().equals("createStatement") - ? statement - : Answers.RETURNS_DEFAULTS.answer(invocation)); + switch (invocation.getMethod().getName()) { + case "createStatement" -> statement; + case "prepareStatement" -> fenceStatement; + default -> Answers.RETURNS_DEFAULTS.answer(invocation); + }); private boolean badIsolation; private boolean badAutoCommit; @@ -471,6 +656,20 @@ private Jdbc() throws SQLException { when(settings.getString(4)).thenReturn("on"); when(settings.getString(5)).thenReturn("serializable"); when(settings.getString(6)).thenReturn("off"); + when(fenceResult.next()) + .thenAnswer( + new org.mockito.stubbing.Answer() { + private final AtomicInteger row = new AtomicInteger(); + + @Override + public Boolean answer(org.mockito.invocation.InvocationOnMock ignored) { + return row.getAndIncrement() % 2 == 0; + } + }); + when(fenceResult.getInt(1)).thenReturn(180011); + when(fenceResult.getBoolean(2)).thenReturn(false); + when(fenceResult.getString(3)).thenReturn("on"); + when(fenceResult.getBoolean(4)).thenAnswer(ignored -> covered); } } } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayTokenIdentityFenceRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayTokenIdentityFenceRepositoryTest.java index 2a03eac2fb..079de0a485 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayTokenIdentityFenceRepositoryTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayTokenIdentityFenceRepositoryTest.java @@ -14,6 +14,7 @@ import java.lang.reflect.Modifier; import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.AccountGameplayTokenIdentityFence.SourceKind; import net.firedevops.firemud.accountservice.dto.AccountGameplayTokenIdentityFence.State; import net.firedevops.firemud.accountservice.dto.AccountGameplayTokenIdentityFence.TokenIdentity; import net.firedevops.firemud.accountservice.repository.AccountGameplayTokenIdentityFenceRepository; @@ -92,7 +93,7 @@ void activeReadLocksAccountBeforeTokenAndIndependentlyReadsExactCommittedSource( .verify(dsl) .fetchOne( "SELECT account_uuid, operation_id, issuance_request_id, token_hash, token_jti, " - + "not_before_epoch_second, token_generation, issuance_fence, token_identity_fence, " + + "not_before_epoch_second, token_generation, issuance_fence, source_kind, token_identity_fence, " + "state, revocation_request_id, revocation_digest " + "FROM account_gameplay_token_identity_fences WHERE operation_id = ? FOR UPDATE", IDENTITY.operationId()); @@ -127,6 +128,52 @@ void missingCommittedSourceCannotAuthorizeEvenWithActiveTokenRow() { .isInstanceOf(TokenFenceUnavailableException.class); } + @Test + void originalNewFenceReadsOnlyItsSeparateCommittedLineageAndIgnoresLoginDisposal() { + DSLContext dsl = mock(DSLContext.class); + TokenIdentity originalNew = + new TokenIdentity( + IDENTITY.accountId(), + IDENTITY.operationId(), + IDENTITY.issuanceRequestId(), + IDENTITY.tokenSha256(), + IDENTITY.tokenJti(), + IDENTITY.notBeforeEpochSecond(), + 1L, + IDENTITY.issuanceFence(), + SourceKind.ORIGINAL_NEW); + Record account = mock(Record.class); + Record token = tokenRow(State.ACTIVE, originalNew); + Record source = mock(Record.class); + when(dsl.fetchOne( + "SELECT account_uuid FROM accounts WHERE account_uuid = ? FOR UPDATE", + originalNew.accountId())) + .thenReturn(account); + when(dsl.fetchOne( + "SELECT account_uuid, operation_id, issuance_request_id, token_hash, token_jti, " + + "not_before_epoch_second, token_generation, issuance_fence, source_kind, token_identity_fence, " + + "state, revocation_request_id, revocation_digest " + + "FROM account_gameplay_token_identity_fences WHERE operation_id = ? FOR UPDATE", + originalNew.operationId())) + .thenReturn(token); + when(dsl.fetchOne( + startsWith("SELECT operation_id FROM account_original_new_bound_gameplay_issuances "), + any(Object[].class))) + .thenReturn(source); + transaction(); + + var fence = + new AccountGameplayTokenIdentityFenceRepository(dsl).requireActiveForUpdate(originalNew); + + assertThat(fence.identity().sourceKind()).isEqualTo(SourceKind.ORIGINAL_NEW); + assertThat(fence.tokenIdentityFence()).isEqualTo(1L); + verify(dsl, never()).fetchOne(DISPOSAL_GUARD_SELECT, originalNew.issuanceRequestId()); + verify(dsl, never()) + .fetchOne( + startsWith("SELECT operation_id FROM account_gameplay_delegation_issuance_operations "), + any(Object[].class)); + } + @Test void exactIdentityMismatchCannotUseAnotherActiveFence() { DSLContext dsl = mock(DSLContext.class); @@ -374,16 +421,21 @@ void callerClaimedDigestCannotStartRevocationOrAcquireLocks() { } private static Record tokenRow(State state) { + return tokenRow(state, IDENTITY); + } + + private static Record tokenRow(State state, TokenIdentity identity) { Record row = mock(Record.class); - when(row.get("account_uuid", UUID.class)).thenReturn(IDENTITY.accountId()); - when(row.get("operation_id", UUID.class)).thenReturn(IDENTITY.operationId()); - when(row.get("issuance_request_id", UUID.class)).thenReturn(IDENTITY.issuanceRequestId()); - when(row.get("token_hash", String.class)).thenReturn(IDENTITY.tokenSha256()); - when(row.get("token_jti", UUID.class)).thenReturn(IDENTITY.tokenJti()); + when(row.get("account_uuid", UUID.class)).thenReturn(identity.accountId()); + when(row.get("operation_id", UUID.class)).thenReturn(identity.operationId()); + when(row.get("issuance_request_id", UUID.class)).thenReturn(identity.issuanceRequestId()); + when(row.get("token_hash", String.class)).thenReturn(identity.tokenSha256()); + when(row.get("token_jti", UUID.class)).thenReturn(identity.tokenJti()); when(row.get("not_before_epoch_second", Long.class)) - .thenReturn(IDENTITY.notBeforeEpochSecond()); - when(row.get("token_generation", Long.class)).thenReturn(IDENTITY.tokenGeneration()); - when(row.get("issuance_fence", Long.class)).thenReturn(IDENTITY.issuanceFence()); + .thenReturn(identity.notBeforeEpochSecond()); + when(row.get("token_generation", Long.class)).thenReturn(identity.tokenGeneration()); + when(row.get("issuance_fence", Long.class)).thenReturn(identity.issuanceFence()); + when(row.get("source_kind", String.class)).thenReturn(identity.sourceKind().name()); when(row.get("state", String.class)).thenReturn(state.name()); when(row.get("token_identity_fence", Long.class)) .thenReturn(state == State.ACTIVE ? 1L : state == State.PENDING ? 2L : 3L); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountOriginalNewBoundGameplayCredentialOwnerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountOriginalNewBoundGameplayCredentialOwnerTest.java new file mode 100644 index 0000000000..30f2a85f32 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountOriginalNewBoundGameplayCredentialOwnerTest.java @@ -0,0 +1,50 @@ +package net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; + +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneOffset; +import javax.sql.DataSource; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayAdmissionCallerVerifier; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationSigner; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationTokenRegistry; +import net.firedevops.firemud.accountservice.service.session.AccountResponseEnvelopeCryptography; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class AccountOriginalNewBoundGameplayCredentialOwnerTest { + @AfterEach + void clearTransactionContext() { + TransactionSynchronizationManager.clear(); + } + + @Test + void finalConfirmationFailsClosedUntilProtectedGsReadbackIsWired() { + DataSource dataSource = mock(DataSource.class); + AccountGameplayAdmissionCallerVerifier callerVerifier = + mock(AccountGameplayAdmissionCallerVerifier.class); + AccountGameplayDelegationSigner signer = mock(AccountGameplayDelegationSigner.class); + AccountGameplayDelegationTokenRegistry tokenRegistry = + mock(AccountGameplayDelegationTokenRegistry.class); + AccountResponseEnvelopeCryptography responseCryptography = + mock(AccountResponseEnvelopeCryptography.class); + var owner = + new AccountOriginalNewBoundGameplayCredentialOwner( + dataSource, + "test", + callerVerifier, + signer, + tokenRegistry, + responseCryptography, + Clock.fixed(Instant.parse("2026-10-27T00:00:00Z"), ZoneOffset.UTC)); + + assertThatThrownBy(() -> owner.confirmOriginalFinalAdmission("unlogged-test-token", null)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Original-new bound gameplay credential is unavailable"); + verifyNoInteractions(dataSource, callerVerifier, signer, tokenRegistry, responseCryptography); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationSignerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationSignerTest.java index 447680ddc7..fa42afe6de 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationSignerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationSignerTest.java @@ -1,5 +1,6 @@ package net.firedevops.firemud.accountservice.service.session; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; @@ -31,6 +32,7 @@ import java.util.Arrays; import java.util.Base64; import java.util.HexFormat; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Optional; @@ -87,10 +89,12 @@ import org.springframework.transaction.support.DefaultTransactionStatus; import org.springframework.transaction.support.TransactionSynchronizationManager; import org.springframework.transaction.support.TransactionTemplate; +import tools.jackson.databind.json.JsonMapper; class AccountGameplayDelegationSignerTest { private static final Instant NOW = Instant.parse("2026-10-05T00:00:00Z"); private static final Clock CLOCK = Clock.fixed(NOW, ZoneOffset.UTC); + private static final JsonMapper JSON = JsonMapper.builder().build(); private static final String ENVIRONMENT = "staging"; private static final String CLUSTER = "cluster-a"; private static final String NAMESPACE = "firemud"; @@ -136,6 +140,22 @@ private static synchronized void ensureEphemeralRsaPairs() throws Exception { mismatchedPair = generator.generateKeyPair(); } + private static Map jwtClaims(byte[] compactJwt) throws Exception { + String[] parts = new String(compactJwt, StandardCharsets.US_ASCII).split("\\.", -1); + assertEquals(3, parts.length); + return JSON.readValue(Base64.getUrlDecoder().decode(parts[1]), Map.class); + } + + private static Map castClaims(Map claims) { + Map copy = new LinkedHashMap<>(); + claims.forEach( + (key, value) -> { + if (!(key instanceof String text)) throw new AssertionError("JWT claim key is not text"); + copy.put(text, value); + }); + return copy; + } + @Test void remainsUnwiredAndFailsClosedWithoutProtectedSignerTrust() { AccountGameplayDelegationIssuanceRepository issuance = @@ -175,6 +195,86 @@ void remainsUnwiredAndFailsClosedWithoutProtectedSignerTrust() { verifyNoInteractions(configMapClient); } + @Test + void originalNewCredentialUsesBoundClaimsWhileLoginRetainsItsUnscopedShape() throws Exception { + Fixture fixture = new Fixture(temporaryDirectory, false); + UUID tenantId = UUID.fromString("22222222-2222-4222-8222-222222222222"); + Map tuple = + new LinkedHashMap<>(GameSessionAccountDelegationProfile.authorityTuple(1L, 1L)); + tuple.put("tenantAuthorityGeneration", Map.of(tenantId.toString(), "3")); + tuple.put("membershipAuthorityGeneration", Map.of(tenantId.toString(), "8")); + var bound = + new AccountMountedJwtSignerBundle.BoundDelegationClaims( + tenantId.toString(), tuple, Map.of(tenantId.toString(), "8")); + + assertThrows( + net.firedevops.firemud.common.security.AccountAsymmetricJwtVerifier.VerificationException + .class, + () -> + new AccountMountedJwtSignerBundle.BoundDelegationClaims( + tenantId.toString(), + GameSessionAccountDelegationProfile.authorityTuple(1L, 1L), + Map.of())); + + AtomicReference loginJwt = new AtomicReference<>(); + AccountMountedJwtSignerBundle.signCommittedGameplayDelegationDigest( + fixture.privateRoot, + Path.of("current.key"), + fixture.publicRoot, + Path.of("jwks.json"), + fixture.mountedIdentity, + new AccountMountedJwtSignerBundle.DelegationSigningSpec( + fixture.pendingIdentity, fixture.authoritySnapshot), + (digest, compact) -> loginJwt.set(compact.clone())); + + UUID lineageId = UUID.randomUUID(); + UUID boundJti = UUID.randomUUID(); + while (lineageId.equals(boundJti) || boundJti.equals(TOKEN_JTI)) { + boundJti = UUID.randomUUID(); + } + AtomicReference boundJwt = new AtomicReference<>(); + var result = + AccountMountedJwtSignerBundle.signOriginalNewBoundGameplayDelegationDigest( + fixture.privateRoot, + Path.of("current.key"), + fixture.publicRoot, + Path.of("jwks.json"), + fixture.mountedIdentity, + new AccountMountedJwtSignerBundle.OriginalNewBoundDelegationSigningSpec( + lineageId, + REQUEST_ID, + ACCOUNT_ID, + boundJti, + NOW.getEpochSecond(), + NOW.getEpochSecond(), + NOW.plusSeconds(120).getEpochSecond(), + fixture.authoritySnapshot.issuanceFence(), + fixture.authoritySnapshot, + bound), + (digest, compact) -> boundJwt.set(compact.clone())); + + Map loginClaims = jwtClaims(loginJwt.get()); + Map boundClaims = jwtClaims(boundJwt.get()); + assertThat(result.issuanceOperationId()).isEqualTo(lineageId); + assertThat(result.jti()).isEqualTo(boundJti); + assertThat(boundClaims.get("tenantId")).isEqualTo(tenantId.toString()); + assertThat(boundClaims.get("tokenGeneration")).isEqualTo("1"); + assertThat(boundClaims.get("issuanceFence")).isEqualTo("1"); + assertThat(boundClaims.get("authorityTuple")).isEqualTo(tuple); + assertThat(boundClaims.get("membershipVersion")).isEqualTo(Map.of(tenantId.toString(), "8")); + assertThat(boundClaims.containsKey("globalRoles")).isFalse(); + assertThat(boundClaims.containsKey("scopedRoles")).isFalse(); + assertThat(loginClaims.containsKey("tenantId")).isFalse(); + assertThat(loginClaims.get("membershipVersion")).isEqualTo(Map.of()); + assertThat(loginClaims.get("tokenGeneration")).isEqualTo("1"); + net.firedevops.firemud.common.security.GameSessionAccountDelegationJwtProfileValidator + .validateClaims(castClaims(boundClaims)); + assertThat(result.toString()) + .doesNotContain(new String(boundJwt.get(), StandardCharsets.US_ASCII)); + Arrays.fill(loginJwt.get(), (byte) 0); + Arrays.fill(boundJwt.get(), (byte) 0); + } + @Test void signsCanonicalPendingCandidateAndSealsOnlyMetadataWithLiveSourceOutsideTransactions() throws Exception { diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/account/admission/AccountGameplayAdmissionLeaseGrpcCodec.java b/services/common-security/src/main/java/net/firedevops/firemud/common/account/admission/AccountGameplayAdmissionLeaseGrpcCodec.java index 97799f0d09..80853d6e24 100644 --- a/services/common-security/src/main/java/net/firedevops/firemud/common/account/admission/AccountGameplayAdmissionLeaseGrpcCodec.java +++ b/services/common-security/src/main/java/net/firedevops/firemud/common/account/admission/AccountGameplayAdmissionLeaseGrpcCodec.java @@ -20,15 +20,22 @@ import net.firedevops.firemud.account.v1.AccountGameplayAdmissionLeaseState; import net.firedevops.firemud.account.v1.AccountGameplayAdmissionOriginalAckReceiptEvidence; import net.firedevops.firemud.account.v1.AcquireGameplayAdmissionLeaseRequest; +import net.firedevops.firemud.account.v1.ConfirmOriginalNewGameplayAdmissionRequest; import net.firedevops.firemud.account.v1.FinalizeGameplayAdmissionLeaseRequest; +import net.firedevops.firemud.account.v1.IssueOriginalNewGameplayCredentialRequest; +import net.firedevops.firemud.account.v1.OriginalNewAdmissionConfirmationResponse; +import net.firedevops.firemud.account.v1.OriginalNewGameplayCredentialResult; import net.firedevops.firemud.account.v1.ReadGameplayAdmissionLeaseRequest; import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec; import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.Candidate; import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.Target; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; import net.firedevops.firemud.common.security.AccountJwtExactValues; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationJwtProfileValidator; import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; import net.firedevops.firemud.gamesession.v1.CanonicalGameplayAdmissionCandidate; import net.firedevops.firemud.gamesession.v1.CanonicalPlayableTargetEvidence; +import tools.jackson.databind.json.JsonMapper; /** * Closed schema-1 transport mapping for Account's exact original public-production NEW lease. @@ -47,12 +54,15 @@ public final class AccountGameplayAdmissionLeaseGrpcCodec { + GameSessionAccountDelegationProfile.MAX_COMPACT_JWT_BYTES + 1024; public static final int MAX_RESPONSE_WIRE_BYTES = - AccountGameplayAdmissionLeaseEvidence.MAX_EVIDENCE_BYTES + 8 * 1024; + AccountGameplayAdmissionLeaseEvidence.MAX_EVIDENCE_BYTES + + GameSessionAccountDelegationProfile.MAX_COMPACT_JWT_BYTES + + 16 * 1024; private static final int SCHEMA_VERSION = 1; private static final BigInteger UINT64_MAX = BigInteger.ONE.shiftLeft(64).subtract(BigInteger.ONE); private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final JsonMapper JSON = JsonMapper.builder().build(); private AccountGameplayAdmissionLeaseGrpcCodec() {} @@ -147,6 +157,214 @@ public String toString() { } } + /** Exact original-lease issuance request. The initial LOGIN JWT is transient and redacted. */ + public static final class OriginalNewCredentialRequest { + private final String presentedInitialGsACompactJwt; + private final AccountGameplayAdmissionLeaseEvidence originalLeaseEvidence; + private final byte[] originalLeaseEvidenceUtf8; + + private OriginalNewCredentialRequest( + String presentedInitialGsACompactJwt, + AccountGameplayAdmissionLeaseEvidence originalLeaseEvidence, + byte[] originalLeaseEvidenceUtf8) { + this.presentedInitialGsACompactJwt = presentedInitialGsACompactJwt; + this.originalLeaseEvidence = originalLeaseEvidence; + this.originalLeaseEvidenceUtf8 = originalLeaseEvidenceUtf8.clone(); + } + + public String presentedInitialGsACompactJwt() { + return presentedInitialGsACompactJwt; + } + + public AccountGameplayAdmissionLeaseEvidence originalLeaseEvidence() { + return originalLeaseEvidence; + } + + public byte[] originalLeaseEvidenceUtf8() { + return originalLeaseEvidenceUtf8.clone(); + } + + @Override + public String toString() { + return "AccountGameplayAdmissionLeaseGrpcCodec.OriginalNewCredentialRequest[redacted]"; + } + } + + /** Internal Account-to-Game-Session credential carrier; diagnostics never reveal its contents. */ + public static final class OriginalNewCredential implements AutoCloseable { + private final String signedBoundGsACompactJwt; + private byte[] opaqueRebindHandle; + private final UUID lineageId; + private final UUID tokenJti; + private final String tokenSha256; + private final long issuanceFence; + private final UUID originalLeaseId; + private final long originalLeaseFence; + private final String originalAckReceiptXid; + private final String checkpointsSha256; + + private OriginalNewCredential( + String signedBoundGsACompactJwt, + byte[] opaqueRebindHandle, + UUID lineageId, + UUID tokenJti, + String tokenSha256, + long issuanceFence, + UUID originalLeaseId, + long originalLeaseFence, + String originalAckReceiptXid, + String checkpointsSha256) { + this.signedBoundGsACompactJwt = signedBoundGsACompactJwt; + this.opaqueRebindHandle = opaqueRebindHandle.clone(); + this.lineageId = lineageId; + this.tokenJti = tokenJti; + this.tokenSha256 = tokenSha256; + this.issuanceFence = issuanceFence; + this.originalLeaseId = originalLeaseId; + this.originalLeaseFence = originalLeaseFence; + this.originalAckReceiptXid = originalAckReceiptXid; + this.checkpointsSha256 = checkpointsSha256; + } + + public String signedBoundGsACompactJwt() { + return signedBoundGsACompactJwt; + } + + public byte[] opaqueRebindHandle() { + if (opaqueRebindHandle == null) + throw new IllegalStateException("Credential result is closed"); + return opaqueRebindHandle.clone(); + } + + public UUID lineageId() { + return lineageId; + } + + public UUID tokenJti() { + return tokenJti; + } + + public String tokenSha256() { + return tokenSha256; + } + + public long issuanceFence() { + return issuanceFence; + } + + public UUID originalLeaseId() { + return originalLeaseId; + } + + public long originalLeaseFence() { + return originalLeaseFence; + } + + public String originalAckReceiptXid() { + return originalAckReceiptXid; + } + + public String checkpointsSha256() { + return checkpointsSha256; + } + + @Override + public void close() { + if (opaqueRebindHandle != null) Arrays.fill(opaqueRebindHandle, (byte) 0); + opaqueRebindHandle = null; + } + + @Override + public String toString() { + return "AccountGameplayAdmissionLeaseGrpcCodec.OriginalNewCredential[redacted]"; + } + } + + /** Exact Account confirmation recovery request; no caller-supplied proof or time fields. */ + public static final class OriginalFinalAdmissionConfirmationRequest { + private final String presentedInitialGsACompactJwt; + private final AccountGameplayAdmissionLeaseEvidence originalLeaseEvidence; + private final byte[] originalLeaseEvidenceUtf8; + + private OriginalFinalAdmissionConfirmationRequest( + String compactJwt, AccountGameplayAdmissionLeaseEvidence lease, byte[] exactLeaseBytes) { + this.presentedInitialGsACompactJwt = compactJwt; + this.originalLeaseEvidence = lease; + this.originalLeaseEvidenceUtf8 = exactLeaseBytes.clone(); + } + + public String presentedInitialGsACompactJwt() { + return presentedInitialGsACompactJwt; + } + + public AccountGameplayAdmissionLeaseEvidence originalLeaseEvidence() { + return originalLeaseEvidence; + } + + public byte[] originalLeaseEvidenceUtf8() { + return originalLeaseEvidenceUtf8.clone(); + } + + @Override + public String toString() { + return "AccountGameplayAdmissionLeaseGrpcCodec.OriginalFinalAdmissionConfirmationRequest[redacted]"; + } + } + + /** Exact current Account confirmation anchors; values alone are not an admission proof. */ + public static final class OriginalFinalAdmissionConfirmation { + private final UUID lineageId; + private final UUID originalLeaseId; + private final long originalLeaseFence; + private final long admissionAtMillis; + private final long continuityExpiresAtMillis; + private final String confirmationReadbackSha256; + + private OriginalFinalAdmissionConfirmation( + UUID lineageId, + UUID originalLeaseId, + long originalLeaseFence, + long admissionAtMillis, + long continuityExpiresAtMillis, + String confirmationReadbackSha256) { + this.lineageId = lineageId; + this.originalLeaseId = originalLeaseId; + this.originalLeaseFence = originalLeaseFence; + this.admissionAtMillis = admissionAtMillis; + this.continuityExpiresAtMillis = continuityExpiresAtMillis; + this.confirmationReadbackSha256 = confirmationReadbackSha256; + } + + public UUID lineageId() { + return lineageId; + } + + public UUID originalLeaseId() { + return originalLeaseId; + } + + public long originalLeaseFence() { + return originalLeaseFence; + } + + public long admissionAtMillis() { + return admissionAtMillis; + } + + public long continuityExpiresAtMillis() { + return continuityExpiresAtMillis; + } + + public String confirmationReadbackSha256() { + return confirmationReadbackSha256; + } + + @Override + public String toString() { + return "AccountGameplayAdmissionLeaseGrpcCodec.OriginalFinalAdmissionConfirmation[redacted]"; + } + } + /** Complete original-operation response shape with a redacted, typed receipt carrier. */ public static final class OperationEvidence { private final AccountGameplayAdmissionLeaseEvidence originalLeaseEvidence; @@ -490,6 +708,235 @@ public static OriginalLeaseRequest parseAbortRequest(AbortGameplayAdmissionLease OriginalLeasePurpose.ABORT, compactJwt, evidence, leaseBytes, decisionId); } + public static IssueOriginalNewGameplayCredentialRequest toIssueOriginalNewCredentialRequest( + String presentedInitialGsACompactJwt, byte[] originalLeaseEvidenceUtf8) { + byte[] leaseBytes = requireOriginalLeaseEvidenceBytes(originalLeaseEvidenceUtf8); + var request = + IssueOriginalNewGameplayCredentialRequest.newBuilder() + .addSchemaVersion(SCHEMA_VERSION) + .addPresentedInitialGsaCompactJwt(compactJwt(presentedInitialGsACompactJwt)) + .addOriginalLeaseEvidenceUtf8(ByteString.copyFrom(leaseBytes)) + .build(); + requireWireSize( + request.getSerializedSize(), + MAX_ORIGINAL_LEASE_REQUEST_WIRE_BYTES, + "original-new credential request"); + parseIssueOriginalNewCredentialRequest(request); + return request; + } + + public static OriginalNewCredentialRequest parseIssueOriginalNewCredentialRequest( + IssueOriginalNewGameplayCredentialRequest request) { + Objects.requireNonNull(request, "request"); + requireWireSize( + request.getSerializedSize(), + MAX_ORIGINAL_LEASE_REQUEST_WIRE_BYTES, + "original-new credential request"); + requireNoUnknownFields(request.getUnknownFields().asMap().isEmpty(), "original-new request"); + requireSchema(one(request.getSchemaVersionList(), "originalNew.schemaVersion")); + String compactJwt = + compactJwt(one(request.getPresentedInitialGsaCompactJwtList(), "originalNew.presentedJwt")); + byte[] leaseBytes = + one(request.getOriginalLeaseEvidenceUtf8List(), "originalNew.originalLeaseEvidenceUtf8") + .toByteArray(); + AccountGameplayAdmissionLeaseEvidence evidence = parseFreshNewLease(leaseBytes); + requirePresentedJwtMatchesLease(evidence, compactJwt); + return new OriginalNewCredentialRequest(compactJwt, evidence, leaseBytes); + } + + public static ConfirmOriginalNewGameplayAdmissionRequest + toConfirmOriginalNewGameplayAdmissionRequest( + String presentedInitialGsACompactJwt, byte[] originalLeaseEvidenceUtf8) { + byte[] leaseBytes = requireOriginalLeaseEvidenceBytes(originalLeaseEvidenceUtf8); + var request = + ConfirmOriginalNewGameplayAdmissionRequest.newBuilder() + .addSchemaVersion(SCHEMA_VERSION) + .addPresentedInitialGsaCompactJwt(compactJwt(presentedInitialGsACompactJwt)) + .addOriginalLeaseEvidenceUtf8(ByteString.copyFrom(leaseBytes)) + .build(); + requireWireSize( + request.getSerializedSize(), + MAX_ORIGINAL_LEASE_REQUEST_WIRE_BYTES, + "original-new admission confirmation request"); + parseConfirmOriginalNewGameplayAdmissionRequest(request); + return request; + } + + public static OriginalFinalAdmissionConfirmationRequest + parseConfirmOriginalNewGameplayAdmissionRequest( + ConfirmOriginalNewGameplayAdmissionRequest request) { + Objects.requireNonNull(request, "request"); + requireWireSize( + request.getSerializedSize(), + MAX_ORIGINAL_LEASE_REQUEST_WIRE_BYTES, + "original-new admission confirmation request"); + requireNoUnknownFields(request.getUnknownFields().asMap().isEmpty(), "confirmation request"); + requireSchema(one(request.getSchemaVersionList(), "confirmation.schemaVersion")); + String compactJwt = + compactJwt( + one(request.getPresentedInitialGsaCompactJwtList(), "confirmation.presentedJwt")); + byte[] leaseBytes = + one(request.getOriginalLeaseEvidenceUtf8List(), "confirmation.originalLeaseEvidence") + .toByteArray(); + AccountGameplayAdmissionLeaseEvidence lease = parseFreshNewLease(leaseBytes); + requirePresentedJwtMatchesLease(lease, compactJwt); + return new OriginalFinalAdmissionConfirmationRequest(compactJwt, lease, leaseBytes); + } + + public static OriginalNewAdmissionConfirmationResponse + toConfirmOriginalNewGameplayAdmissionResponse( + OriginalFinalAdmissionConfirmationRequest request, + UUID lineageId, + UUID originalLeaseId, + long originalLeaseFence, + long admissionAtMillis, + long continuityExpiresAtMillis, + String confirmationReadbackSha256) { + Objects.requireNonNull(request); + UUID leaseId = leaseId(request.originalLeaseEvidence()); + long leaseFence = positiveLong(request.originalLeaseEvidence().leaseFence()); + if (!leaseId.equals(originalLeaseId) + || leaseFence != originalLeaseFence + || admissionAtMillis <= 0L + || continuityExpiresAtMillis <= admissionAtMillis) { + throw invalid("Confirmation changed the exact original lease or deadline anchors"); + } + var response = + OriginalNewAdmissionConfirmationResponse.newBuilder() + .addSchemaVersion(SCHEMA_VERSION) + .addLineageUuid(highEntropyUuid(lineageId).toString()) + .addOriginalLeaseUuid(leaseId.toString()) + .addOriginalLeaseFence(Long.toString(leaseFence)) + .addAdmissionAtMs(Long.toString(admissionAtMillis)) + .addContinuityExpiresAtMs(Long.toString(continuityExpiresAtMillis)) + .addConfirmationReadbackSha256(digest(confirmationReadbackSha256)) + .build(); + requireWireSize(response.getSerializedSize(), 1024, "original-new confirmation response"); + parseConfirmOriginalNewGameplayAdmissionResponse(request, response); + return response; + } + + public static OriginalFinalAdmissionConfirmation parseConfirmOriginalNewGameplayAdmissionResponse( + OriginalFinalAdmissionConfirmationRequest request, + OriginalNewAdmissionConfirmationResponse response) { + Objects.requireNonNull(request); + Objects.requireNonNull(response); + requireWireSize(response.getSerializedSize(), 1024, "original-new confirmation response"); + requireNoUnknownFields(response.getUnknownFields().asMap().isEmpty(), "confirmation response"); + requireSchema(one(response.getSchemaVersionList(), "confirmationResponse.schemaVersion")); + UUID lineage = + highEntropyUuid(one(response.getLineageUuidList(), "confirmationResponse.lineageId")); + UUID lease = + highEntropyUuid(one(response.getOriginalLeaseUuidList(), "confirmationResponse.leaseId")); + long leaseFence = + positiveLongDecimal( + one(response.getOriginalLeaseFenceList(), "confirmationResponse.leaseFence"), + "leaseFence"); + long admissionAt = + positiveLongDecimal( + one(response.getAdmissionAtMsList(), "confirmationResponse.admissionAtMs"), + "admissionAtMs"); + long continuityExpires = + positiveLongDecimal( + one( + response.getContinuityExpiresAtMsList(), + "confirmationResponse.continuityExpiresAtMs"), + "continuityExpiresAtMs"); + String readbackDigest = + digest( + one( + response.getConfirmationReadbackSha256List(), + "confirmationResponse.readbackSha256")); + if (!lease.equals(leaseId(request.originalLeaseEvidence())) + || leaseFence != positiveLong(request.originalLeaseEvidence().leaseFence()) + || continuityExpires <= admissionAt) { + throw invalid("Confirmation response differs from the exact original lease"); + } + return new OriginalFinalAdmissionConfirmation( + lineage, lease, leaseFence, admissionAt, continuityExpires, readbackDigest); + } + + public static AccountGameplayAdmissionLeaseResponse toIssueOriginalNewCredentialResponse( + OriginalNewCredentialRequest request, + AccountGameplayAdmissionLeaseEvidence originalLeaseEvidence, + State state, + UUID bindingDecisionId, + OriginalAckReceiptEvidence originalAckReceipt, + OriginalNewCredential credential) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(credential, "credential"); + if (!request.originalLeaseEvidence().hasSameIdentity(originalLeaseEvidence) + || !Arrays.equals( + request.originalLeaseEvidenceUtf8(), canonicalLeaseBytes(originalLeaseEvidence))) { + throw invalid("Original-new result changed the exact lease evidence"); + } + AccountGameplayAdmissionLeaseResponse base = + buildResponse( + request.originalLeaseEvidenceUtf8(), + originalLeaseEvidence, + state, + bindingDecisionId, + null, + originalAckReceipt); + var response = + base.toBuilder().addOriginalNewCredential(toWireOriginalNewCredential(credential)).build(); + OriginalNewCredential parsed = parseIssueOriginalNewCredentialResponse(request, response); + parsed.close(); + return response; + } + + public static OriginalNewCredential parseIssueOriginalNewCredentialResponse( + OriginalNewCredentialRequest request, AccountGameplayAdmissionLeaseResponse response) { + Objects.requireNonNull(request, "request"); + OperationEvidence operation = parseResponse(response, true); + if (operation.state() != State.COMMITTED + || operation.bindingDecisionId() == null + || operation.originalAckReceipt() == null + || operation.orphanCleanupId() != null + || !Arrays.equals( + request.originalLeaseEvidenceUtf8(), + response.getOriginalLeaseEvidenceUtf8(0).toByteArray()) + || !request.originalLeaseEvidence().hasSameIdentity(operation.originalLeaseEvidence())) { + throw invalid("Original-new credential result requires the exact committed original lease"); + } + OriginalNewCredential result = + fromWireOriginalNewCredential(one(response.getOriginalNewCredentialList(), "originalNew")); + validateOriginalNewCredential( + operation.originalLeaseEvidence(), operation.originalAckReceipt(), result); + return result; + } + + /** Builds the redacted internal result value for Account's protected envelope recovery path. */ + public static OriginalNewCredential originalNewCredential( + String signedBoundGsACompactJwt, + byte[] opaqueRebindHandle, + UUID lineageId, + UUID tokenJti, + String tokenSha256, + long issuanceFence, + UUID originalLeaseId, + long originalLeaseFence, + String originalAckReceiptXid, + String checkpointsSha256) { + if (opaqueRebindHandle == null + || opaqueRebindHandle.length != 32 + || issuanceFence <= 0L + || originalLeaseFence <= 0L) { + throw invalid("Original-new credential result metadata is malformed"); + } + return new OriginalNewCredential( + compactJwt(signedBoundGsACompactJwt), + Objects.requireNonNull(opaqueRebindHandle).clone(), + highEntropyUuid(lineageId), + highEntropyUuid(tokenJti), + digest(tokenSha256), + issuanceFence, + highEntropyUuid(originalLeaseId), + originalLeaseFence, + xid(originalAckReceiptXid), + digest(checkpointsSha256)); + } + /** * Serializes a complete original-operation response and revalidates it against the acquisition. */ @@ -745,9 +1192,21 @@ private static AccountGameplayAdmissionLeaseResponse buildResponse( } private static OperationEvidence parseResponse(AccountGameplayAdmissionLeaseResponse response) { + return parseResponse(response, false); + } + + private static OperationEvidence parseResponse( + AccountGameplayAdmissionLeaseResponse response, boolean allowOriginalNewCredential) { Objects.requireNonNull(response, "response"); requireWireSize(response.getSerializedSize(), MAX_RESPONSE_WIRE_BYTES, "lease response"); requireNoUnknownFields(response.getUnknownFields().asMap().isEmpty(), "lease response"); + if (allowOriginalNewCredential) { + if (response.getOriginalNewCredentialCount() != 1) { + throw invalid("Original-new response must carry one credential result"); + } + } else if (response.getOriginalNewCredentialCount() != 0) { + throw invalid("Lease response cannot carry an original-new credential result"); + } requireSchema(one(response.getSchemaVersionList(), "response.schemaVersion")); byte[] leaseBytes = one(response.getOriginalLeaseEvidenceUtf8List(), "response.leaseEvidence").toByteArray(); @@ -766,6 +1225,157 @@ private static OperationEvidence parseResponse(AccountGameplayAdmissionLeaseResp return new OperationEvidence(lease, state, decisionId, cleanupId, receipt); } + private static OriginalNewGameplayCredentialResult toWireOriginalNewCredential( + OriginalNewCredential credential) { + byte[] handle = credential.opaqueRebindHandle(); + try { + return OriginalNewGameplayCredentialResult.newBuilder() + .addSchemaVersion(SCHEMA_VERSION) + .addSignedBoundGsaCompactJwt(credential.signedBoundGsACompactJwt()) + .addOpaqueRebindHandle(ByteString.copyFrom(handle)) + .addLineageUuid(credential.lineageId().toString()) + .addTokenJtiUuid(credential.tokenJti().toString()) + .addTokenSha256(credential.tokenSha256()) + .addIssuanceFence(Long.toString(credential.issuanceFence())) + .addOriginalLeaseUuid(credential.originalLeaseId().toString()) + .addOriginalLeaseFence(Long.toString(credential.originalLeaseFence())) + .addOriginalAckReceiptXid(credential.originalAckReceiptXid()) + .addCheckpointsSha256(credential.checkpointsSha256()) + .build(); + } finally { + Arrays.fill(handle, (byte) 0); + } + } + + private static OriginalNewCredential fromWireOriginalNewCredential( + OriginalNewGameplayCredentialResult wire) { + requireNoUnknownFields(wire.getUnknownFields().asMap().isEmpty(), "original-new credential"); + int schema = one(wire.getSchemaVersionList(), "originalNew.schemaVersion"); + requireSchema(schema); + String jwt = compactJwt(one(wire.getSignedBoundGsaCompactJwtList(), "originalNew.compactJwt")); + byte[] handle = one(wire.getOpaqueRebindHandleList(), "originalNew.rebindHandle").toByteArray(); + if (handle.length != 32) throw invalid("Opaque rebind handle must be exactly 32 bytes"); + try { + return originalNewCredential( + jwt, + handle, + highEntropyUuid(one(wire.getLineageUuidList(), "originalNew.lineageId")), + highEntropyUuid(one(wire.getTokenJtiUuidList(), "originalNew.tokenJti")), + digest(one(wire.getTokenSha256List(), "originalNew.tokenSha256")), + positiveLongDecimal( + one(wire.getIssuanceFenceList(), "originalNew.issuanceFence"), "issuanceFence"), + highEntropyUuid(one(wire.getOriginalLeaseUuidList(), "originalNew.leaseId")), + positiveLongDecimal( + one(wire.getOriginalLeaseFenceList(), "originalNew.leaseFence"), "leaseFence"), + xid(one(wire.getOriginalAckReceiptXidList(), "originalNew.ackReceiptXid")), + digest(one(wire.getCheckpointsSha256List(), "originalNew.checkpointsSha256"))); + } finally { + Arrays.fill(handle, (byte) 0); + } + } + + private static void validateOriginalNewCredential( + AccountGameplayAdmissionLeaseEvidence lease, + OriginalAckReceiptEvidence receipt, + OriginalNewCredential result) { + byte[] jwtBytes = compactJwtUtf8(result.signedBoundGsACompactJwt()); + try { + Map claims = parseCompactJwtClaims(result.signedBoundGsACompactJwt()); + Map carrier = lease.carrier(); + Map scope = object(carrier.get("bindingScope"), "bindingScope"); + Map baseline = object(carrier.get("membershipBaseline"), "membershipBaseline"); + Map tokenIdentity = + object(carrier.get("tokenIdentityEvidence"), "tokenIdentityEvidence"); + String accountId = string(scope, "accountId"); + String tenantId = string(scope, "tenantId"); + String originalJti = string(tokenIdentity, "tokenJti"); + long issuanceFence = positiveLongValue(carrier.get("issuanceFence"), "issuanceFence"); + long leaseFence = positiveLong(lease.leaseFence()); + byte[] checkpoints = canonicalJsonBytes(carrier.get("outboxCheckpoints")); + try { + if (!sha256(jwtBytes).equals(result.tokenSha256()) + || result.lineageId().equals(result.tokenJti()) + || result.tokenJti().toString().equals(originalJti) + || !leaseId(lease).equals(result.originalLeaseId()) + || leaseFence != result.originalLeaseFence() + || issuanceFence != result.issuanceFence() + || !sha256(checkpoints).equals(result.checkpointsSha256()) + || receipt == null + || !receipt.receiptXid().equals(result.originalAckReceiptXid()) + || !accountId.equals(claims.get("sub")) + || !accountId.equals(claims.get("accountId")) + || !tenantId.equals(claims.get("tenantId")) + || !result.tokenJti().toString().equals(claims.get("jti")) + || positiveClaim(claims, "tokenGeneration") != 1L + || positiveClaim(claims, "issuanceFence") != issuanceFence + || !Objects.equals(carrier.get("authorityTuple"), claims.get("authorityTuple")) + || !Objects.equals(baseline.get("membershipVersion"), claims.get("membershipVersion")) + || claims.containsKey("globalRoles") + || claims.containsKey("scopedRoles")) { + throw invalid("Original-new credential differs from the exact committed lease binding"); + } + } finally { + Arrays.fill(checkpoints, (byte) 0); + } + } finally { + Arrays.fill(jwtBytes, (byte) 0); + } + } + + private static Map parseCompactJwtClaims(String compact) { + String[] parts = compact.split("\\.", -1); + if (parts.length != 3 || parts[0].isEmpty() || parts[1].isEmpty() || parts[2].isEmpty()) { + throw invalid("Signed bound GSA compact JWT is malformed"); + } + byte[] payload; + try { + payload = java.util.Base64.getUrlDecoder().decode(parts[1]); + } catch (IllegalArgumentException malformed) { + throw invalid("Signed bound GSA compact JWT payload is malformed"); + } + try { + Map claims = JSON.readValue(payload, Map.class); + GameSessionAccountDelegationJwtProfileValidator.validateClaims(claims); + return claims; + } catch (Exception malformed) { + throw invalid("Signed bound GSA claims are malformed"); + } finally { + Arrays.fill(payload, (byte) 0); + } + } + + private static byte[] canonicalJsonBytes(Object value) { + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } catch (Exception malformed) { + throw invalid("Original lease checkpoints are malformed"); + } + } + + private static UUID leaseId(AccountGameplayAdmissionLeaseEvidence lease) { + return highEntropyUuid(string(lease.carrier(), "leaseId")); + } + + private static long positiveLongValue(Object value, String field) { + try { + return AccountJwtExactValues.positiveDecimalCounter(value).longValueExact(); + } catch (RuntimeException malformed) { + throw invalid(field + " is outside its supported positive signed-long range"); + } + } + + private static long positiveClaim(Map claims, String field) { + return positiveLongValue(claims.get(field), field); + } + + private static String sha256(byte[] value) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value)); + } catch (NoSuchAlgorithmException unavailable) { + throw new IllegalStateException("SHA-256 is unavailable", unavailable); + } + } + private static void validateOperationState( AccountGameplayAdmissionLeaseEvidence lease, State state, diff --git a/services/common-security/src/test/java/net/firedevops/firemud/common/account/admission/AccountGameplayAdmissionLeaseGrpcCodecTest.java b/services/common-security/src/test/java/net/firedevops/firemud/common/account/admission/AccountGameplayAdmissionLeaseGrpcCodecTest.java index 207f05a239..d592de651b 100644 --- a/services/common-security/src/test/java/net/firedevops/firemud/common/account/admission/AccountGameplayAdmissionLeaseGrpcCodecTest.java +++ b/services/common-security/src/test/java/net/firedevops/firemud/common/account/admission/AccountGameplayAdmissionLeaseGrpcCodecTest.java @@ -10,7 +10,9 @@ import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.time.Instant; +import java.util.Base64; import java.util.HexFormat; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.UUID; @@ -20,15 +22,18 @@ import net.firedevops.firemud.account.v1.AcquireGameplayAdmissionLeaseRequest; import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseGrpcCodec.AcquireRequest; import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseGrpcCodec.OriginalAckReceiptEvidence; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseGrpcCodec.OriginalNewCredential; import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseGrpcCodec.State; import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.Candidate; import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.OriginKind; import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.OwnerProofOutcome; import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.Target; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold; import net.firedevops.firemud.gamesession.v1.CanonicalPlayableTargetEvidence; import org.junit.jupiter.api.Test; +import tools.jackson.databind.json.JsonMapper; /** Shape and tuple checks only; these carriers grant no Account or gameplay authority. */ class AccountGameplayAdmissionLeaseGrpcCodecTest { @@ -43,6 +48,7 @@ class AccountGameplayAdmissionLeaseGrpcCodecTest { private static final UUID VERSION_ID = UUID.fromString("99999999-9999-4999-8999-999999999999"); private static final UUID HOLD_ID = UUID.fromString("55555555-5555-4555-8555-555555555555"); private static final UUID HOLD_FENCE = UUID.fromString("66666666-6666-4666-8666-666666666666"); + private static final JsonMapper JSON = JsonMapper.builder().build(); @Test void roundTripsExactAcquireLeaseBytesAndCompleteAckWithoutClaimingAuthority() { @@ -202,6 +208,110 @@ void rejectsAcquireResponseWhenTokenDigestDiffersFromPresentedCredential() { assertRejected(request, pendingResponse(changedLease)); } + @Test + void originalNewCredentialCarrierKeepsHandleOpaqueAndRejectsUnboundClaims() throws Exception { + var lease = lease(); + byte[] leaseBytes = lease.canonicalJson().getBytes(StandardCharsets.UTF_8); + var request = + AccountGameplayAdmissionLeaseGrpcCodec.parseIssueOriginalNewCredentialRequest( + AccountGameplayAdmissionLeaseGrpcCodec.toIssueOriginalNewCredentialRequest( + JWT, leaseBytes)); + Map carrier = lease.carrier(); + Map scope = object(carrier, "bindingScope"); + UUID requestId = UUID.fromString((String) carrier.get("requestId")); + UUID accountId = UUID.fromString((String) scope.get("accountId")); + UUID leaseId = UUID.fromString((String) carrier.get("leaseId")); + long leaseFence = lease.leaseFence().longValueExact(); + UUID lineageId = UUID.randomUUID(); + UUID tokenJti = UUID.randomUUID(); + while (tokenJti.equals(lineageId) + || tokenJti + .toString() + .equals(String.valueOf(object(carrier, "tokenIdentityEvidence").get("tokenJti")))) { + tokenJti = UUID.randomUUID(); + } + long issuedAt = Instant.now().getEpochSecond(); + Map claims = boundClaims(lease, tokenJti, issuedAt); + String boundJwt = compactJwt(claims); + byte[] handle = new byte[32]; + java.util.Arrays.fill(handle, (byte) 0x2a); + String checkpointsSha256 = checkpointsSha256(carrier.get("outboxCheckpoints")); + OriginalNewCredential credential = + AccountGameplayAdmissionLeaseGrpcCodec.originalNewCredential( + boundJwt, + handle, + lineageId, + tokenJti, + jwtSha256(boundJwt), + Long.parseLong((String) carrier.get("issuanceFence")), + leaseId, + leaseFence, + "102", + checkpointsSha256); + var ack = + OriginalAckReceiptEvidence.fromFields( + 1, + requestId, + accountId, + leaseId, + leaseFence, + lease.sha256(), + DECISION_ID, + 1_015_000L, + "101", + 1_014_999L, + "102"); + + var response = + AccountGameplayAdmissionLeaseGrpcCodec.toIssueOriginalNewCredentialResponse( + request, lease, State.COMMITTED, DECISION_ID, ack, credential); + OriginalNewCredential parsed = + AccountGameplayAdmissionLeaseGrpcCodec.parseIssueOriginalNewCredentialResponse( + request, response); + byte[] firstHandleRead = parsed.opaqueRebindHandle(); + String handleHex = HexFormat.of().formatHex(handle); + assertThat(parsed.lineageId()).isEqualTo(lineageId); + assertThat(parsed.signedBoundGsACompactJwt()).isEqualTo(boundJwt); + assertThat(firstHandleRead).containsExactly(handle); + assertThat(parsed.toString()).doesNotContain(boundJwt, handleHex); + assertThat(request.toString()).doesNotContain(JWT, handleHex); + java.util.Arrays.fill(firstHandleRead, (byte) 0); + byte[] secondHandleRead = parsed.opaqueRebindHandle(); + assertThat(secondHandleRead).containsExactly(handle); + java.util.Arrays.fill(secondHandleRead, (byte) 0); + parsed.close(); + assertThatThrownBy(parsed::opaqueRebindHandle) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Credential result is closed"); + + Map unboundClaims = new LinkedHashMap<>(claims); + unboundClaims.remove("tenantId"); + unboundClaims.put("membershipVersion", Map.of()); + unboundClaims.put("authorityTuple", GameSessionAccountDelegationProfile.authorityTuple(1L, 1L)); + String unboundJwt = compactJwt(unboundClaims); + OriginalNewCredential unboundCredential = + AccountGameplayAdmissionLeaseGrpcCodec.originalNewCredential( + unboundJwt, + handle, + lineageId, + tokenJti, + jwtSha256(unboundJwt), + Long.parseLong((String) carrier.get("issuanceFence")), + leaseId, + leaseFence, + "102", + checkpointsSha256); + assertThatThrownBy( + () -> + AccountGameplayAdmissionLeaseGrpcCodec.toIssueOriginalNewCredentialResponse( + request, lease, State.COMMITTED, DECISION_ID, ack, unboundCredential)) + .isInstanceOf(IllegalArgumentException.class); + credential.close(); + unboundCredential.close(); + java.util.Arrays.fill(handle, (byte) 0); + java.util.Arrays.fill(leaseBytes, (byte) 0); + } + @Test void rejectsMissingDuplicateAndUnknownAcquireAndResponseFields() { var lease = lease(); @@ -780,6 +890,48 @@ private static String jwtSha256(String jwt) { } } + private static Map boundClaims( + AccountGameplayAdmissionLeaseEvidence lease, UUID tokenJti, long issuedAt) { + Map carrier = lease.carrier(); + Map scope = object(carrier, "bindingScope"); + Map baseline = object(carrier, "membershipBaseline"); + Map claims = new LinkedHashMap<>(); + claims.put("iss", GameSessionAccountDelegationProfile.ISSUER); + claims.put("sub", scope.get("accountId")); + claims.put("accountId", scope.get("accountId")); + claims.put("jti", tokenJti.toString()); + claims.put("aud", GameSessionAccountDelegationProfile.AUDIENCE); + claims.put("iat", issuedAt); + claims.put("nbf", issuedAt); + claims.put("exp", issuedAt + 120L); + claims.put("tokenGeneration", "1"); + claims.put("authorityTuple", carrier.get("authorityTuple")); + claims.put("membershipVersion", baseline.get("membershipVersion")); + claims.put("issuanceFence", carrier.get("issuanceFence")); + claims.put("tenantId", scope.get("tenantId")); + return claims; + } + + private static String compactJwt(Map claims) throws Exception { + String header = + Base64.getUrlEncoder() + .withoutPadding() + .encodeToString( + "{\"alg\":\"RS256\",\"kid\":\"controlled-test\"}".getBytes(StandardCharsets.UTF_8)); + String payload = + Base64.getUrlEncoder().withoutPadding().encodeToString(JSON.writeValueAsBytes(claims)); + return header + "." + payload + ".c2ln"; + } + + private static String checkpointsSha256(Object checkpoints) throws Exception { + byte[] canonical = Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(checkpoints)); + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(canonical)); + } finally { + java.util.Arrays.fill(canonical, (byte) 0); + } + } + private static Map object(Map carrier, String field) { return (Map) carrier.get(field); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountGameplayAdmissionLeaseClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountGameplayAdmissionLeaseClient.java index a03f2a7bae..6caf868995 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountGameplayAdmissionLeaseClient.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountGameplayAdmissionLeaseClient.java @@ -14,7 +14,11 @@ import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseGrpcCodec; import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseGrpcCodec.AcquireRequest; import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseGrpcCodec.OperationEvidence; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseGrpcCodec.OriginalFinalAdmissionConfirmation; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseGrpcCodec.OriginalFinalAdmissionConfirmationRequest; import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseGrpcCodec.OriginalLeaseRequest; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseGrpcCodec.OriginalNewCredential; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseGrpcCodec.OriginalNewCredentialRequest; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.Candidate; import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.Target; @@ -25,7 +29,9 @@ import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; -/** Manual Game Session to Account transport for the four exact NEW-binding lease operations. */ +/** + * Manual Game Session to Account transport for NEW lease and ORIGINAL-NEW credential operations. + */ public final class AccountGameplayAdmissionLeaseClient extends AbstractReloadingBlockingGrpcClient< AccountGameplayAdmissionLeaseServiceGrpc.AccountGameplayAdmissionLeaseServiceBlockingStub> { @@ -196,6 +202,72 @@ public OperationEvidence abort( } } + /** + * Requests the first bound ORIGINAL-NEW credential after Account's actual COMMITTED lease/ACK + * readback. The returned handle is an internal opaque value; callers must not log it or forward + * it to any player-facing response. + */ + public OriginalNewCredential issueOriginalNewBoundGameplayCredential( + String presentedInitialGsACompactJwt, byte[] originalLeaseEvidenceUtf8) { + requireNoAmbientSql("Original-new credential issuance requires no ambient SQL"); + var wireRequest = + AccountGameplayAdmissionLeaseGrpcCodec.toIssueOriginalNewCredentialRequest( + presentedInitialGsACompactJwt, originalLeaseEvidenceUtf8); + OriginalNewCredentialRequest expected = + AccountGameplayAdmissionLeaseGrpcCodec.parseIssueOriginalNewCredentialRequest(wireRequest); + requireLeaseCorrelation(expected.originalLeaseEvidence()); + try { + OriginalNewCredential credential = + AccountGameplayAdmissionLeaseGrpcCodec.parseIssueOriginalNewCredentialResponse( + expected, + requireInitializedStub("Account lease service is not initialized") + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .issueOriginalNewGameplayCredential(wireRequest)); + if (!credential + .originalLeaseId() + .equals( + UUID.fromString( + (String) expected.originalLeaseEvidence().carrier().get("leaseId"))) + || credential.originalLeaseFence() + != expected.originalLeaseEvidence().leaseFence().longValueExact()) { + throw new IllegalArgumentException("Account credential result changed its original lease"); + } + return credential; + } catch (StatusRuntimeException failure) { + throw statusFailure("Account original-new credential issuance failed", failure); + } catch (IllegalArgumentException malformed) { + throw invalidEvidence("Account returned invalid original-new credential evidence", malformed); + } + } + + /** + * Requests Account's durable confirmation after it fetches the authenticated actual GS result. + */ + public OriginalFinalAdmissionConfirmation confirmOriginalNewGameplayAdmission( + String presentedInitialGsACompactJwt, byte[] originalLeaseEvidenceUtf8) { + requireNoAmbientSql("Original-new admission confirmation requires no ambient SQL"); + var wireRequest = + AccountGameplayAdmissionLeaseGrpcCodec.toConfirmOriginalNewGameplayAdmissionRequest( + presentedInitialGsACompactJwt, originalLeaseEvidenceUtf8); + OriginalFinalAdmissionConfirmationRequest expected = + AccountGameplayAdmissionLeaseGrpcCodec.parseConfirmOriginalNewGameplayAdmissionRequest( + wireRequest); + requireLeaseCorrelation(expected.originalLeaseEvidence()); + try { + return AccountGameplayAdmissionLeaseGrpcCodec + .parseConfirmOriginalNewGameplayAdmissionResponse( + expected, + requireInitializedStub("Account lease service is not initialized") + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .confirmOriginalNewGameplayAdmission(wireRequest)); + } catch (StatusRuntimeException failure) { + throw statusFailure("Account original-new admission confirmation failed", failure); + } catch (IllegalArgumentException malformed) { + throw invalidEvidence( + "Account returned invalid original-new admission confirmation", malformed); + } + } + private void requireLeaseCorrelation(AccountGameplayAdmissionLeaseEvidence lease) { Objects.requireNonNull(lease, "lease"); Object targetNamespace = lease.carrier().get("targetNamespace"); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierInitializerRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierInitializerRepository.java index d446efc9f7..30ab265e9f 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierInitializerRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierInitializerRepository.java @@ -155,7 +155,9 @@ InitialObservationContext readCurrentObservationContext(UUID originalRequestId) AccountControlSource current = readCurrentNoActiveControl(transaction, snapshot.accountId()); requireSameCurrentSource(snapshot, current); - requireOriginalJournalStillCurrent(transaction, snapshot); + if (snapshot.state() != State.OPEN_INSTALLED) { + requireOriginalJournalStillCurrent(transaction, snapshot); + } return InitialObservationContext.from(snapshot); }); } @@ -171,7 +173,69 @@ InitializerSnapshot readCurrent(UUID originalRequestId) { AccountControlSource current = readCurrentNoActiveControl(transaction, snapshot.accountId()); requireSameCurrentSource(snapshot, current); - requireOriginalJournalStillCurrent(transaction, snapshot); + if (snapshot.state() != State.OPEN_INSTALLED) { + requireOriginalJournalStillCurrent(transaction, snapshot); + } + return snapshot; + }); + } + + /** + * Resolves exactly one retained installed INITIAL target by its physical account scope. The + * lookup is read-only and checks the target's captured positive NO_ACTIVE control tuple; it does + * not use original LOGIN liveness as storage authority or create a replacement target. + */ + InitializerSnapshot readInstalledOpenForTarget( + UUID accountId, UUID tenantId, UUID playableStateNamespaceId) { + requireNonNil(accountId, "accountId"); + requireNonNil(tenantId, "tenantId"); + requireNonNil(playableStateNamespaceId, "playableStateNamespaceId"); + requireNoAmbientTransaction(); + return dsl.transactionResult( + configuration -> { + DSLContext transaction = DSL.using(configuration); + transaction.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY"); + var rows = + transaction.fetch( + "SELECT i.initializer_id, i.original_request_id, i.original_caller_context_id," + + " i.original_attempt_fence, i.account_id, i.account_login_evidence_digest," + + " i.source_control_state, i.source_control_epoch," + + " i.inventory_snapshot_revision, i.source_control_digest, t.tenant_id," + + " t.playable_state_namespace_id, t.target_state," + + " t.before_accepted_attestation_digest, t.before_incarnation_digest," + + " t.before_source_payload_digest," + + " t.before_observation_issued_at_epoch_millis," + + " t.before_observation_observed_at_epoch_millis," + + " t.before_observation_expires_at_epoch_millis, t.installed_fields_digest" + + " FROM " + + INITIALIZER + + " i JOIN " + + TARGET + + " t ON t.initializer_id = i.initializer_id" + + " AND t.original_request_id = i.original_request_id" + + " WHERE i.account_id = ? AND t.account_id = ? AND t.tenant_id = ?" + + " AND t.playable_state_namespace_id = ?" + + " AND t.target_state = 'OPEN_INSTALLED'" + + " ORDER BY i.initializer_id, t.target_ordinal", + accountId, + accountId, + tenantId, + playableStateNamespaceId); + if (rows.size() != 1) { + throw conflict( + rows.isEmpty() + ? "No retained installed INITIAL OPEN target matches the exact account scope" + : "Multiple retained installed INITIAL OPEN targets match the exact account scope"); + } + InitializerSnapshot snapshot = toSnapshot(rows.get(0)); + if (snapshot.state() != State.OPEN_INSTALLED + || !accountId.equals(snapshot.accountId()) + || !tenantId.equals(snapshot.tenantId()) + || !playableStateNamespaceId.equals(snapshot.playableStateNamespaceId())) { + throw conflict("Retained INITIAL OPEN target differs from the exact account scope"); + } + AccountControlSource current = readCurrentNoActiveControl(transaction, accountId); + requireSameCurrentSource(snapshot, current); return snapshot; }); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierRedisOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierRedisOwner.java index 62efba8ed2..691c0fb6f3 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierRedisOwner.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierRedisOwner.java @@ -213,6 +213,45 @@ CanonicalGameplayAccountInitialOpenProof verifyCurrentOpen(UUID originalRequestI } } + /** + * Resolves and verifies a retained installed INITIAL OPEN for its exact account scope. These + * coordinates select storage evidence only; the returned proof is not fresh caller or Account + * admission authority. + */ + CanonicalGameplayAccountInitialOpenProof verifyCurrentOpenForTarget( + UUID accountId, UUID tenantId, UUID playableStateNamespaceId) { + if (isNil(accountId) || isNil(tenantId) || isNil(playableStateNamespaceId)) { + return refused(CanonicalGameplayAccountInitialOpenProof.Reason.ORIGINAL_ATTEMPT_MISMATCH); + } + CanonicalGameplayAccountInitialBarrierInitializerRepository.InitializerSnapshot snapshot; + try { + requireNoAmbientTransaction(); + snapshot = + repository.readInstalledOpenForTarget(accountId, tenantId, playableStateNamespaceId); + } catch (RuntimeException unavailable) { + return refused(CanonicalGameplayAccountInitialOpenProof.Reason.SOURCE_CONTROL_UNAVAILABLE); + } + if (snapshot == null + || !accountId.equals(snapshot.accountId()) + || !tenantId.equals(snapshot.tenantId()) + || !playableStateNamespaceId.equals(snapshot.playableStateNamespaceId())) { + return refused(CanonicalGameplayAccountInitialOpenProof.Reason.ORIGINAL_ATTEMPT_MISMATCH); + } + if (snapshot.state() + == CanonicalGameplayAccountInitialBarrierInitializerRepository.State.NEVER_DISPATCHED) { + return refused(CanonicalGameplayAccountInitialOpenProof.Reason.TARGET_NEVER_DISPATCHED); + } + if (snapshot.state() + == CanonicalGameplayAccountInitialBarrierInitializerRepository.State.DISPATCH_POSSIBLE) { + return refused(CanonicalGameplayAccountInitialOpenProof.Reason.REMOTE_OUTCOME_UNCERTAIN); + } + if (snapshot.state() + != CanonicalGameplayAccountInitialBarrierInitializerRepository.State.OPEN_INSTALLED) { + return refused(CanonicalGameplayAccountInitialOpenProof.Reason.ORIGINAL_ATTEMPT_MISMATCH); + } + return verifyCurrentOpen(snapshot.originalRequestId()); + } + private void tryCreateOnce( CanonicalGameplayAccountInitialBarrierInitializerRepository.InitializerSnapshot snapshot, CanonicalGameplayTenantGameplayTagRepository.Assignment assignment, @@ -489,6 +528,10 @@ private static IllegalStateException unavailable(Throwable cause) { return new IllegalStateException("INITIAL account barrier is unavailable", cause); } + private static boolean isNil(UUID value) { + return value == null || value.equals(new UUID(0L, 0L)); + } + record Readback( UUID initializerId, UUID originalRequestId, diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepository.java index 62ae4e132c..810009bac0 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepository.java @@ -284,6 +284,115 @@ CanonicalGameplayBindingProvisionalCasEvidence readProvisionalCasEvidence(UUID t }); } + /** + * Claims the one permitted original-NEW candidate installation. The immutable candidate and + * DISPATCH_POSSIBLE marker commit together before the caller can reach Redis. A returned create + * permission exists only for that first committed claim; later calls are read-only. + */ + OriginalNewCandidateInstallationClaim claimOriginalNewCandidateInstallation( + CanonicalGameplayAdmissionDecision originalDecision) { + Objects.requireNonNull(originalDecision, "originalDecision"); + requireNoAmbientTransaction(); + return dsl.transactionResult( + configuration -> { + DSLContext transaction = DSL.using(configuration); + BigInteger currentRevision = lockInventoryRevision(transaction); + CanonicalGameplayAccountCoverageEvidence accountCoverage = + lockAccountCoverageEvidence(transaction, originalDecision.candidate().accountId()); + lockLeaseBoundRuntimeBeforeTransition( + transaction, + originalDecision.bindingDecisionId(), + originalDecision.candidate().bindingRef().bytes(), + originalDecision.targetEvidence()); + CanonicalGameplayBindingProvisionalCasEvidence evidence = + loadProvisionalCasEvidence(transaction, originalDecision.bindingDecisionId(), true); + if (!accountCoverage.equals(evidence.transition().accountCoverageEvidence())) { + throw conflict("Original NEW account control changed before candidate dispatch claim"); + } + requireDecisionMatchesOperation(originalDecision, evidence); + CanonicalGameplayOriginalNewCandidate candidate; + try { + candidate = + CanonicalGameplayOriginalNewCandidate.fromOriginalSources( + evidence, originalDecision); + } catch (RuntimeException invalidSource) { + throw conflict("Original NEW candidate source is not exact and public-production"); + } + + Record transition = findTransition(transaction, evidence.transition().transitionId()); + byte[] storedBytes = transition.get("original_new_candidate_bytes", byte[].class); + String storedDigest = transition.get("original_new_candidate_digest", String.class); + String storedState = transition.get("original_new_candidate_state", String.class); + String storedReadbackDigest = + transition.get("original_new_candidate_readback_digest", String.class); + if (storedBytes == null) { + if (storedDigest != null + || storedState != null + || storedReadbackDigest != null + || evidence.transition().status() + != CanonicalGameplayBindingTransitionSnapshot.Status.PREPARED + || transition.get("admission_lease_id", UUID.class) != null) { + throw conflict("Only an untouched PREPARED original NEW row can claim creation"); + } + byte[] bytes = candidate.canonicalBytes(); + String digest = CanonicalGameplayIssuerMemberV2Codec.sha256(bytes); + BigInteger priorRevision = evidence.transition().inventoryRevision(); + BigInteger nextRevision = currentRevision.add(BigInteger.ONE); + updateOriginalNewCandidateRevisionRows( + transaction, evidence, priorRevision, nextRevision, bytes, digest); + bumpInventoryClock(transaction, currentRevision, nextRevision); + CanonicalGameplayBindingProvisionalCasEvidence current = + loadProvisionalCasEvidence(transaction, evidence.transition().transitionId(), true); + return new OriginalNewCandidateInstallationClaim( + current, + originalDecision, + candidate, + OriginalNewCandidateInstallationState.DISPATCH_POSSIBLE, + new OriginalNewCandidateCreatePermission()); + } + + if (storedDigest == null + || !storedDigest.equals(CanonicalGameplayIssuerMemberV2Codec.sha256(storedBytes)) + || !Arrays.equals(storedBytes, candidate.canonicalBytes()) + || (!"DISPATCH_POSSIBLE".equals(storedState) + && !"READBACK_CONFIRMED".equals(storedState))) { + throw conflict("Original NEW candidate retry differs from its immutable SQL source"); + } + CanonicalGameplayOriginalNewCandidate parsed = + CanonicalGameplayOriginalNewCandidate.parseCanonical(storedBytes); + if (!parsed.equals(candidate) + || !parsed.matchesOriginalDecision(originalDecision) + || !parsed.matchesProvisionalSources(evidence)) { + throw conflict("Stored original NEW candidate no longer matches its durable sources"); + } + if (evidence.transition().status() + == CanonicalGameplayBindingTransitionSnapshot.Status.PROVISIONAL) { + CanonicalGameplayAdmissionDecision stored = toAdmissionDecision(transition, evidence); + requireSameAdmissionDecision(originalDecision, stored); + if (!"READBACK_CONFIRMED".equals(storedState) || storedReadbackDigest == null) { + throw conflict("PROVISIONAL original NEW source lacks retained physical readback"); + } + } + return new OriginalNewCandidateInstallationClaim( + evidence, + originalDecision, + parsed, + OriginalNewCandidateInstallationState.valueOf(storedState), + null); + }); + } + + /** + * Records only actual owner-produced physical readback, then reuses the existing provisional CAS. + */ + CanonicalGameplayBindingTransitionSnapshot markOriginalNewCandidateProvisional( + OriginalNewCandidateInstallationClaim claim, + CanonicalGameplayOriginalNewCandidateRedisOwner.PhysicalReadback readback) { + Objects.requireNonNull(claim, "candidate installation claim"); + Objects.requireNonNull(readback, "owner-produced physical readback"); + return markProvisional(claim.evidence(), claim.originalDecision(), claim.candidate(), readback); + } + void requireSameProvisionalSource( CanonicalGameplayBindingProvisionalCasEvidence expected, CanonicalGameplayBindingProvisionalCasEvidence current) { @@ -634,6 +743,87 @@ private static void writeRevisionRows( "Candidate issuer reservation changed before region bridge revision"); } + private static void updateOriginalNewCandidateRevisionRows( + DSLContext transaction, + CanonicalGameplayBindingProvisionalCasEvidence evidence, + BigInteger oldRevision, + BigInteger nextRevision, + byte[] candidateBytes, + String candidateDigest) { + UUID transitionId = evidence.transition().transitionId(); + requireOne( + transaction.execute( + "UPDATE " + + TRANSITION + + " SET original_new_candidate_bytes = ?, original_new_candidate_digest = ?," + + " original_new_candidate_state = 'DISPATCH_POSSIBLE', inventory_revision = ?" + + " WHERE transition_id = ? AND status = 'PREPARED' AND inventory_revision = ?" + + " AND expected_prior_binding_ref IS NULL" + + " AND expected_prior_binding_generation IS NULL" + + " AND admission_lease_id IS NULL AND original_new_candidate_bytes IS NULL" + + " AND original_new_candidate_digest IS NULL AND original_new_candidate_state IS NULL" + + " AND original_new_candidate_readback_digest IS NULL", + candidateBytes, + candidateDigest, + decimal(nextRevision), + transitionId, + decimal(oldRevision)), + "Original NEW candidate lost its first durable dispatch claim"); + requireOne( + transaction.execute( + "UPDATE " + + INVENTORY + + " SET inventory_revision = ? WHERE binding_ref = ? AND transition_id = ?" + + " AND lifecycle = 'CANDIDATE_PREPARED' AND binding_generation = ?" + + " AND account_index_state = 'REPAIR_REQUIRED'" + + " AND issuer_index_state = 'REPAIR_REQUIRED' AND inventory_revision = ?", + decimal(nextRevision), + evidence.candidate().bindingRef().bytes(), + transitionId, + decimal(evidence.transition().bindingGeneration()), + decimal(oldRevision)), + "Original NEW candidate inventory row changed before first dispatch claim"); + requireCount( + transaction.execute( + "UPDATE " + + ACCOUNT_OBLIGATION + + " SET inventory_revision = ? WHERE transition_id = ? AND inventory_revision = ?", + decimal(nextRevision), + transitionId, + decimal(oldRevision)), + 1, + "Original NEW account-index obligation changed before first dispatch claim"); + requireOne( + transaction.execute( + "UPDATE " + + ISSUER_OBLIGATION + + " SET inventory_revision = ? WHERE transition_id = ? AND inventory_revision = ?", + decimal(nextRevision), + transitionId, + decimal(oldRevision)), + "Original NEW issuer-index obligation changed before first dispatch claim"); + requireOne( + transaction.execute( + "UPDATE " + + REGION_OBLIGATION + + " SET inventory_revision = ? WHERE transition_id = ? AND inventory_revision = ?", + decimal(nextRevision), + transitionId, + decimal(oldRevision)), + "Original NEW region obligation changed before first dispatch claim"); + requireOne( + transaction.execute( + "UPDATE " + + RESERVATION + + " SET inventory_revision = ? WHERE reservation_id = ? AND transition_id = ?" + + " AND lifecycle = 'RESERVED' AND inventory_revision = ?", + decimal(nextRevision), + evidence.candidateReservation().reservationId(), + transitionId, + decimal(oldRevision)), + "Original NEW issuer reservation changed before first dispatch claim"); + } + private static void bumpInventoryClock( DSLContext transaction, BigInteger currentRevision, BigInteger nextRevision) { requireOne( @@ -1477,7 +1667,18 @@ CanonicalGameplayBindingTransitionSnapshot markProvisional( CanonicalGameplayBindingTransitionSnapshot markProvisional( CanonicalGameplayBindingProvisionalCasEvidence expectedEvidence, CanonicalGameplayAdmissionDecision expectedDecision) { + return markProvisional(expectedEvidence, expectedDecision, null, null); + } + + private CanonicalGameplayBindingTransitionSnapshot markProvisional( + CanonicalGameplayBindingProvisionalCasEvidence expectedEvidence, + CanonicalGameplayAdmissionDecision expectedDecision, + CanonicalGameplayOriginalNewCandidate candidate, + CanonicalGameplayOriginalNewCandidateRedisOwner.PhysicalReadback readback) { Objects.requireNonNull(expectedEvidence, "expectedEvidence"); + if ((candidate == null) != (readback == null)) { + throw new IllegalArgumentException("Candidate and owner readback must be supplied together"); + } return dsl.transactionResult( configuration -> { DSLContext transaction = DSL.using(configuration); @@ -1501,6 +1702,68 @@ CanonicalGameplayBindingTransitionSnapshot markProvisional( throw conflict( "First-binding provisional publication requires the exact Account lease decision"); } + boolean originalNew = current.expectedPrior() == null && expectedDecision != null; + if (originalNew && candidate != null) { + if (readback == null) throw conflict("Original NEW readback source is unavailable"); + requireDecisionMatchesOperation(expectedDecision, current); + CanonicalGameplayOriginalNewCandidate actualCandidate; + try { + actualCandidate = + CanonicalGameplayOriginalNewCandidate.fromOriginalSources( + current, expectedDecision); + } catch (RuntimeException invalidSource) { + throw conflict("Original NEW candidate sources are not exact"); + } + if (!actualCandidate.equals(candidate) + || !candidate.matchesOriginalDecision(expectedDecision) + || !candidate.matchesProvisionalSources(current) + || !readback.matches(candidate, current)) { + throw conflict("Owner readback does not bind the exact original NEW source"); + } + Record installation = findTransition(transaction, current.transition().transitionId()); + byte[] storedCandidate = installation.get("original_new_candidate_bytes", byte[].class); + String storedCandidateDigest = + installation.get("original_new_candidate_digest", String.class); + String installationState = + installation.get("original_new_candidate_state", String.class); + String storedReadbackDigest = + installation.get("original_new_candidate_readback_digest", String.class); + if (storedCandidate == null + || !Arrays.equals(storedCandidate, candidate.canonicalBytes()) + || !Objects.equals( + storedCandidateDigest, + CanonicalGameplayIssuerMemberV2Codec.sha256(storedCandidate))) { + throw conflict("Original NEW candidate bytes differ from the retained SQL source"); + } + if ("READBACK_CONFIRMED".equals(installationState)) { + if (!Objects.equals(storedReadbackDigest, readback.digest())) { + throw conflict("Original NEW candidate has a different retained physical readback"); + } + } else if ("DISPATCH_POSSIBLE".equals(installationState) + && current.transition().status() + == CanonicalGameplayBindingTransitionSnapshot.Status.PREPARED) { + requireOne( + transaction.execute( + "UPDATE " + + TRANSITION + + " SET original_new_candidate_state = 'READBACK_CONFIRMED'," + + " original_new_candidate_readback_digest = ?" + + " WHERE transition_id = ? AND status = 'PREPARED'" + + " AND original_new_candidate_bytes = ?" + + " AND original_new_candidate_digest = ?" + + " AND original_new_candidate_state = 'DISPATCH_POSSIBLE'" + + " AND original_new_candidate_readback_digest IS NULL", + readback.digest(), + current.transition().transitionId(), + candidate.canonicalBytes(), + storedCandidateDigest), + "Original NEW candidate readback source changed before provisional CAS"); + } else { + throw conflict("Original NEW candidate is not in a readback-confirmable state"); + } + } else if (candidate != null || readback != null) { + throw conflict("Original NEW candidate readback cannot authorize a transfer"); + } if (current.transition().status() == CanonicalGameplayBindingTransitionSnapshot.Status.PROVISIONAL) { Record row = findTransition(transaction, current.transition().transitionId()); @@ -4636,6 +4899,69 @@ private record AccountCoverageControl( BigInteger coverageGeneration, CanonicalGameplayAccountCoverageEvidence evidence) {} + enum OriginalNewCandidateInstallationState { + DISPATCH_POSSIBLE, + READBACK_CONFIRMED + } + + /** SQL-issued, one-use permission returned only by the transaction that first claims dispatch. */ + static final class OriginalNewCandidateCreatePermission { + private boolean consumed; + + private OriginalNewCandidateCreatePermission() {} + + synchronized boolean consume() { + if (consumed) return false; + consumed = true; + return true; + } + } + + /** + * Exact SQL source plus the optional first-dispatch permission; constructors stay + * repository-owned. + */ + static final class OriginalNewCandidateInstallationClaim { + private final CanonicalGameplayBindingProvisionalCasEvidence evidence; + private final CanonicalGameplayAdmissionDecision originalDecision; + private final CanonicalGameplayOriginalNewCandidate candidate; + private final OriginalNewCandidateInstallationState state; + private final OriginalNewCandidateCreatePermission createPermission; + + private OriginalNewCandidateInstallationClaim( + CanonicalGameplayBindingProvisionalCasEvidence evidence, + CanonicalGameplayAdmissionDecision originalDecision, + CanonicalGameplayOriginalNewCandidate candidate, + OriginalNewCandidateInstallationState state, + OriginalNewCandidateCreatePermission createPermission) { + this.evidence = Objects.requireNonNull(evidence, "evidence"); + this.originalDecision = Objects.requireNonNull(originalDecision, "originalDecision"); + this.candidate = Objects.requireNonNull(candidate, "candidate"); + this.state = Objects.requireNonNull(state, "state"); + this.createPermission = createPermission; + } + + CanonicalGameplayBindingProvisionalCasEvidence evidence() { + return evidence; + } + + CanonicalGameplayAdmissionDecision originalDecision() { + return originalDecision; + } + + CanonicalGameplayOriginalNewCandidate candidate() { + return candidate; + } + + OriginalNewCandidateInstallationState state() { + return state; + } + + boolean consumeCreatePermission() { + return createPermission != null && createPermission.consume(); + } + } + private static void requireOne(int changed, String message) { if (changed != 1) { throw conflict(message); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerCohortSql.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerCohortSql.java index ff7eae1fc0..ad5ea91fba 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerCohortSql.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerCohortSql.java @@ -15,9 +15,14 @@ final class CanonicalGameplayIssuerCohortSql { + " t.inventory_revision AS source_revision," // Preserve frozen pre-V1035 transition bytes for the absence-equivalent new NULL field. // A definitive abort UUID remains part of the full captured source. - + " CASE WHEN to_jsonb(t)->'admission_orphan_cleanup_id' = 'null'::jsonb" - + " THEN (to_jsonb(t) - 'admission_orphan_cleanup_id')::text" - + " ELSE to_jsonb(t)::text END AS source_row_json" + + " (CASE WHEN to_jsonb(t)->'admission_orphan_cleanup_id' = 'null'::jsonb" + + " THEN to_jsonb(t) - 'admission_orphan_cleanup_id'" + + " ELSE to_jsonb(t) END" + // V1048 preserves old pending cohorts until an actual candidate dispatch is claimed. + + " - CASE WHEN to_jsonb(t)->'original_new_candidate_bytes' = 'null'::jsonb" + + " THEN ARRAY['original_new_candidate_bytes', 'original_new_candidate_digest'," + + " 'original_new_candidate_state', 'original_new_candidate_readback_digest']" + + " ELSE ARRAY[]::text[] END)::text AS source_row_json" + " FROM game_session_canonical_binding_transition t WHERE t.inventory_revision <= ?" + " UNION ALL SELECT CASE WHEN r.issuer_id = ? THEN 'RESERVATION'" + " ELSE 'UNRESOLVED_LEGACY_RESERVATION' END AS source_kind," diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewAuthenticatedSession.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewAuthenticatedSession.java new file mode 100644 index 0000000000..931c526903 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewAuthenticatedSession.java @@ -0,0 +1,587 @@ +package net.firedevops.firemud.gamesession.repository; + +import com.fasterxml.jackson.core.JsonFactory; +import com.fasterxml.jackson.core.StreamReadConstraints; +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.ByteBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.time.Clock; +import java.util.Arrays; +import java.util.Base64; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseGrpcCodec; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; + +/** + * Strict in-memory ORIGINAL_NEW gameplay-session payload template and schema-2 reader. + * + *

{@link Template} produces only the canonical bytes consumed by the final tenant-local session + * CAS. Its two unique time placeholders are never a finalized session and must never be persisted + * as a session record. Only {@link #parseFinalized(byte[], Clock)} accepts a complete schema-2 + * value. This class parses and correlates data; it does not perform the final CAS or prove current + * Account, Redis-registry, lease, barrier, or gameplay-admission authority. + */ +public final class CanonicalGameplayOriginalNewAuthenticatedSession { + public static final int SCHEMA_VERSION = 2; + public static final int MAX_SESSION_BYTES = 1024 * 1024; + public static final long MAX_CANONICAL_SESSION_DURATION_MILLIS = 300_000L; + public static final long FINAL_ADMISSION_CLOCK_SKEW_MILLIS = 5_000L; + + private static final String ADMISSION_AT_PLACEHOLDER = "__ORIGINAL_NEW_ADMISSION_AT_MS__"; + private static final String CONTINUITY_PLACEHOLDER = "__ORIGINAL_NEW_CONTINUITY_EXPIRES_AT_MS__"; + private static final Pattern SHA256 = Pattern.compile("[0-9a-f]{64}"); + private static final Pattern POSITIVE_DECIMAL = Pattern.compile("[1-9][0-9]{0,18}"); + private static final JsonFactory JSON_FACTORY = + JsonFactory.builder() + .streamReadConstraints( + StreamReadConstraints.builder() + .maxNestingDepth(64) + .maxStringLength(MAX_SESSION_BYTES) + .maxNumberLength(16) + .build()) + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .build(); + private static final ObjectMapper JSON = + new ObjectMapper(JSON_FACTORY).enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS); + private static final Set SESSION_FIELDS = + Set.of( + "schemaVersion", + "admissionState", + "originalCandidate", + "bindingGeneration", + "accountIndexState", + "issuerIndexState", + "regionBridgeState", + "admissionAt", + "authTokenHash", + "authTokenIssuedAt", + "authTokenExpiresAt", + "tokenGeneration", + "issuanceFence", + "rebindHandle", + "continuityBindingExpiresAt", + "membershipBaseline", + "authorityTuple", + "outboxCheckpoints", + "canonicalSessionDurationMillis"); + private static final Set AUTHENTICATION_FIELDS = + Set.of( + "authTokenHash", + "authTokenIssuedAt", + "authTokenExpiresAt", + "tokenGeneration", + "issuanceFence", + "rebindHandle", + "continuityBindingExpiresAt", + "membershipBaseline", + "authorityTuple", + "outboxCheckpoints"); + + private CanonicalGameplayOriginalNewAuthenticatedSession() {} + + /** + * Verifies Account's complete signed result and freezes a non-persistable final-CAS template. + * + *

The duration must be the canonical, already-frozen session duration. The returned bytes + * contain the exact candidate and unchanged Account membership, tuple, and checkpoint values. + */ + public static Template template( + CanonicalGameplayOriginalNewCandidate originalCandidate, + AccountGameplayAdmissionLeaseGrpcCodec.OriginalNewCredential accountCredential, + CanonicalGameplayOriginalNewBoundCredentialVerifier credentialVerifier, + long canonicalSessionDurationMillis) { + Objects.requireNonNull(originalCandidate, "original NEW candidate is required"); + Objects.requireNonNull(accountCredential, "Account credential is required"); + Objects.requireNonNull(credentialVerifier, "bound credential verifier is required"); + requireCanonicalDuration(canonicalSessionDurationMillis); + + byte[] candidateBytes = null; + try (var verified = credentialVerifier.verify(originalCandidate, accountCredential)) { + candidateBytes = originalCandidate.canonicalBytes(); + CanonicalGameplayOriginalNewCandidate exactCandidate = + CanonicalGameplayOriginalNewCandidate.parseCanonical(candidateBytes); + if (!exactCandidate.exactlyMatches(candidateBytes)) throw invalid(); + byte[] templateBytes = makeTemplate(exactCandidate, verified, canonicalSessionDurationMillis); + try { + requireTemplateOnlyHasTimePlaceholders(templateBytes); + return new Template( + templateBytes, credentialVerifier.clock(), canonicalSessionDurationMillis); + } finally { + wipe(templateBytes); + } + } finally { + wipe(candidateBytes); + } + } + + /** + * Strictly reads a completed schema-2 session without establishing current admission authority. + */ + public static Finalized parseFinalized(byte[] encoded, Clock clock) { + Objects.requireNonNull(clock, "clock is required"); + if (encoded == null || encoded.length == 0 || encoded.length > MAX_SESSION_BYTES) { + throw invalid(); + } + byte[] handle = null; + byte[] canonical = null; + byte[] candidateBytes = null; + try { + String json = strictUtf8(encoded); + JsonNode parsed = JSON.readTree(json); + if (!(parsed instanceof ObjectNode root)) throw invalid(); + requireExactFields(root, SESSION_FIELDS); + requireSchemaAndAcknowledgements(root); + + candidateBytes = canonicalNode(root.get("originalCandidate")); + CanonicalGameplayOriginalNewCandidate candidate = + CanonicalGameplayOriginalNewCandidate.parseCanonical(candidateBytes); + AccountGameplayAdmissionLeaseEvidence lease = candidate.leaseEvidence(); + requireBindingAnchors(root, candidate, lease); + + String admissionAt = requiredText(root, "admissionAt"); + String continuityExpires = requiredText(root, "continuityBindingExpiresAt"); + String tokenHash = requiredText(root, "authTokenHash"); + String issuedAt = requiredText(root, "authTokenIssuedAt"); + String expiresAt = requiredText(root, "authTokenExpiresAt"); + String tokenGeneration = requiredText(root, "tokenGeneration"); + String issuanceFence = requiredText(root, "issuanceFence"); + String encodedHandle = requiredText(root, "rebindHandle"); + String duration = requiredText(root, "canonicalSessionDurationMillis"); + + if (!SHA256.matcher(tokenHash).matches()) throw invalid(); + long admissionAtMillis = positiveDecimal(admissionAt); + long continuityExpiresAtMillis = positiveDecimal(continuityExpires); + long tokenIssuedAtSeconds = positiveDecimal(issuedAt); + long tokenExpiresAtSeconds = positiveDecimal(expiresAt); + long issuanceFenceValue = positiveDecimal(issuanceFence); + long durationMillis = positiveDecimal(duration); + requireCanonicalDuration(durationMillis); + if (!"1".equals(tokenGeneration)) throw invalid(); + if (!issuanceFence.equals(lease.carrier().get("issuanceFence"))) { + throw invalid(); + } + if (tokenIssuedAtSeconds >= tokenExpiresAtSeconds + || tokenExpiresAtSeconds - tokenIssuedAtSeconds > 300L) throw invalid(); + long admissionAtSeconds = admissionAtMillis / 1000L; + if (tokenIssuedAtSeconds > safeAdd(admissionAtSeconds, 5L) + || tokenExpiresAtSeconds <= admissionAtSeconds) throw invalid(); + if (new java.math.BigInteger((String) lease.carrier().get("expiresAt")) + .compareTo(java.math.BigInteger.valueOf(admissionAtMillis)) + <= 0) throw invalid(); + if (continuityExpiresAtMillis != safeAdd(admissionAtMillis, durationMillis)) throw invalid(); + long nowMillis = clock.millis(); + if (nowMillis <= 0L + || admissionAtMillis > safeAdd(nowMillis, FINAL_ADMISSION_CLOCK_SKEW_MILLIS)) { + throw invalid(); + } + + handle = decodeHandle(encodedHandle); + canonical = canonicalNode(root); + if (!Arrays.equals(canonical, encoded)) throw invalid(); + return new Finalized( + canonical, + candidate, + admissionAtMillis, + continuityExpiresAtMillis, + tokenHash, + tokenIssuedAtSeconds, + tokenExpiresAtSeconds, + issuanceFence, + durationMillis, + handle); + } catch (RuntimeException rejected) { + throw invalid(); + } catch (Exception malformed) { + throw invalid(); + } finally { + wipe(handle); + wipe(canonical); + wipe(candidateBytes); + } + } + + private static byte[] makeTemplate( + CanonicalGameplayOriginalNewCandidate candidate, + CanonicalGameplayOriginalNewBoundCredentialVerifier.VerifiedBoundCredential credential, + long canonicalSessionDurationMillis) { + byte[] handle = null; + byte[] candidateBytes = null; + try { + handle = credential.opaqueRebindHandle(); + candidateBytes = candidate.canonicalBytes(); + ObjectNode root = JSON.createObjectNode(); + root.put("schemaVersion", SCHEMA_VERSION); + root.put("admissionState", "COMPLETE"); + root.set("originalCandidate", JSON.readTree(candidateBytes)); + root.put("bindingGeneration", candidate.transition().bindingGeneration().toString()); + root.put("accountIndexState", "ACKNOWLEDGED"); + root.put("issuerIndexState", "ACKNOWLEDGED"); + root.put("regionBridgeState", "ACKNOWLEDGED"); + root.put("admissionAt", ADMISSION_AT_PLACEHOLDER); + root.put("authTokenHash", credential.tokenHash()); + root.put("authTokenIssuedAt", Long.toString(credential.issuedAtEpochSeconds())); + root.put("authTokenExpiresAt", Long.toString(credential.expiresAtEpochSeconds())); + root.put("tokenGeneration", credential.tokenGeneration()); + root.put("issuanceFence", credential.issuanceFence()); + root.put("rebindHandle", Base64.getUrlEncoder().withoutPadding().encodeToString(handle)); + root.put("continuityBindingExpiresAt", CONTINUITY_PLACEHOLDER); + Map lease = candidate.leaseEvidence().carrier(); + root.set("membershipBaseline", JSON.valueToTree(lease.get("membershipBaseline"))); + root.set("authorityTuple", JSON.valueToTree(lease.get("authorityTuple"))); + root.set("outboxCheckpoints", JSON.valueToTree(lease.get("outboxCheckpoints"))); + root.put("canonicalSessionDurationMillis", Long.toString(canonicalSessionDurationMillis)); + return canonicalNode(root); + } catch (Exception malformed) { + throw invalid(); + } finally { + wipe(handle); + wipe(candidateBytes); + } + } + + private static void requireTemplateOnlyHasTimePlaceholders(byte[] templateBytes) { + try { + ObjectNode root = (ObjectNode) JSON.readTree(strictUtf8(templateBytes)); + requireExactFields(root, SESSION_FIELDS); + if (!ADMISSION_AT_PLACEHOLDER.equals(requiredText(root, "admissionAt")) + || !CONTINUITY_PLACEHOLDER.equals(requiredText(root, "continuityBindingExpiresAt"))) + throw invalid(); + root.fieldNames() + .forEachRemaining( + name -> { + if (!name.equals("admissionAt") && !name.equals("continuityBindingExpiresAt")) { + JsonNode value = root.get(name); + if (containsPlaceholder(value)) throw invalid(); + } + }); + } catch (Exception malformed) { + throw invalid(); + } + } + + private static boolean containsPlaceholder(JsonNode value) { + if (value.isTextual()) { + return ADMISSION_AT_PLACEHOLDER.equals(value.textValue()) + || CONTINUITY_PLACEHOLDER.equals(value.textValue()); + } + if (value.isObject()) { + var fields = value.fields(); + while (fields.hasNext()) if (containsPlaceholder(fields.next().getValue())) return true; + } else if (value.isArray()) { + for (JsonNode item : value) if (containsPlaceholder(item)) return true; + } + return false; + } + + private static void requireSchemaAndAcknowledgements(ObjectNode root) { + JsonNode schema = root.get("schemaVersion"); + if (schema == null + || !schema.isIntegralNumber() + || !schema.canConvertToInt() + || schema.intValue() != SCHEMA_VERSION) { + throw invalid(); + } + if (!"COMPLETE".equals(requiredText(root, "admissionState")) + || !"ACKNOWLEDGED".equals(requiredText(root, "accountIndexState")) + || !"ACKNOWLEDGED".equals(requiredText(root, "issuerIndexState")) + || !"ACKNOWLEDGED".equals(requiredText(root, "regionBridgeState"))) throw invalid(); + for (String field : AUTHENTICATION_FIELDS) { + JsonNode value = root.get(field); + if (value == null || value.isNull()) throw invalid(); + } + } + + private static void requireBindingAnchors( + ObjectNode root, + CanonicalGameplayOriginalNewCandidate candidate, + AccountGameplayAdmissionLeaseEvidence lease) + throws Exception { + if (!candidate + .transition() + .bindingGeneration() + .toString() + .equals(requiredText(root, "bindingGeneration"))) throw invalid(); + Map carrier = lease.carrier(); + requireCanonicalEqual(root.get("membershipBaseline"), carrier.get("membershipBaseline")); + requireCanonicalEqual(root.get("authorityTuple"), carrier.get("authorityTuple")); + requireCanonicalEqual(root.get("outboxCheckpoints"), carrier.get("outboxCheckpoints")); + } + + private static void requireCanonicalEqual(JsonNode node, Object source) throws Exception { + byte[] left = canonicalNode(node); + byte[] right = Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(source)); + try { + if (!Arrays.equals(left, right)) throw invalid(); + } finally { + wipe(left); + wipe(right); + } + } + + private static byte[] decodeHandle(String encoded) { + if (encoded.isEmpty() || !encoded.matches("[A-Za-z0-9_-]+")) throw invalid(); + try { + byte[] result = Base64.getUrlDecoder().decode(encoded); + if (result.length != 32 + || !Base64.getUrlEncoder().withoutPadding().encodeToString(result).equals(encoded)) { + wipe(result); + throw invalid(); + } + return result; + } catch (IllegalArgumentException malformed) { + throw invalid(); + } + } + + private static byte[] canonicalNode(JsonNode node) throws IOException { + if (node == null) throw invalid(); + byte[] canonical = Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(node)); + if (canonical.length > MAX_SESSION_BYTES) { + wipe(canonical); + throw invalid(); + } + return canonical; + } + + private static String strictUtf8(byte[] encoded) { + try { + return StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(encoded)) + .toString(); + } catch (CharacterCodingException malformed) { + throw invalid(); + } + } + + private static void requireExactFields(ObjectNode object, Set expected) { + Set actual = new java.util.HashSet<>(); + object.fieldNames().forEachRemaining(actual::add); + if (!actual.equals(expected)) throw invalid(); + } + + private static String requiredText(ObjectNode object, String field) { + JsonNode value = object.get(field); + if (value == null || !value.isTextual() || value.textValue().isEmpty()) throw invalid(); + return value.textValue(); + } + + private static long positiveDecimal(String value) { + if (value == null || !POSITIVE_DECIMAL.matcher(value).matches()) throw invalid(); + try { + return Long.parseLong(value); + } catch (NumberFormatException malformed) { + throw invalid(); + } + } + + private static void requireCanonicalDuration(long value) { + if (value <= 0L || value > MAX_CANONICAL_SESSION_DURATION_MILLIS) throw invalid(); + } + + private static long safeAdd(long left, long right) { + try { + return Math.addExact(left, right); + } catch (ArithmeticException malformed) { + throw invalid(); + } + } + + private static void wipe(byte[] value) { + if (value != null) Arrays.fill(value, (byte) 0); + } + + private static IllegalArgumentException invalid() { + return new IllegalArgumentException("Canonical ORIGINAL_NEW authenticated session is invalid"); + } + + /** In-memory pre-final-CAS bytes. Closing overwrites the encoded opaque handle. */ + public static final class Template implements AutoCloseable { + private byte[] canonicalTemplateBytes; + private final Clock clock; + private final long canonicalSessionDurationMillis; + + private Template( + byte[] canonicalTemplateBytes, Clock clock, long canonicalSessionDurationMillis) { + this.canonicalTemplateBytes = canonicalTemplateBytes.clone(); + this.clock = Objects.requireNonNull(clock); + this.canonicalSessionDurationMillis = canonicalSessionDurationMillis; + } + + public long canonicalSessionDurationMillis() { + return canonicalSessionDurationMillis; + } + + /** Exact canonical preimage for the final CAS; the two time strings are not final values. */ + public byte[] finalCasTemplateBytes() { + if (canonicalTemplateBytes == null) + throw new IllegalStateException("Session template is closed"); + return canonicalTemplateBytes.clone(); + } + + /** Validates final-CAS readback and allows only the two server-time values to differ. */ + public Finalized requireFinalizedReadback(byte[] finalCasReadback) { + if (canonicalTemplateBytes == null) + throw new IllegalStateException("Session template is closed"); + Finalized finalized = parseFinalized(finalCasReadback, clock); + byte[] templateCopy = canonicalTemplateBytes.clone(); + byte[] expected = null; + byte[] readbackBytes = null; + try { + ObjectNode root = (ObjectNode) JSON.readTree(strictUtf8(templateCopy)); + root.put("admissionAt", Long.toString(finalized.admissionAtMillis())); + root.put( + "continuityBindingExpiresAt", + Long.toString(finalized.continuityBindingExpiresAtMillis())); + expected = canonicalNode(root); + readbackBytes = finalized.canonicalBytes(); + if (!Arrays.equals(expected, readbackBytes)) throw invalid(); + return finalized; + } catch (RuntimeException rejected) { + finalized.close(); + throw invalid(); + } catch (Exception malformed) { + finalized.close(); + throw invalid(); + } finally { + wipe(templateCopy); + wipe(expected); + wipe(readbackBytes); + } + } + + @Override + public void close() { + wipe(canonicalTemplateBytes); + canonicalTemplateBytes = null; + } + + @Override + public String toString() { + return "CanonicalGameplayOriginalNewAuthenticatedSession.Template[nonAdmitting,redacted]"; + } + } + + /** Strictly decoded complete schema-2 bytes; the value itself supplies no current authority. */ + public static final class Finalized implements AutoCloseable { + private byte[] canonicalBytes; + private byte[] opaqueRebindHandle; + private final CanonicalGameplayOriginalNewCandidate originalCandidate; + private final long admissionAtMillis; + private final long continuityBindingExpiresAtMillis; + private final String authTokenHash; + private final long authTokenIssuedAt; + private final long authTokenExpiresAt; + private final String issuanceFence; + private final long canonicalSessionDurationMillis; + + private Finalized( + byte[] canonicalBytes, + CanonicalGameplayOriginalNewCandidate originalCandidate, + long admissionAtMillis, + long continuityBindingExpiresAtMillis, + String authTokenHash, + long authTokenIssuedAt, + long authTokenExpiresAt, + String issuanceFence, + long canonicalSessionDurationMillis, + byte[] opaqueRebindHandle) { + this.canonicalBytes = canonicalBytes.clone(); + this.originalCandidate = originalCandidate; + this.admissionAtMillis = admissionAtMillis; + this.continuityBindingExpiresAtMillis = continuityBindingExpiresAtMillis; + this.authTokenHash = authTokenHash; + this.authTokenIssuedAt = authTokenIssuedAt; + this.authTokenExpiresAt = authTokenExpiresAt; + this.issuanceFence = issuanceFence; + this.canonicalSessionDurationMillis = canonicalSessionDurationMillis; + this.opaqueRebindHandle = opaqueRebindHandle.clone(); + } + + public byte[] canonicalBytes() { + if (canonicalBytes == null) throw new IllegalStateException("Finalized session is closed"); + return canonicalBytes.clone(); + } + + public CanonicalGameplayOriginalNewCandidate originalCandidate() { + return originalCandidate; + } + + public CanonicalGameplayOriginalNewCandidate candidate() { + return originalCandidate; + } + + public long admissionAtMillis() { + return admissionAtMillis; + } + + public long continuityBindingExpiresAtMillis() { + return continuityBindingExpiresAtMillis; + } + + public long continuityExpiresAtMillis() { + return continuityBindingExpiresAtMillis; + } + + public String authTokenHash() { + return authTokenHash; + } + + public long authTokenIssuedAt() { + return authTokenIssuedAt; + } + + public long authTokenExpiresAt() { + return authTokenExpiresAt; + } + + public String tokenGeneration() { + return "1"; + } + + public String issuanceFence() { + return issuanceFence; + } + + public long canonicalSessionDurationMillis() { + return canonicalSessionDurationMillis; + } + + /** Returns only a caller-owned copy; Account remains the sole handle resolver. */ + public byte[] opaqueRebindHandle() { + if (opaqueRebindHandle == null) + throw new IllegalStateException("Finalized session is closed"); + return opaqueRebindHandle.clone(); + } + + public byte[] rebindHandle() { + return opaqueRebindHandle(); + } + + @Override + public void close() { + wipe(canonicalBytes); + wipe(opaqueRebindHandle); + canonicalBytes = null; + opaqueRebindHandle = null; + } + + @Override + public String toString() { + return "CanonicalGameplayOriginalNewAuthenticatedSession.Finalized[complete,redacted]"; + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewBoundCredentialVerifier.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewBoundCredentialVerifier.java new file mode 100644 index 0000000000..e6df4341a8 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewBoundCredentialVerifier.java @@ -0,0 +1,318 @@ +package net.firedevops.firemud.gamesession.repository; + +import com.fasterxml.jackson.databind.ObjectMapper; +import java.math.BigDecimal; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.Clock; +import java.util.Arrays; +import java.util.HashSet; +import java.util.HexFormat; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseGrpcCodec; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.security.AccountAsymmetricJwtVerifier; +import net.firedevops.firemud.common.security.AccountAsymmetricJwtVerifier.ExplicitRouteProfilePolicy; +import net.firedevops.firemud.common.security.AccountAsymmetricJwtVerifier.VerifiedClaims; +import net.firedevops.firemud.common.security.AccountPublicJwksCache; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationJwtProfileValidator; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; + +/** + * Verifies the Account-signed, tenant-bound ORIGINAL_NEW credential and its exact lease anchors. + * + *

This checks signature and claim/source shape only. It does not prove current Account + * authority, token-registry status, final admission, or gameplay admission. Those predicates stay + * with their owning readers and the final session CAS. + */ +public final class CanonicalGameplayOriginalNewBoundCredentialVerifier { + private static final ObjectMapper JSON = new ObjectMapper(); + private static final long ALLOWED_CLOCK_SKEW_SECONDS = 5L; + private static final ExplicitRouteProfilePolicy ORIGINAL_NEW_POLICY = policy(); + + private final AccountAsymmetricJwtVerifier verifier; + private final Clock clock; + + /** Requires the caller to supply the already configured trusted Account JWKS cache. */ + public CanonicalGameplayOriginalNewBoundCredentialVerifier( + AccountPublicJwksCache trustedAccountJwks, Clock clock) { + this.clock = Objects.requireNonNull(clock, "clock is required"); + this.verifier = + new AccountAsymmetricJwtVerifier( + Objects.requireNonNull(trustedAccountJwks, "trusted Account JWKS cache is required"), + clock); + } + + VerifiedBoundCredential verify( + CanonicalGameplayOriginalNewCandidate candidate, + AccountGameplayAdmissionLeaseGrpcCodec.OriginalNewCredential accountCredential) { + Objects.requireNonNull(candidate, "original NEW candidate is required"); + Objects.requireNonNull(accountCredential, "Account credential is required"); + byte[] compactBytes = null; + byte[] handle = null; + try { + String compactJwt = accountCredential.signedBoundGsACompactJwt(); + if (compactJwt == null + || compactJwt.isEmpty() + || compactJwt.length() > GameSessionAccountDelegationProfile.MAX_COMPACT_JWT_BYTES + || compactJwt.chars().anyMatch(value -> value > 0x7f)) { + throw invalid(); + } + compactBytes = compactJwt.getBytes(StandardCharsets.US_ASCII); + String tokenHash = sha256(compactBytes); + if (!tokenHash.equals(accountCredential.tokenSha256())) throw invalid(); + + VerifiedClaims verified = verifier.verify(compactJwt, ORIGINAL_NEW_POLICY); + Map claims = verified.claims(); + Map lease = candidate.leaseEvidence().carrier(); + Map bindingScope = object(lease.get("bindingScope")); + Map membershipBaseline = object(lease.get("membershipBaseline")); + Map tokenIdentityEvidence = object(lease.get("tokenIdentityEvidence")); + Object authorityTuple = lease.get("authorityTuple"); + Object checkpoints = lease.get("outboxCheckpoints"); + + String accountId = candidate.bindingIdentity().accountId().toString(); + String tenantId = candidate.bindingIdentity().tenantId().toString(); + String initialJti = text(tokenIdentityEvidence.get("tokenJti")); + String originalLeaseId = text(lease.get("leaseId")); + String issuedFence = text(lease.get("issuanceFence")); + String boundJti = accountCredential.tokenJti().toString(); + UUID lineageId = accountCredential.lineageId(); + long nowSeconds = clock.instant().getEpochSecond(); + long issuedAt = positiveEpochSecond(claims.get("iat")); + long notBefore = positiveEpochSecond(claims.get("nbf")); + long expiresAt = positiveEpochSecond(claims.get("exp")); + + if (!accountId.equals(bindingScope.get("accountId")) + || !tenantId.equals(bindingScope.get("tenantId")) + || !accountId.equals(claims.get("sub")) + || !accountId.equals(claims.get("accountId")) + || !tenantId.equals(claims.get("tenantId")) + || !boundJti.equals(claims.get("jti")) + || boundJti.equals(initialJti) + || lineageId.equals(accountCredential.tokenJti()) + || !"1".equals(claims.get("tokenGeneration")) + || !issuedFence.equals(claims.get("issuanceFence")) + || accountCredential.issuanceFence() != positiveDecimal(issuedFence) + || !originalLeaseId.equals(accountCredential.originalLeaseId().toString()) + || candidate.leaseEvidence().leaseFence().longValueExact() + != accountCredential.originalLeaseFence() + || !canonicalEquals(authorityTuple, claims.get("authorityTuple")) + || !canonicalEquals( + membershipBaseline.get("membershipVersion"), claims.get("membershipVersion")) + || !candidate + .leaseEvidence() + .leaseKind() + .equals(AccountGameplayAdmissionLeaseEvidence.LeaseKind.NEW_BINDING) + || !accountCredential.checkpointsSha256().equals(sha256Canonical(checkpoints))) { + throw invalid(); + } + + String membershipGeneration = text(membershipBaseline.get("membershipAuthorityGeneration")); + Map tuple = object(authorityTuple); + Map membershipAuthority = object(tuple.get("membershipAuthorityGeneration")); + if (!membershipGeneration.equals(membershipAuthority.get(tenantId))) throw invalid(); + + if (issuedAt > safeAdd(nowSeconds, ALLOWED_CLOCK_SKEW_SECONDS) + || notBefore > safeAdd(nowSeconds, ALLOWED_CLOCK_SKEW_SECONDS) + || expiresAt <= nowSeconds + || notBefore > expiresAt + || issuedAt >= expiresAt + || safeSubtract(notBefore, issuedAt) > ALLOWED_CLOCK_SKEW_SECONDS + || safeSubtract(issuedAt, notBefore) > ALLOWED_CLOCK_SKEW_SECONDS + || safeSubtract(expiresAt, issuedAt) + > GameSessionAccountDelegationProfile.MAX_TOKEN_LIFETIME_SECONDS) { + throw invalid(); + } + + handle = accountCredential.opaqueRebindHandle(); + if (handle.length != 32) throw invalid(); + return new VerifiedBoundCredential(tokenHash, issuedAt, expiresAt, "1", issuedFence, handle); + } catch (AccountAsymmetricJwtVerifier.VerificationUnavailableException unavailable) { + throw unavailable; + } catch (RuntimeException rejected) { + throw invalid(); + } catch (Exception malformed) { + throw invalid(); + } finally { + wipe(compactBytes); + wipe(handle); + } + } + + Clock clock() { + return clock; + } + + private static ExplicitRouteProfilePolicy policy() { + Set required = + new HashSet<>(GameSessionAccountDelegationJwtProfileValidator.REQUIRED_CLAIMS); + required.add("tenantId"); + return new ExplicitRouteProfilePolicy( + "game-session-original-new-bound-credential", + GameSessionAccountDelegationProfile.PROFILE, + GameSessionAccountDelegationProfile.TYPE, + GameSessionAccountDelegationProfile.ISSUER, + GameSessionAccountDelegationProfile.AUDIENCE, + required, + Set.of(), + GameSessionAccountDelegationProfile.MAX_TOKEN_LIFETIME_SECONDS, + ALLOWED_CLOCK_SKEW_SECONDS, + GameSessionAccountDelegationProfile.MAX_COMPACT_JWT_BYTES, + GameSessionAccountDelegationJwtProfileValidator::validatePublicTenantBoundClaims); + } + + private static boolean canonicalEquals(Object left, Object right) throws Exception { + byte[] leftBytes = null; + byte[] rightBytes = null; + try { + leftBytes = canonicalBytes(left); + rightBytes = canonicalBytes(right); + return Arrays.equals(leftBytes, rightBytes); + } finally { + wipe(leftBytes); + wipe(rightBytes); + } + } + + private static byte[] canonicalBytes(Object value) throws Exception { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } + + private static String sha256Canonical(Object value) throws Exception { + byte[] canonical = canonicalBytes(value); + try { + return sha256(canonical); + } finally { + wipe(canonical); + } + } + + private static String sha256(byte[] bytes) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException unavailable) { + throw new IllegalStateException("SHA-256 is unavailable", unavailable); + } + } + + private static Map object(Object value) { + if (!(value instanceof Map map)) throw invalid(); + return map; + } + + private static String text(Object value) { + if (!(value instanceof String text) || text.isBlank()) throw invalid(); + return text; + } + + private static long positiveEpochSecond(Object value) { + if (!(value instanceof Number number)) throw invalid(); + try { + long seconds = new BigDecimal(number.toString()).longValueExact(); + if (seconds <= 0L) throw invalid(); + return seconds; + } catch (ArithmeticException | NumberFormatException malformed) { + throw invalid(); + } + } + + private static long positiveDecimal(String value) { + if (value == null || !value.matches("[1-9][0-9]{0,18}")) throw invalid(); + try { + return Long.parseLong(value); + } catch (NumberFormatException malformed) { + throw invalid(); + } + } + + private static long safeAdd(long left, long right) { + try { + return Math.addExact(left, right); + } catch (ArithmeticException malformed) { + throw invalid(); + } + } + + private static long safeSubtract(long left, long right) { + try { + return Math.subtractExact(left, right); + } catch (ArithmeticException malformed) { + throw invalid(); + } + } + + private static void wipe(byte[] value) { + if (value != null) Arrays.fill(value, (byte) 0); + } + + private static IllegalArgumentException invalid() { + return new IllegalArgumentException("Original NEW bound credential is invalid"); + } + + static final class VerifiedBoundCredential implements AutoCloseable { + private final String tokenHash; + private final long issuedAtEpochSeconds; + private final long expiresAtEpochSeconds; + private final String tokenGeneration; + private final String issuanceFence; + private byte[] opaqueRebindHandle; + + private VerifiedBoundCredential( + String tokenHash, + long issuedAtEpochSeconds, + long expiresAtEpochSeconds, + String tokenGeneration, + String issuanceFence, + byte[] opaqueRebindHandle) { + this.tokenHash = tokenHash; + this.issuedAtEpochSeconds = issuedAtEpochSeconds; + this.expiresAtEpochSeconds = expiresAtEpochSeconds; + this.tokenGeneration = tokenGeneration; + this.issuanceFence = issuanceFence; + this.opaqueRebindHandle = opaqueRebindHandle.clone(); + } + + String tokenHash() { + return tokenHash; + } + + long issuedAtEpochSeconds() { + return issuedAtEpochSeconds; + } + + long expiresAtEpochSeconds() { + return expiresAtEpochSeconds; + } + + String tokenGeneration() { + return tokenGeneration; + } + + String issuanceFence() { + return issuanceFence; + } + + byte[] opaqueRebindHandle() { + if (opaqueRebindHandle == null) + throw new IllegalStateException("Verified credential is closed"); + return opaqueRebindHandle.clone(); + } + + @Override + public void close() { + wipe(opaqueRebindHandle); + opaqueRebindHandle = null; + } + + @Override + public String toString() { + return "VerifiedBoundCredential[metadata-only,handle-redacted]"; + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCandidateRedisOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCandidateRedisOwner.java new file mode 100644 index 0000000000..a618773a8b --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCandidateRedisOwner.java @@ -0,0 +1,547 @@ +package net.firedevops.firemud.gamesession.repository; + +import io.lettuce.core.RedisClient; +import io.lettuce.core.RedisFuture; +import io.lettuce.core.ScriptOutputType; +import io.lettuce.core.api.StatefulRedisConnection; +import io.lettuce.core.api.async.RedisAsyncCommands; +import io.lettuce.core.codec.ByteArrayCodec; +import java.io.ByteArrayOutputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.util.Arrays; +import java.util.HexFormat; +import java.util.List; +import java.util.Objects; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingIdentity; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingProvisionalCasEvidence; +import net.firedevops.firemud.gamesession.service.CanonicalGameplayOriginalNewCandidateRedisScriptContribution; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Manual, unregistered owner for one original public-production NEW candidate installation. The + * result and physical readback remain explicitly non-admitting. + */ +public final class CanonicalGameplayOriginalNewCandidateRedisOwner { + private static final String PRINCIPAL = "gamesession_coord_app"; + private static final int MAX_SCRIPT_BYTES = 32 * 1024; + private static final int MAX_CANDIDATE_BYTES = 512 * 1024; + private static final long COMMAND_TIMEOUT_MILLIS = 5_000; + private static final List EXPECTED_KEYS = + List.of( + new RedisScriptDescriptor.KeySpec( + "session", "session:game:", RedisScriptDescriptor.HashTagDeclaration.REQUIRED), + new RedisScriptDescriptor.KeySpec( + "characterIndex", + "session:game:index:character:", + RedisScriptDescriptor.HashTagDeclaration.REQUIRED), + new RedisScriptDescriptor.KeySpec( + "accountTenantIndex", + "session:game:index:account-tenant:", + RedisScriptDescriptor.HashTagDeclaration.REQUIRED), + new RedisScriptDescriptor.KeySpec( + "tenantIndex", + "session:game:index:tenant:", + RedisScriptDescriptor.HashTagDeclaration.REQUIRED)); + private static final List EXPECTED_ARGUMENTS = + List.of( + new RedisScriptDescriptor.ArgumentSpec("purpose"), + new RedisScriptDescriptor.ArgumentSpec("tenantId"), + new RedisScriptDescriptor.ArgumentSpec("accountId"), + new RedisScriptDescriptor.ArgumentSpec("playableStateNamespaceId"), + new RedisScriptDescriptor.ArgumentSpec("characterId"), + new RedisScriptDescriptor.ArgumentSpec("gameInstanceId"), + new RedisScriptDescriptor.ArgumentSpec("sessionId"), + new RedisScriptDescriptor.ArgumentSpec("bindingGeneration"), + new RedisScriptDescriptor.ArgumentSpec("tenantGameplayTag"), + new RedisScriptDescriptor.ArgumentSpec("candidateBytes")); + private static final List EXPECTED_OUTCOMES = + List.of( + outcome( + "CANDIDATE_CREATED", + RedisScriptDescriptor.OutcomeCategory.SUCCESS, + RedisScriptDescriptor.MutationEffect.MUTATING), + outcome( + "EXISTING_STATE_REFUSED", + RedisScriptDescriptor.OutcomeCategory.STALE, + RedisScriptDescriptor.MutationEffect.NON_MUTATING), + outcome( + "INVALID_ARGUMENTS", + RedisScriptDescriptor.OutcomeCategory.VALIDATION_FAILURE, + RedisScriptDescriptor.MutationEffect.NON_MUTATING)); + + private final RedisClient redisClient; + private final RedisScriptCatalog catalog; + private final CanonicalGameplayBindingInventoryRepository inventory; + private final CanonicalGameplayTenantGameplayTagRepository tenantTags; + + CanonicalGameplayOriginalNewCandidateRedisOwner( + RedisClient redisClient, + RedisScriptCatalog catalog, + CanonicalGameplayBindingInventoryRepository inventory, + CanonicalGameplayTenantGameplayTagRepository tenantTags) { + this.redisClient = Objects.requireNonNull(redisClient, "Configured Redis client required"); + this.catalog = Objects.requireNonNull(catalog, "Manual Redis script catalog required"); + this.inventory = Objects.requireNonNull(inventory, "Binding inventory repository required"); + this.tenantTags = Objects.requireNonNull(tenantTags, "Persisted tenant-tag owner required"); + } + + /** + * Uses the one SQL-issued create permission or performs only current physical readback. Exact + * readback is then accepted through the existing source/Account/runtime-guarded provisional CAS. + */ + public Installation installOnce( + net.firedevops.firemud.gamesession.binding.CanonicalGameplayAdmissionDecision + originalDecision) { + Objects.requireNonNull(originalDecision, "original Account decision"); + requireNoAmbientTransaction(); + CanonicalGameplayBindingInventoryRepository.OriginalNewCandidateInstallationClaim claim = + inventory.claimOriginalNewCandidateInstallation(originalDecision); + return installClaimOnce(claim); + } + + /** Package seam for the actual SQL-issued single-use claim; no caller can construct a claim. */ + Installation installClaimOnce( + CanonicalGameplayBindingInventoryRepository.OriginalNewCandidateInstallationClaim claim) { + Objects.requireNonNull(claim, "SQL-issued original NEW claim"); + requireNoAmbientTransaction(); + var originalDecision = claim.originalDecision(); + CanonicalGameplayOriginalNewCandidate candidate = claim.candidate(); + CanonicalGameplayTenantGameplayTagRepository.Assignment assignment; + try { + requireNoAmbientTransaction(); + assignment = tenantTags.assignmentForTransition(claim.evidence().transition().transitionId()); + requireAssignment(assignment, candidate); + } catch (RuntimeException unavailable) { + throw unavailable(); + } + Keys keys = keys(assignment, candidate); + + if (claim.consumeCreatePermission()) { + CreateAttempt attempt = createOnce(claim, assignment, keys); + if (attempt == CreateAttempt.REFUSED) throw unavailable(); + // A lost reply remains uncertain until this separate exact physical read succeeds. + } + + PhysicalReadback readback = readExact(candidate, assignment, keys); + CanonicalGameplayBindingInventoryRepository.OriginalNewCandidateInstallationClaim freshClaim = + inventory.claimOriginalNewCandidateInstallation(originalDecision); + if (!freshClaim.candidate().equals(candidate)) throw unavailable(); + var provisional = inventory.markOriginalNewCandidateProvisional(freshClaim, readback); + if (provisional.status() + != net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingTransitionSnapshot + .Status.PROVISIONAL + || !provisional.transitionId().equals(candidate.transition().transitionId())) { + throw unavailable(); + } + return new Installation(candidate, assignment, keys, readback, provisional); + } + + private CreateAttempt createOnce( + CanonicalGameplayBindingInventoryRepository.OriginalNewCandidateInstallationClaim claim, + CanonicalGameplayTenantGameplayTagRepository.Assignment assignment, + Keys keys) { + requireNoAmbientTransaction(); + RedisScriptDescriptor descriptor = requireDescriptor(); + byte[] script = scriptSource(descriptor); + byte[] candidateBytes = claim.candidate().canonicalBytes(); + if (candidateBytes.length == 0 || candidateBytes.length > MAX_CANDIDATE_BYTES) { + throw unavailable(); + } + try (StatefulRedisConnection connection = + redisClient.connect(ByteArrayCodec.INSTANCE)) { + RedisAsyncCommands commands = requireCommands(connection); + requirePrincipal(await(commands.aclWhoami())); + String loadedSha = await(commands.scriptLoad(script)); + if (!digest("SHA-1", script).equals(loadedSha)) throw unavailable(); + Long result = + await( + commands.evalsha( + loadedSha, + ScriptOutputType.INTEGER, + keyBytes(keys), + ascii(CanonicalGameplayOriginalNewCandidate.PURPOSE), + ascii(assignment.tenantId().toString()), + ascii(assignment.accountId().toString()), + ascii(assignment.playableStateNamespaceId().toString()), + ascii(assignment.characterId().toString()), + ascii(assignment.gameInstanceId().toString()), + ascii(assignment.sessionId()), + ascii(claim.candidate().transition().bindingGeneration().toString()), + ascii(assignment.tenantGameplayTag()), + candidateBytes)); + return Long.valueOf(1L).equals(result) ? CreateAttempt.CREATED : CreateAttempt.REFUSED; + } catch (RuntimeException possibleLostReply) { + // DISPATCH_POSSIBLE is already durable. The caller will only attempt an exact read. + return CreateAttempt.REPLY_UNCERTAIN; + } + } + + private PhysicalReadback readExact( + CanonicalGameplayOriginalNewCandidate candidate, + CanonicalGameplayTenantGameplayTagRepository.Assignment assignment, + Keys keys) { + requireNoAmbientTransaction(); + byte[] candidateBytes = candidate.canonicalBytes(); + byte[] characterBytes = characterProjection(candidate); + byte[] sessionKey = ascii(keys.session()); + byte[] characterKey = ascii(keys.characterIndex()); + byte[] accountTenantKey = ascii(keys.accountTenantIndex()); + byte[] tenantKey = ascii(keys.tenantIndex()); + byte[] sessionMember = ascii(candidate.bindingIdentity().sessionId()); + try (StatefulRedisConnection connection = + redisClient.connect(ByteArrayCodec.INSTANCE)) { + RedisAsyncCommands commands = requireCommands(connection); + requirePrincipal(await(commands.aclWhoami())); + if (!"string".equals(await(commands.type(sessionKey))) + || !Long.valueOf(-1L).equals(await(commands.pttl(sessionKey))) + || !Arrays.equals(candidateBytes, await(commands.get(sessionKey))) + || !"string".equals(await(commands.type(characterKey))) + || !Long.valueOf(-1L).equals(await(commands.pttl(characterKey))) + || !Arrays.equals(characterBytes, await(commands.get(characterKey))) + || !persistentMember(commands, accountTenantKey, sessionMember) + || !persistentMember(commands, tenantKey, sessionMember)) { + throw unavailable(); + } + } catch (RuntimeException unavailable) { + throw unavailable(); + } + return new PhysicalReadback(candidate, assignment, keys, candidateBytes, characterBytes); + } + + private static boolean persistentMember( + RedisAsyncCommands commands, byte[] key, byte[] member) { + String type = await(commands.type(key)); + Long ttl = await(commands.pttl(key)); + return "set".equals(type) + && Long.valueOf(-1L).equals(ttl) + && Boolean.TRUE.equals(await(commands.sismember(key, member))); + } + + private RedisScriptDescriptor requireDescriptor() { + try { + RedisScriptDescriptor descriptor = + catalog.require(CanonicalGameplayOriginalNewCandidateRedisScriptContribution.SCRIPT_ID); + if (!CanonicalGameplayOriginalNewCandidateRedisScriptContribution.SCRIPT_ID.equals( + descriptor.scriptId()) + || !CanonicalGameplayOriginalNewCandidateRedisScriptContribution.RESOURCE_PATH.equals( + descriptor.resourcePath()) + || !"game-session-service".equals(descriptor.owner()) + || !PRINCIPAL.equals(descriptor.principal()) + || descriptor.role() != RedisScriptDescriptor.RedisRole.COORDINATION + || !EXPECTED_KEYS.equals(descriptor.keys()) + || !EXPECTED_ARGUMENTS.equals(descriptor.arguments()) + || descriptor.category() != RedisScriptDescriptor.ScriptCategory.SESSION_CAS + || !EXPECTED_OUTCOMES.equals(descriptor.outcomes()) + || descriptor.resetSensitivity() != RedisScriptDescriptor.ResetSensitivity.CLUSTER + || descriptor.lossClass() + != RedisScriptDescriptor.LossClass.EMPTY_REDIS_COLD_START_OR_RESET + || descriptor.compatibilityLevel() + != RedisScriptDescriptor.CompatibilityLevel.REQUIRES_CLUSTER_RESET) { + throw unavailable(); + } + return descriptor; + } catch (RuntimeException failure) { + throw unavailable(); + } + } + + private byte[] scriptSource(RedisScriptDescriptor descriptor) { + try (InputStream input = + getClass().getClassLoader().getResourceAsStream(descriptor.resourcePath())) { + if (input == null) throw unavailable(); + byte[] bytes = input.readNBytes(MAX_SCRIPT_BYTES + 1); + if (bytes.length == 0 + || bytes.length > MAX_SCRIPT_BYTES + || !digest("SHA-256", bytes).equals(descriptor.sha256())) { + throw unavailable(); + } + return bytes; + } catch (IOException | RuntimeException failure) { + throw unavailable(); + } + } + + private static Keys keys( + CanonicalGameplayTenantGameplayTagRepository.Assignment assignment, + CanonicalGameplayOriginalNewCandidate candidate) { + var binding = candidate.bindingIdentity().bindingRef(); + return new Keys( + CanonicalGameplaySessionRedisKeys.session(assignment, binding), + CanonicalGameplaySessionRedisKeys.characterIndex(assignment, binding), + CanonicalGameplaySessionRedisKeys.accountTenantIndex(assignment, binding), + CanonicalGameplaySessionRedisKeys.tenantIndex(assignment, binding)); + } + + private static byte[] characterProjection(CanonicalGameplayOriginalNewCandidate candidate) { + var binding = candidate.bindingIdentity(); + return ("{\"sessionId\":\"" + + binding.sessionId() + + "\",\"gameInstanceId\":\"" + + binding.gameInstanceId() + + "\",\"bindingGeneration\":\"" + + candidate.transition().bindingGeneration() + + "\"}") + .getBytes(StandardCharsets.US_ASCII); + } + + private static void requireAssignment( + CanonicalGameplayTenantGameplayTagRepository.Assignment assignment, + CanonicalGameplayOriginalNewCandidate candidate) { + CanonicalGameplayBindingIdentity binding = candidate.bindingIdentity(); + if (!assignment.isBindingTransition() + || !candidate.transition().transitionId().equals(assignment.transitionId()) + || !binding.tenantId().equals(assignment.tenantId()) + || !binding.accountId().equals(assignment.accountId()) + || !binding.playableStateNamespaceId().equals(assignment.playableStateNamespaceId()) + || !binding.characterId().equals(assignment.characterId()) + || !binding.gameInstanceId().equals(assignment.gameInstanceId()) + || !binding.sessionId().equals(assignment.sessionId())) { + throw unavailable(); + } + CanonicalGameplayTenantGameplayTagRepository.requireCanonicalTag( + assignment.tenantGameplayTag()); + } + + private static byte[][] keyBytes(Keys keys) { + return new byte[][] { + ascii(keys.session()), + ascii(keys.characterIndex()), + ascii(keys.accountTenantIndex()), + ascii(keys.tenantIndex()) + }; + } + + private static RedisAsyncCommands requireCommands( + StatefulRedisConnection connection) { + RedisAsyncCommands commands = connection.async(); + if (commands == null) throw unavailable(); + return commands; + } + + private static T await(RedisFuture future) { + try { + T result = future.get(COMMAND_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS); + if (result == null) throw unavailable(); + return result; + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw unavailable(); + } catch (ExecutionException | TimeoutException failure) { + throw unavailable(); + } + } + + private static void requirePrincipal(String principal) { + if (!PRINCIPAL.equals(principal)) throw unavailable(); + } + + private static void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "Original NEW Redis work cannot run inside an ambient SQL transaction or synchronization"); + } + } + + private static byte[] ascii(String value) { + return value.getBytes(StandardCharsets.US_ASCII); + } + + private static String digest(String algorithm, byte[] bytes) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance(algorithm).digest(bytes)); + } catch (java.security.NoSuchAlgorithmException impossible) { + throw new IllegalStateException("JVM digest algorithm is unavailable", impossible); + } + } + + private static RedisScriptDescriptor.OutcomeSpec outcome( + String code, + RedisScriptDescriptor.OutcomeCategory category, + RedisScriptDescriptor.MutationEffect effect) { + return new RedisScriptDescriptor.OutcomeSpec(code, category, effect); + } + + private static IllegalStateException unavailable() { + return new IllegalStateException("Original NEW candidate install/readback is unavailable"); + } + + private enum CreateAttempt { + CREATED, + REPLY_UNCERTAIN, + REFUSED + } + + private record Keys( + String session, String characterIndex, String accountTenantIndex, String tenantIndex) {} + + /** Private-constructor physical proof from a separate exact read of all four scoped keys. */ + public static final class PhysicalReadback { + private final String transitionId; + private final CanonicalGameplayOriginalNewCandidate candidate; + private final CanonicalGameplayTenantGameplayTagRepository.Assignment assignment; + private final Keys keys; + private final byte[] candidateBytes; + private final byte[] characterBytes; + private final String digest; + + private PhysicalReadback( + CanonicalGameplayOriginalNewCandidate candidate, + CanonicalGameplayTenantGameplayTagRepository.Assignment assignment, + Keys keys, + byte[] candidateBytes, + byte[] characterBytes) { + this.transitionId = candidate.transition().transitionId().toString(); + this.candidate = candidate; + this.assignment = assignment; + this.keys = keys; + this.candidateBytes = candidateBytes.clone(); + this.characterBytes = characterBytes.clone(); + this.digest = + exactReadbackDigest( + keys, candidateBytes, characterBytes, candidate.bindingIdentity().sessionId()); + } + + String digest() { + return digest; + } + + boolean matches( + CanonicalGameplayOriginalNewCandidate expected, + CanonicalGameplayBindingProvisionalCasEvidence evidence) { + try { + requireAssignment(assignment, expected); + Keys expectedKeys = keys(assignment, expected); + return candidate.equals(expected) + && transitionId.equals(evidence.transition().transitionId().toString()) + && expected.transition().transitionId().equals(evidence.transition().transitionId()) + && expected.matchesProvisionalSources(evidence) + && keys.equals(expectedKeys) + && Arrays.equals(candidateBytes, expected.canonicalBytes()) + && Arrays.equals(characterBytes, characterProjection(expected)) + && digest.equals( + exactReadbackDigest( + keys, candidateBytes, characterBytes, expected.bindingIdentity().sessionId())); + } catch (RuntimeException invalidSource) { + return false; + } + } + + @Override + public String toString() { + return "PhysicalReadback[transitionId=" + transitionId + ", nonAdmitting=true]"; + } + } + + /** + * Owner result handed to Main for later exact candidate comparison and final-CAS preimage use. + */ + public static final class Installation { + private final CanonicalGameplayOriginalNewCandidate candidate; + private final CanonicalGameplayTenantGameplayTagRepository.Assignment assignment; + private final Keys keys; + private final PhysicalReadback physicalReadback; + private final net.firedevops.firemud.gamesession.binding + .CanonicalGameplayBindingTransitionSnapshot + provisional; + + private Installation( + CanonicalGameplayOriginalNewCandidate candidate, + CanonicalGameplayTenantGameplayTagRepository.Assignment assignment, + Keys keys, + PhysicalReadback physicalReadback, + net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingTransitionSnapshot + provisional) { + this.candidate = candidate; + this.assignment = assignment; + this.keys = keys; + this.physicalReadback = physicalReadback; + this.provisional = provisional; + } + + public CanonicalGameplayOriginalNewCandidate candidate() { + return candidate; + } + + public byte[] exactCandidateBytes() { + return candidate.canonicalBytes(); + } + + public String sessionKey() { + return keys.session(); + } + + public String characterIndexKey() { + return keys.characterIndex(); + } + + public String accountTenantIndexKey() { + return keys.accountTenantIndex(); + } + + public String tenantIndexKey() { + return keys.tenantIndex(); + } + + public CanonicalGameplayTenantGameplayTagRepository.Assignment assignment() { + return assignment; + } + + public PhysicalReadback physicalReadback() { + return physicalReadback; + } + + public net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingTransitionSnapshot + provisionalTransition() { + return provisional; + } + + public boolean isNonAdmittingCandidate() { + return true; + } + + @Override + public String toString() { + return "Installation[transitionId=" + + candidate.transition().transitionId() + + ", purpose=" + + CanonicalGameplayOriginalNewCandidate.PURPOSE + + ", nonAdmitting=true]"; + } + } + + private static String exactReadbackDigest( + Keys keys, byte[] candidateBytes, byte[] characterBytes, String sessionId) { + try { + ByteArrayOutputStream buffer = new ByteArrayOutputStream(); + try (DataOutputStream output = new DataOutputStream(buffer)) { + output.write("original-new-candidate-readback/v1".getBytes(StandardCharsets.US_ASCII)); + writeFrame(output, keys.session().getBytes(StandardCharsets.US_ASCII)); + writeFrame(output, candidateBytes); + writeFrame(output, keys.characterIndex().getBytes(StandardCharsets.US_ASCII)); + writeFrame(output, characterBytes); + writeFrame(output, keys.accountTenantIndex().getBytes(StandardCharsets.US_ASCII)); + writeFrame(output, sessionId.getBytes(StandardCharsets.US_ASCII)); + writeFrame(output, keys.tenantIndex().getBytes(StandardCharsets.US_ASCII)); + writeFrame(output, sessionId.getBytes(StandardCharsets.US_ASCII)); + } + return "sha256:" + digest("SHA-256", buffer.toByteArray()); + } catch (IOException impossible) { + throw new IllegalStateException("Cannot encode exact physical readback", impossible); + } + } + + private static void writeFrame(DataOutputStream output, byte[] bytes) throws IOException { + output.writeInt(bytes.length); + output.write(bytes); + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCandidateRedisOwnerFactory.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCandidateRedisOwnerFactory.java new file mode 100644 index 0000000000..1b446680f8 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCandidateRedisOwnerFactory.java @@ -0,0 +1,22 @@ +package net.firedevops.firemud.gamesession.repository; + +import io.lettuce.core.RedisClient; +import java.util.Objects; +import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; + +/** Explicit manual construction for the unregistered original NEW candidate Redis owner. */ +public final class CanonicalGameplayOriginalNewCandidateRedisOwnerFactory { + private CanonicalGameplayOriginalNewCandidateRedisOwnerFactory() {} + + public static CanonicalGameplayOriginalNewCandidateRedisOwner create( + RedisClient redisClient, + RedisScriptCatalog scriptCatalog, + CanonicalGameplayBindingInventoryRepository inventoryRepository, + CanonicalGameplayTenantGameplayTagRepository tenantGameplayTags) { + return new CanonicalGameplayOriginalNewCandidateRedisOwner( + Objects.requireNonNull(redisClient, "redisClient"), + Objects.requireNonNull(scriptCatalog, "scriptCatalog"), + Objects.requireNonNull(inventoryRepository, "inventoryRepository"), + Objects.requireNonNull(tenantGameplayTags, "tenantGameplayTags")); + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayOriginalNewCandidateRedisScriptContribution.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayOriginalNewCandidateRedisScriptContribution.java new file mode 100644 index 0000000000..ffe959cb4d --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayOriginalNewCandidateRedisScriptContribution.java @@ -0,0 +1,52 @@ +package net.firedevops.firemud.gamesession.service; + +import java.io.IOException; +import java.io.InputStream; +import java.util.Collection; +import java.util.List; +import net.firedevops.firemud.common.redis.contracts.RedisScriptContribution; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.json.JsonMapper; + +/** Passive descriptor for the manual first-install-only non-admitting original NEW candidate. */ +public final class CanonicalGameplayOriginalNewCandidateRedisScriptContribution + implements RedisScriptContribution { + public static final String SCRIPT_ID = "game-session.original-new-candidate-install.v1"; + public static final String RESOURCE_PATH = + "redis/lua/game-session-original-new-candidate-install.lua"; + private static final String DESCRIPTOR_PATH = + "/redis/scripts/game-session-original-new-candidate-install.json"; + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + @Override + public String ownerId() { + return "game-session-service"; + } + + @Override + public Collection descriptors() { + try (InputStream input = getClass().getResourceAsStream(DESCRIPTOR_PATH)) { + if (input == null) throw unavailable(); + byte[] bytes = input.readNBytes(16 * 1024 + 1); + if (bytes.length == 0 || bytes.length > 16 * 1024) throw unavailable(); + RedisScriptDescriptor descriptor = JSON.readValue(bytes, RedisScriptDescriptor.class); + if (!ownerId().equals(descriptor.owner()) || !SCRIPT_ID.equals(descriptor.scriptId())) { + throw unavailable(); + } + return List.of(descriptor); + } catch (IOException | RuntimeException failure) { + throw unavailable(); + } + } + + private static IllegalStateException unavailable() { + return new IllegalStateException("Original NEW candidate Redis descriptor is unavailable"); + } +} diff --git a/services/game-session-service/src/main/resources/META-INF/services/net.firedevops.firemud.common.redis.contracts.RedisScriptContribution b/services/game-session-service/src/main/resources/META-INF/services/net.firedevops.firemud.common.redis.contracts.RedisScriptContribution index c9317c80ea..59d900160f 100644 --- a/services/game-session-service/src/main/resources/META-INF/services/net.firedevops.firemud.common.redis.contracts.RedisScriptContribution +++ b/services/game-session-service/src/main/resources/META-INF/services/net.firedevops.firemud.common.redis.contracts.RedisScriptContribution @@ -1,3 +1,4 @@ net.firedevops.firemud.gamesession.service.InitialGameplayLoginRedisScriptContribution net.firedevops.firemud.gamesession.service.CanonicalGameplayAccountMemberRepairRedisScriptContribution net.firedevops.firemud.gamesession.service.CanonicalGameplayAccountClosedBarrierRedisScriptContribution +net.firedevops.firemud.gamesession.service.CanonicalGameplayOriginalNewCandidateRedisScriptContribution diff --git a/services/game-session-service/src/main/resources/db/migration/V1048__canonical_original_new_candidate_installation.sql b/services/game-session-service/src/main/resources/db/migration/V1048__canonical_original_new_candidate_installation.sql new file mode 100644 index 0000000000..5154004f9d --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V1048__canonical_original_new_candidate_installation.sql @@ -0,0 +1,106 @@ +-- The first NEW session value is a distinct non-admitting candidate. Its exact bytes and +-- dispatch/readback lifecycle live on the transition row already captured by account-control +-- cohort snapshots. No second ledger or authenticated-session columns are introduced. + +ALTER TABLE game_session_canonical_binding_transition + ADD COLUMN original_new_candidate_bytes bytea, + ADD COLUMN original_new_candidate_digest character varying(71), + ADD COLUMN original_new_candidate_state character varying(32), + ADD COLUMN original_new_candidate_readback_digest character varying(71); + +ALTER TABLE game_session_canonical_binding_transition + ADD CONSTRAINT chk_gs_original_new_candidate_installation CHECK ( + ((original_new_candidate_bytes IS NULL + AND original_new_candidate_digest IS NULL + AND original_new_candidate_state IS NULL + AND original_new_candidate_readback_digest IS NULL) + OR (original_new_candidate_bytes IS NOT NULL + AND octet_length(original_new_candidate_bytes) BETWEEN 1 AND 524288 + AND original_new_candidate_digest IS NOT NULL + AND original_new_candidate_digest ~ '^sha256:[0-9a-f]{64}$' + AND original_new_candidate_state IS NOT NULL + AND original_new_candidate_state IN ('DISPATCH_POSSIBLE', 'READBACK_CONFIRMED') + AND ((original_new_candidate_state = 'DISPATCH_POSSIBLE' + AND original_new_candidate_readback_digest IS NULL) + OR (original_new_candidate_state = 'READBACK_CONFIRMED' + AND original_new_candidate_readback_digest IS NOT NULL + AND original_new_candidate_readback_digest ~ '^sha256:[0-9a-f]{64}$')))) + AND (original_new_candidate_bytes IS NULL + OR (expected_prior_binding_ref IS NULL + AND expected_prior_binding_generation IS NULL + AND status IN ('PREPARED', 'PROVISIONAL', 'COMMITTED', 'ABORTED', 'AMBIGUOUS'))) + ); + +-- The first write freezes the exact candidate before any Redis attempt. The only later change +-- records a positive owner readback digest. These columns are never reset or retargeted. +-- [jooq ignore start] +CREATE FUNCTION guard_gs_original_new_candidate_installation() RETURNS trigger AS $$ +BEGIN + IF TG_OP = 'TRUNCATE' THEN + IF EXISTS (SELECT 1 FROM game_session_canonical_binding_transition + WHERE original_new_candidate_bytes IS NOT NULL) THEN + RAISE EXCEPTION 'Original NEW candidate transition retention is held' + USING ERRCODE = '23514', CONSTRAINT = 'gs_original_new_candidate_retained'; + END IF; + RETURN NULL; + END IF; + IF TG_OP = 'DELETE' THEN + IF OLD.original_new_candidate_bytes IS NOT NULL THEN + RAISE EXCEPTION 'Original NEW candidate transition retention is held' + USING ERRCODE = '23514', CONSTRAINT = 'gs_original_new_candidate_retained'; + END IF; + RETURN OLD; + END IF; + IF ROW(NEW.original_new_candidate_bytes, NEW.original_new_candidate_digest) + IS DISTINCT FROM ROW(OLD.original_new_candidate_bytes, OLD.original_new_candidate_digest) THEN + IF OLD.original_new_candidate_bytes IS NOT NULL + OR OLD.original_new_candidate_digest IS NOT NULL + OR NEW.original_new_candidate_bytes IS NULL + OR NEW.original_new_candidate_digest IS NULL + OR NEW.original_new_candidate_state IS DISTINCT FROM 'DISPATCH_POSSIBLE' + OR NEW.original_new_candidate_readback_digest IS NOT NULL + OR NEW.expected_prior_binding_ref IS NOT NULL + OR NEW.expected_prior_binding_generation IS NOT NULL + OR NEW.status NOT IN ('PREPARED', 'PROVISIONAL') THEN + RAISE EXCEPTION 'Original NEW candidate bytes are immutable after the first dispatch claim' + USING ERRCODE = '23514', CONSTRAINT = 'gs_original_new_candidate_immutable'; + END IF; + END IF; + IF NEW.original_new_candidate_state IS DISTINCT FROM OLD.original_new_candidate_state THEN + IF OLD.original_new_candidate_state IS NULL + AND NEW.original_new_candidate_state = 'DISPATCH_POSSIBLE' + AND OLD.original_new_candidate_bytes IS NULL + AND NEW.original_new_candidate_bytes IS NOT NULL + AND NEW.original_new_candidate_readback_digest IS NULL + AND NEW.expected_prior_binding_ref IS NULL + AND NEW.expected_prior_binding_generation IS NULL + AND NEW.status IN ('PREPARED', 'PROVISIONAL') THEN + NULL; + ELSIF OLD.original_new_candidate_state = 'DISPATCH_POSSIBLE' + AND NEW.original_new_candidate_state = 'READBACK_CONFIRMED' + AND NEW.original_new_candidate_bytes IS NOT DISTINCT FROM OLD.original_new_candidate_bytes + AND NEW.original_new_candidate_digest IS NOT DISTINCT FROM OLD.original_new_candidate_digest + AND NEW.original_new_candidate_readback_digest IS NOT NULL + AND NEW.original_new_candidate_readback_digest ~ '^sha256:[0-9a-f]{64}$' + AND NEW.status IN ('PREPARED', 'PROVISIONAL', 'COMMITTED', 'AMBIGUOUS') THEN + NULL; + ELSE + RAISE EXCEPTION 'Original NEW candidate dispatch/readback state is not monotone' + USING ERRCODE = '23514', CONSTRAINT = 'gs_original_new_candidate_state_monotone'; + END IF; + ELSIF NEW.original_new_candidate_readback_digest IS DISTINCT FROM OLD.original_new_candidate_readback_digest THEN + RAISE EXCEPTION 'Original NEW candidate readback digest is immutable' + USING ERRCODE = '23514', CONSTRAINT = 'gs_original_new_candidate_readback_immutable'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER gs_original_new_candidate_installation_guard + BEFORE UPDATE OR DELETE ON game_session_canonical_binding_transition + FOR EACH ROW EXECUTE FUNCTION guard_gs_original_new_candidate_installation(); + +CREATE TRIGGER gs_original_new_candidate_installation_retention + BEFORE TRUNCATE ON game_session_canonical_binding_transition + FOR EACH STATEMENT EXECUTE FUNCTION guard_gs_original_new_candidate_installation(); +-- [jooq ignore stop] diff --git a/services/game-session-service/src/main/resources/redis/lua/game-session-original-new-candidate-install.lua b/services/game-session-service/src/main/resources/redis/lua/game-session-original-new-candidate-install.lua new file mode 100644 index 0000000000..d41bee4694 --- /dev/null +++ b/services/game-session-service/src/main/resources/redis/lua/game-session-original-new-candidate-install.lua @@ -0,0 +1,79 @@ +-- First publication of one exact ORIGINAL_NEW non-admitting candidate. +-- KEYS: session, character index, account-tenant set, tenant set. +-- This script has no replay/create mode: the SQL owner authorizes exactly one invocation. +local sessionPrefix = 'session:game:' +local characterPrefix = 'session:game:index:character:' +local accountTenantPrefix = 'session:game:index:account-tenant:' +local tenantPrefix = 'session:game:index:tenant:' +local maxCandidateBytes = 524288 +local maxIdentifierBytes = 512 +local maxGenerationBytes = 256 + +local function uuid(value) + return type(value) == 'string' and #value == 36 + and string.match(value, '^%x%x%x%x%x%x%x%x%-%x%x%x%x%-%x%x%x%x%-%x%x%x%x%-%x%x%x%x%x%x%x%x%x%x%x%x$') + and value == string.lower(value) + and value ~= '00000000-0000-0000-0000-000000000000' +end + +local function positive(value) + return type(value) == 'string' and #value > 0 and #value <= maxGenerationBytes + and string.match(value, '^[1-9][0-9]*$') +end + +local function boundedText(value) + return type(value) == 'string' and #value > 0 and #value <= maxIdentifierBytes +end + +if #KEYS ~= 4 or #ARGV ~= 10 then return -2 end +local purpose = ARGV[1] +local tenantId = ARGV[2] +local accountId = ARGV[3] +local namespaceId = ARGV[4] +local characterId = ARGV[5] +local gameInstanceId = ARGV[6] +local sessionId = ARGV[7] +local bindingGeneration = ARGV[8] +local tenantGameplayTag = ARGV[9] +local candidateBytes = ARGV[10] + +if purpose ~= 'original-new-non-admitting-candidate/v1' + or not uuid(tenantId) or not uuid(accountId) or not uuid(namespaceId) + or not uuid(characterId) or not uuid(gameInstanceId) or not uuid(sessionId) + or not positive(bindingGeneration) or not boundedText(tenantGameplayTag) + or type(candidateBytes) ~= 'string' or #candidateBytes == 0 or #candidateBytes > maxCandidateBytes then + return -2 +end + +local sessionKey = sessionPrefix .. '{' .. tenantGameplayTag .. '}:' .. gameInstanceId .. ':' .. sessionId +local characterKey = characterPrefix .. '{' .. tenantGameplayTag .. '}:' .. namespaceId .. ':' .. characterId +local accountTenantKey = accountTenantPrefix .. '{' .. tenantGameplayTag .. '}:' .. accountId +local tenantKey = tenantPrefix .. '{' .. tenantGameplayTag .. '}' +if KEYS[1] ~= sessionKey or KEYS[2] ~= characterKey + or KEYS[3] ~= accountTenantKey or KEYS[4] ~= tenantKey then return -2 end + +-- Check every key before the first mutation. The session and character projection must be truly +-- absent; existing exact values are still an unknown prior writer and are never adopted. +local sessionType = redis.call('TYPE', KEYS[1]).ok +local characterType = redis.call('TYPE', KEYS[2]).ok +local accountType = redis.call('TYPE', KEYS[3]).ok +local tenantType = redis.call('TYPE', KEYS[4]).ok +if sessionType ~= 'none' or characterType ~= 'none' + or (accountType ~= 'none' and accountType ~= 'set') + or (tenantType ~= 'none' and tenantType ~= 'set') then return -1 end +if redis.call('PTTL', KEYS[1]) ~= -2 or redis.call('PTTL', KEYS[2]) ~= -2 + or (accountType == 'none' and redis.call('PTTL', KEYS[3]) ~= -2) + or (accountType == 'set' and redis.call('PTTL', KEYS[3]) ~= -1) + or (tenantType == 'none' and redis.call('PTTL', KEYS[4]) ~= -2) + or (tenantType == 'set' and redis.call('PTTL', KEYS[4]) ~= -1) then return -1 end +if redis.call('SISMEMBER', KEYS[3], sessionId) ~= 0 + or redis.call('SISMEMBER', KEYS[4], sessionId) ~= 0 then return -1 end + +-- These writes are additive and target only the four exact same-slot keys. +redis.call('SET', KEYS[1], candidateBytes) +redis.call('SET', KEYS[2], + '{"sessionId":"' .. sessionId .. '","gameInstanceId":"' .. gameInstanceId + .. '","bindingGeneration":"' .. bindingGeneration .. '"}') +redis.call('SADD', KEYS[3], sessionId) +redis.call('SADD', KEYS[4], sessionId) +return 1 diff --git a/services/game-session-service/src/main/resources/redis/scripts/game-session-original-new-candidate-install.json b/services/game-session-service/src/main/resources/redis/scripts/game-session-original-new-candidate-install.json new file mode 100644 index 0000000000..5b252d9f2a --- /dev/null +++ b/services/game-session-service/src/main/resources/redis/scripts/game-session-original-new-candidate-install.json @@ -0,0 +1,40 @@ +{ + "scriptId": "game-session.original-new-candidate-install.v1", + "resourcePath": "redis/lua/game-session-original-new-candidate-install.lua", + "sha256": "1f2658014b73710bca61f0be80fa7994e567e2680569a96b138f7c164e773dbd", + "owner": "game-session-service", + "principal": "gamesession_coord_app", + "role": "COORDINATION", + "keys": [ + {"name": "session", "ownedPrefix": "session:game:", "hashTagDeclaration": "REQUIRED"}, + {"name": "characterIndex", "ownedPrefix": "session:game:index:character:", "hashTagDeclaration": "REQUIRED"}, + {"name": "accountTenantIndex", "ownedPrefix": "session:game:index:account-tenant:", "hashTagDeclaration": "REQUIRED"}, + {"name": "tenantIndex", "ownedPrefix": "session:game:index:tenant:", "hashTagDeclaration": "REQUIRED"} + ], + "arguments": [ + {"name": "purpose"}, + {"name": "tenantId"}, + {"name": "accountId"}, + {"name": "playableStateNamespaceId"}, + {"name": "characterId"}, + {"name": "gameInstanceId"}, + {"name": "sessionId"}, + {"name": "bindingGeneration"}, + {"name": "tenantGameplayTag"}, + {"name": "candidateBytes"} + ], + "category": "SESSION_CAS", + "outcomes": [ + {"code": "CANDIDATE_CREATED", "category": "SUCCESS", "effect": "MUTATING"}, + {"code": "EXISTING_STATE_REFUSED", "category": "STALE", "effect": "NON_MUTATING"}, + {"code": "INVALID_ARGUMENTS", "category": "VALIDATION_FAILURE", "effect": "NON_MUTATING"} + ], + "resetSensitivity": "CLUSTER", + "lossClass": "EMPTY_REDIS_COLD_START_OR_RESET", + "tailLossBehavior": "The exact candidate is not an authenticated session and cannot authorize authenticated readers, PLAY, LOOK, or gameplay admission. The SQL owner persists DISPATCH_POSSIBLE before this one CREATE invocation. Every later retry is read-only and requires exact current readback of the session value and all three indexes; absence, partial state, foreign state, expiry, reset, or lost outcome remains uncertain and is never repaired. Only a later Account-committed final six-key CAS may replace the exact candidate with a complete authenticated session.", + "compatibilityLevel": "REQUIRES_CLUSTER_RESET", + "supportedCoexistence": [ + {"callerVersion": "v1", "payloadVersion": "none"} + ], + "legacyPayloadShape": null +} diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountAdmissionBarrierRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountAdmissionBarrierRepositoryIntegrationTest.java index b68fb27763..138f45bf30 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountAdmissionBarrierRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountAdmissionBarrierRepositoryIntegrationTest.java @@ -787,7 +787,9 @@ public CanonicalGameplayLegacyMigrationReadback readBackExact( } private static TestSchema newTestSchema(String prefix) { - String schema = prefix + UUID.randomUUID().toString().replace("-", ""); + String schema = + prefix.substring(0, Math.min(prefix.length(), 31)) + + UUID.randomUUID().toString().replace("-", ""); DriverManagerDataSource dataSource = dataSource(schema); Flyway.configure() .dataSource(dataSource) diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountClosedBarrierRedisOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountClosedBarrierRedisOwnerIntegrationTest.java index 0f7dd2425f..1b141876b5 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountClosedBarrierRedisOwnerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountClosedBarrierRedisOwnerIntegrationTest.java @@ -12,16 +12,19 @@ import io.lettuce.core.codec.ByteArrayCodec; import io.lettuce.core.protocol.CommandKeyword; import io.lettuce.core.protocol.CommandType; +import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.nio.file.Path; import java.security.KeyPair; import java.security.KeyPairGenerator; +import java.security.MessageDigest; import java.security.Signature; import java.sql.SQLException; import java.time.Clock; import java.time.Duration; import java.time.Instant; import java.time.ZoneOffset; +import java.util.HexFormat; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @@ -1162,8 +1165,10 @@ static Fixture open(java.math.BigInteger lastOperationFence, String migrationTar lastOperationFence, accountId); CanonicalGameplayAccountAdmissionFenceIntent intent = - new CanonicalGameplayAccountAdmissionBarrierRepository(dsl) - .beginFenceIntent(accountId, UUID.randomUUID()); + retainedIdentity == null + ? new CanonicalGameplayAccountAdmissionBarrierRepository(dsl) + .beginFenceIntent(accountId, UUID.randomUUID()) + : seedHistoricalV1028Intent(dsl, retainedIdentity, lastOperationFence); if (!intent.operationFence().equals(lastOperationFence.add(java.math.BigInteger.ONE))) { throw new IllegalStateException("Test fixture did not establish the intended fence epoch"); } @@ -1188,6 +1193,153 @@ static Fixture open(java.math.BigInteger lastOperationFence, String migrationTar schema, dataSource, dsl, intent, runtime.targetNamespace(), keyPair, evidence); } + private static CanonicalGameplayAccountAdmissionFenceIntent seedHistoricalV1028Intent( + DSLContext dsl, + CanonicalGameplayBindingIdentity identity, + java.math.BigInteger lastOperationFence) + throws Exception { + // TEST ONLY: seed the populated historical V1027/V1028 storage contract. The live intent + // producer captures INITIAL rows added in V1047 and must not run against this old schema. + // seedActiveSource creates exactly one binding, committed transition, and bound reservation; + // capture all three in the canonical kind order using their actual PostgreSQL JSONB images. + var rows = + dsl.fetch( + "SELECT 0 AS row_ordinal, 'BINDING' AS source_kind," + + " encode(i.binding_ref, 'hex') AS source_key, i.tenant_id," + + " i.playable_state_namespace_id, to_jsonb(i)::text AS source_record_json" + + " FROM game_session_canonical_gameplay_binding_inventory i" + + " WHERE i.account_id = ?" + + " UNION ALL SELECT 1, 'TRANSITION', t.transition_id::text, t.tenant_id," + + " t.playable_state_namespace_id, to_jsonb(t)::text" + + " FROM game_session_canonical_binding_transition t" + + " JOIN game_session_canonical_gameplay_binding_inventory i" + + " ON i.binding_ref = t.candidate_binding_ref WHERE i.account_id = ?" + + " UNION ALL SELECT 2, 'RESERVATION', r.reservation_id::text, r.tenant_id," + + " r.playable_state_namespace_id, to_jsonb(r)::text" + + " FROM game_session_canonical_issuer_partition_reservation r" + + " WHERE r.account_id = ? ORDER BY row_ordinal", + identity.accountId(), + identity.accountId(), + identity.accountId()) + .map( + row -> + CanonicalGameplayAccountAdmissionFenceIntent.cohortRow( + row.get("row_ordinal", Long.class), + CanonicalGameplayAccountAdmissionFenceIntent.CohortKind.valueOf( + row.get("source_kind", String.class)), + row.get("source_key", String.class), + row.get("tenant_id", UUID.class), + row.get("playable_state_namespace_id", UUID.class), + row.get("source_record_json", String.class))); + if (rows.size() != 3 + || rows.stream() + .anyMatch( + row -> + !identity.tenantId().equals(row.tenantId()) + || !identity + .playableStateNamespaceId() + .equals(row.playableStateNamespaceId()))) { + throw new IllegalStateException("Historical fixture must retain its three scoped sources"); + } + var target = + CanonicalGameplayAccountAdmissionFenceIntent.barrierTarget( + 0L, identity.tenantId(), identity.playableStateNamespaceId()); + MessageDigest cohortDigest = MessageDigest.getInstance("SHA-256"); + for (var row : rows) { + updateHistoricalDigest( + cohortDigest, + Long.toString(row.ordinal()), + row.kind().name(), + row.sourceKey(), + row.tenantId().toString(), + row.playableStateNamespaceId().toString(), + row.sourceRecordJson()); + } + MessageDigest targetDigest = MessageDigest.getInstance("SHA-256"); + updateHistoricalDigest( + targetDigest, + Long.toString(target.ordinal()), + target.tenantId().toString(), + target.playableStateNamespaceId().toString()); + UUID operationId = UUID.randomUUID(); + UUID requestId = UUID.randomUUID(); + UUID plannedFence = UUID.randomUUID(); + var operationFence = lastOperationFence.add(java.math.BigInteger.ONE); + dsl.execute( + "INSERT INTO game_session_canonical_account_admission_fence_intent" + + " (operation_id, request_id, account_id, operation_fence," + + " planned_account_admission_fence, inventory_snapshot_revision," + + " legacy_cohort_id, legacy_owner_operation_id, legacy_writer_fence," + + " legacy_source_snapshot_revision, legacy_canonical_inventory_revision," + + " legacy_namespace_index_readback_revision, legacy_evidence_digest, intent_state," + + " cohort_row_count, cohort_digest, barrier_target_count, barrier_target_digest)" + + " SELECT ?, ?, ?, ?, ?, clock.inventory_revision, legacy.cohort_id," + + " legacy.owner_operation_id, legacy.legacy_writer_fence," + + " legacy.source_snapshot_revision, legacy.canonical_inventory_revision," + + " legacy.namespace_index_readback_revision, legacy.evidence_digest," + + " 'ACQUISITION_INTENT', 3, ?, 1, ?" + + " FROM game_session_canonical_binding_inventory_clock clock" + + " CROSS JOIN game_session_canonical_binding_legacy_disposition legacy" + + " WHERE clock.singleton_id = 1 AND legacy.singleton_id = 1", + operationId, + requestId, + identity.accountId(), + operationFence, + plannedFence, + "sha256:" + HexFormat.of().formatHex(cohortDigest.digest()), + "sha256:" + HexFormat.of().formatHex(targetDigest.digest())); + dsl.execute( + "INSERT INTO game_session_canonical_account_admission_fence_intent_barrier_target" + + " (operation_id, account_id, target_ordinal, tenant_id," + + " playable_state_namespace_id, target_state) VALUES (?, ?, 0, ?, ?, 'REQUIRED')", + operationId, + identity.accountId(), + target.tenantId(), + target.playableStateNamespaceId()); + for (var row : rows) { + dsl.execute( + "INSERT INTO game_session_canonical_account_admission_fence_intent_cohort_row" + + " (operation_id, account_id, row_ordinal, source_kind, source_key, tenant_id," + + " playable_state_namespace_id, source_row)" + + " VALUES (?, ?, ?, ?, ?, ?, ?, CAST(? AS jsonb))", + operationId, + identity.accountId(), + row.ordinal(), + row.kind().name(), + row.sourceKey(), + row.tenantId(), + row.playableStateNamespaceId(), + row.sourceRecordJson()); + } + dsl.execute( + "UPDATE game_session_canonical_account_coverage_control control" + + " SET state = 'ACQUISITION_INTENT', last_operation_fence = intent.operation_fence," + + " current_fence_intent_id = intent.operation_id," + + " current_operation_fence = intent.operation_fence," + + " account_admission_fence = intent.planned_account_admission_fence," + + " inventory_snapshot_revision = intent.inventory_snapshot_revision," + + " updated_at = CURRENT_TIMESTAMP" + + " FROM game_session_canonical_account_admission_fence_intent intent" + + " WHERE control.account_id = intent.account_id AND intent.operation_id = ?" + + " AND control.state = 'NO_ACTIVE_ACCOUNT_WIDE_FLOW'" + + " AND control.last_operation_fence = ?", + operationId, + lastOperationFence); + // Use the real immutable read model to verify the seeded tuple, counts, digests and control. + return new CanonicalGameplayAccountAdmissionBarrierRepository(dsl) + .readFenceIntent(identity.accountId(), requestId); + } + + private static void updateHistoricalDigest(MessageDigest digest, String... values) { + // V1027 hashes UTF-8 fields framed by their four-byte big-endian lengths. These three + // historical sources all have resolved non-null scopes; no newer source kinds are seeded. + for (String value : values) { + byte[] encoded = value.getBytes(StandardCharsets.UTF_8); + digest.update(ByteBuffer.allocate(Integer.BYTES).putInt(encoded.length).array()); + digest.update(encoded); + } + } + private static void seedNoActiveAccountCoverageControl(DSLContext dsl, UUID accountId) { // Controlled retained-row input only; this is not owner-produced no-active authority. dsl.execute( diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingRuntimeTestFixtures.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingRuntimeTestFixtures.java index 3674a45168..aa4ee98c68 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingRuntimeTestFixtures.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingRuntimeTestFixtures.java @@ -278,7 +278,7 @@ public static RuntimeTarget seedRunningLaunch( SHA256, 1L, SHA256, - Instant.now(), + Instant.now().truncatedTo(java.time.temporal.ChronoUnit.MICROS), catalog.characterCreationPolicy(), sourceEvidence.sourceGameRowId(), sourceEvidence.sourceGameTenantKey(), diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepositoryIntegrationTest.java index afa0312f44..b4445c546c 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepositoryIntegrationTest.java @@ -412,7 +412,9 @@ void cutoffClosesAnAbortedOriginTargetAndRetainsItsFrozenInitializer() { cutoffOperationId, target.closedValue().tenantId(), target.closedValue().playableStateNamespaceId()); - assertThat(closed.scriptOutcome()).isEqualTo(1L); + // Outcome 3 is CAPTURED_OPEN_CLOSED: this target replaces the exact OPEN + // payload captured by the cutoff. + assertThat(closed.scriptOutcome()).isEqualTo(3L); var installed = state.repository().completeCutoff(cutoffOperationId); assertThat(installed.state()) .isEqualTo(CanonicalGameplayIssuerAdmissionControlValue.State.INSTALLED); @@ -616,6 +618,17 @@ private CanonicalGameplayIssuerBindingLocalOperation prepareCurrentOperation( new CanonicalGameplayIssuerBindingLocalOperationRepository( state.fixture().dsl(), state.sourceReader()) .beginOrResumeOrdinaryNew(request); + var localCatalog = + RedisScriptCatalog.fromContributions( + List.of(new CanonicalGameplayIssuerBindingLocalRedisScriptContribution())); + var localProjection = + new CanonicalGameplayIssuerBindingLocalProjectionRepository( + state.fixture().dsl(), state.sourceReader()); + var localOwner = + new CanonicalGameplayIssuerBindingLocalRedisOwner( + ownerClient, localCatalog, localProjection, state.sourceReader()); + // Capacity is a distinct physical phase: publish it while SQL is still PREPARED. + localOwner.projectAndRead(operation); var inventory = new CanonicalGameplayBindingInventoryRepository(state.fixture().dsl()); var provisionalEvidence = inventory.readProvisionalCasEvidence(transitionId); var lease = @@ -630,15 +643,7 @@ private CanonicalGameplayIssuerBindingLocalOperation prepareCurrentOperation( operation.preparedTransition().bindingGeneration(), null, state.fixture().source().originalDecision().targetEvidence())); - var localCatalog = - RedisScriptCatalog.fromContributions( - List.of(new CanonicalGameplayIssuerBindingLocalRedisScriptContribution())); - var localProjection = - new CanonicalGameplayIssuerBindingLocalProjectionRepository( - state.fixture().dsl(), state.sourceReader()); - new CanonicalGameplayIssuerBindingLocalRedisOwner( - ownerClient, localCatalog, localProjection, state.sourceReader()) - .projectAndRead(operation); + localOwner.projectAndRead(operation); return operation; } diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java index 95c8d1d6b5..6667322eeb 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java @@ -750,8 +750,11 @@ void readsProjectedSubsetWhenTwoSamePartitionRegistrationsPrecedePhysicalProject intent.sourceCheckpoint(), incarnation); AtomicReference currentState = new AtomicReference<>(initialState); - initialCoverageOwner(dsl, currentState::get) - .completeInitialBootstrap(intent.operationId(), bootstrapRequestId); + CanonicalGameplayIssuerInstalledAnchor anchor = + initialCoverageOwner(dsl, currentState::get) + .completeInitialBootstrap(intent.operationId(), bootstrapRequestId); + new CanonicalGameplayIssuerAdmissionControlRepository(dsl) + .installInitialOpen(anchor, currentState::get); var runtimeTarget = CanonicalGameplayBindingRuntimeTestFixtures.seedRunningLaunch( diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPartitionBuildRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPartitionBuildRepositoryIntegrationTest.java index ee22452f7b..6b7bd3193d 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPartitionBuildRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPartitionBuildRepositoryIntegrationTest.java @@ -2271,6 +2271,13 @@ private static List rowImages(DSLContext dsl, String tableName) { image = "CASE WHEN to_jsonb(retained_row)->'admission_orphan_cleanup_id' = 'null'::jsonb" + " THEN to_jsonb(retained_row) - 'admission_orphan_cleanup_id' ELSE to_jsonb(retained_row) END"; + image = + "(" + + image + + ") - CASE WHEN to_jsonb(retained_row)->'original_new_candidate_bytes'" + + " = 'null'::jsonb THEN ARRAY['original_new_candidate_bytes'," + + " 'original_new_candidate_digest', 'original_new_candidate_state'," + + " 'original_new_candidate_readback_digest'] ELSE ARRAY[]::text[] END"; } else if (tableName.equals("game_session_canonical_binding_issuer_index_obligation")) { // V1036's null release link is absent-equivalent; an actual release UUID stays significant. image = @@ -2295,6 +2302,13 @@ private static List rowImagesWithXmin(DSLContext dsl, String tableName) image = "CASE WHEN to_jsonb(retained_row)->'admission_orphan_cleanup_id' = 'null'::jsonb" + " THEN to_jsonb(retained_row) - 'admission_orphan_cleanup_id' ELSE to_jsonb(retained_row) END"; + image = + "(" + + image + + ") - CASE WHEN to_jsonb(retained_row)->'original_new_candidate_bytes'" + + " = 'null'::jsonb THEN ARRAY['original_new_candidate_bytes'," + + " 'original_new_candidate_digest', 'original_new_candidate_state'," + + " 'original_new_candidate_readback_digest'] ELSE ARRAY[]::text[] END"; } else if (tableName.equals("game_session_canonical_binding_issuer_index_obligation")) { // V1036's null release link is absent-equivalent; an actual release UUID stays significant. image = diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCandidateRedisOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCandidateRedisOwnerIntegrationTest.java new file mode 100644 index 0000000000..74a7c22037 --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCandidateRedisOwnerIntegrationTest.java @@ -0,0 +1,659 @@ +package net.firedevops.firemud.gamesession.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.lettuce.core.AclSetuserArgs; +import io.lettuce.core.ClientOptions; +import io.lettuce.core.RedisClient; +import io.lettuce.core.RedisURI; +import io.lettuce.core.api.StatefulRedisConnection; +import io.lettuce.core.api.sync.RedisCommands; +import io.lettuce.core.codec.ByteArrayCodec; +import io.lettuce.core.protocol.CommandKeyword; +import io.lettuce.core.protocol.CommandType; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.time.Duration; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; +import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAdmissionDecision; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingIdentity; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingProvisionalCasEvidence; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingTransitionRequest; +import net.firedevops.firemud.gamesession.binding.CanonicalIssuerReservationFenceEvidence; +import net.firedevops.firemud.gamesession.service.CanonicalGameplayOriginalNewCandidateRedisScriptContribution; +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.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * Actual PostgreSQL source plus Coordination Redis proof for the non-admitting original NEW value. + * The upstream target and Account lease are controlled fixtures; this proof does not qualify their + * authority or the separate ordinary-NEW issuer-LIVE preparation owner. + */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class CanonicalGameplayOriginalNewCandidateRedisOwnerIntegrationTest { + private static final String PRINCIPAL = "gamesession_coord_app"; + private static final String PASSWORD = UUID.randomUUID().toString(); + private static final String KEY_PATTERN = "session:game:*"; + private static final int PORT = 6379; + private static final String MIGRATION_LOCATION = + "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize(); + private static final UUID TRANSITION_ID = UUID.randomUUID(); + private static final UUID ACCOUNT_INDEX_FENCE = UUID.randomUUID(); + private static final String ISSUER_ID = GameSessionAccountDelegationProfile.ISSUER; + + @Container + private static final GenericContainer REDIS = + new GenericContainer<>(TestContainerImages.redis()).withExposedPorts(PORT); + + @Container + private static final PostgreSQLContainer POSTGRES = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + private RedisClient administrator; + private RedisClient ownerClient; + private StatefulRedisConnection adminConnection; + private RedisCommands admin; + private TestSource source; + private CanonicalGameplayOriginalNewCandidateRedisOwner owner; + + @org.junit.jupiter.api.BeforeEach + void setUp() { + administrator = createClient(null, null); + adminConnection = administrator.connect(ByteArrayCodec.INSTANCE); + admin = adminConnection.sync(); + admin.flushdb(); + admin.aclSetuser( + PRINCIPAL, + new AclSetuserArgs() + .reset() + .on() + .addPassword(PASSWORD) + .keyPattern(KEY_PATTERN) + .addCommand(CommandType.HELLO) + .addCommand(CommandType.PING) + .addCommand(CommandType.CLIENT, CommandKeyword.SETINFO) + .addCommand(CommandType.ACL, CommandKeyword.WHOAMI) + .addCommand(CommandType.SCRIPT, CommandKeyword.LOAD) + .addCommand(CommandType.EVALSHA) + .addCommand(CommandType.TYPE) + .addCommand(CommandType.PTTL) + .addCommand(CommandType.GET) + .addCommand(CommandType.SET) + .addCommand(CommandType.SADD) + .addCommand(CommandType.SISMEMBER)); + ownerClient = createClient(PRINCIPAL, PASSWORD); + var catalog = RedisScriptCatalog.loadInstalled(getClass().getClassLoader()); + source = prepareSource(); + owner = + CanonicalGameplayOriginalNewCandidateRedisOwnerFactory.create( + ownerClient, catalog, source.repository(), source.tenantTags()); + } + + @org.junit.jupiter.api.AfterEach + void tearDown() { + if (source != null) source.close(); + if (adminConnection != null) adminConnection.close(); + if (ownerClient != null) ownerClient.shutdown(Duration.ZERO, Duration.ofSeconds(2)); + if (administrator != null) administrator.shutdown(Duration.ZERO, Duration.ofSeconds(2)); + } + + @org.junit.jupiter.api.Test + void installsExactCandidateAndReadOnlyRetryRetainsTheSameProvisionalDecision() { + var first = owner.installOnce(source.decision()); + advanceInventoryWithUnrelatedPreparedNew(); + var retry = owner.installOnce(source.decision()); + + assertThat(first.candidate().matchesOriginalDecision(source.decision())).isTrue(); + assertThat(first.candidate().canonicalBytes()).containsExactly(first.exactCandidateBytes()); + assertThat(first.isNonAdmittingCandidate()).isTrue(); + assertThat(first.provisionalTransition().status().name()).isEqualTo("PROVISIONAL"); + assertThat(retry.candidate()).isEqualTo(first.candidate()); + assertThat(retry.physicalReadback().digest()).isEqualTo(first.physicalReadback().digest()); + assertThat( + source + .repository() + .readAdmissionDecision(TRANSITION_ID, source.decision().leaseEvidence())) + .satisfies( + stored -> { + assertThat(first.candidate().matchesOriginalDecision(stored)).isTrue(); + assertThat(stored.leaseEvidence().canonicalJson()) + .isEqualTo(source.decision().leaseEvidence().canonicalJson()); + }); + + assertThat(admin.type(ascii(first.sessionKey()))).isEqualTo("string"); + assertThat(admin.get(ascii(first.sessionKey()))).containsExactly(first.exactCandidateBytes()); + assertThat(admin.type(ascii(first.characterIndexKey()))).isEqualTo("string"); + assertThat(new String(admin.get(ascii(first.characterIndexKey())), StandardCharsets.US_ASCII)) + .contains( + source.identity().sessionId(), + source.identity().gameInstanceId().toString(), + "bindingGeneration"); + assertThat( + admin.sismember( + ascii(first.accountTenantIndexKey()), ascii(source.identity().sessionId()))) + .isTrue(); + assertThat(admin.sismember(ascii(first.tenantIndexKey()), ascii(source.identity().sessionId()))) + .isTrue(); + assertThat(admin.pttl(ascii(first.sessionKey()))).isEqualTo(-1L); + } + + @org.junit.jupiter.api.Test + void missingAccountTenantOrTenantSetRefusesRetryWithoutChangingSqlOrOtherPostimages() { + List additionalSources = new ArrayList<>(); + try { + for (int missingIndex = 0; missingIndex < 2; missingIndex++) { + TestSource scenario = missingIndex == 0 ? source : prepareSource(); + if (scenario != source) additionalSources.add(scenario); + CanonicalGameplayOriginalNewCandidateRedisOwner scenarioOwner = + scenario == source + ? owner + : CanonicalGameplayOriginalNewCandidateRedisOwnerFactory.create( + ownerClient, + RedisScriptCatalog.loadInstalled(getClass().getClassLoader()), + scenario.repository(), + scenario.tenantTags()); + var installation = scenarioOwner.installOnce(scenario.decision()); + String missingKey = + missingIndex == 0 + ? installation.accountTenantIndexKey() + : installation.tenantIndexKey(); + String preservedKey = + missingIndex == 0 + ? installation.tenantIndexKey() + : installation.accountTenantIndexKey(); + byte[] sessionBytes = admin.get(ascii(installation.sessionKey())); + byte[] characterBytes = admin.get(ascii(installation.characterIndexKey())); + String sqlImageBeforeRetry = sourceSqlImage(scenario); + + assertThat(admin.del(ascii(missingKey))).isEqualTo(1L); + assertThatThrownBy(() -> scenarioOwner.installOnce(scenario.decision())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("install/readback is unavailable"); + + assertThat(admin.type(ascii(missingKey))).isEqualTo("none"); + assertThat(admin.type(ascii(installation.sessionKey()))).isEqualTo("string"); + assertThat(admin.pttl(ascii(installation.sessionKey()))).isEqualTo(-1L); + assertThat(admin.get(ascii(installation.sessionKey()))).containsExactly(sessionBytes); + assertThat(admin.type(ascii(installation.characterIndexKey()))).isEqualTo("string"); + assertThat(admin.pttl(ascii(installation.characterIndexKey()))).isEqualTo(-1L); + assertThat(admin.get(ascii(installation.characterIndexKey()))) + .containsExactly(characterBytes); + assertThat(admin.type(ascii(preservedKey))).isEqualTo("set"); + assertThat(admin.pttl(ascii(preservedKey))).isEqualTo(-1L); + assertThat(admin.sismember(ascii(preservedKey), ascii(scenario.identity().sessionId()))) + .isTrue(); + assertThat(sourceSqlImage(scenario)).isEqualTo(sqlImageBeforeRetry); + } + } finally { + additionalSources.forEach(TestSource::close); + } + } + + @org.junit.jupiter.api.Test + void doubleSqlClaimIssuesExactlyOneSingleUseCreatePermission() { + var first = source.repository().claimOriginalNewCandidateInstallation(source.decision()); + var second = source.repository().claimOriginalNewCandidateInstallation(source.decision()); + + assertThat(first.consumeCreatePermission()).isTrue(); + assertThat(first.consumeCreatePermission()).isFalse(); + assertThat(second.consumeCreatePermission()).isFalse(); + assertThatThrownBy(() -> owner.installClaimOnce(second)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("install/readback is unavailable"); + assertThat(admin.dbsize()).isZero(); + } + + @org.junit.jupiter.api.Test + void changedOriginalLeaseCannotReuseThePersistedCandidateOrDispatchRedis() { + var originalClaim = + source.repository().claimOriginalNewCandidateInstallation(source.decision()); + assertThat(originalClaim.state().name()).isEqualTo("DISPATCH_POSSIBLE"); + Map changedCarrier = + new LinkedHashMap<>(source.decision().leaseEvidence().carrier()); + changedCarrier.put("leaseId", UUID.randomUUID().toString()); + var changedLease = AccountGameplayAdmissionLeaseEvidence.fromCarrier(changedCarrier); + var changedDecision = + new CanonicalGameplayAdmissionDecision( + TRANSITION_ID, + changedLease, + source.identity(), + source.decision().bindingGeneration(), + null, + source.decision().targetEvidence()); + + assertThatThrownBy(() -> owner.installOnce(changedDecision)) + .isInstanceOf(RuntimeException.class); + assertThat(admin.dbsize()).isZero(); + assertThat( + source + .dsl() + .fetchSingle( + "SELECT original_new_candidate_state FROM game_session_canonical_binding_transition" + + " WHERE transition_id = ?", + TRANSITION_ID) + .get("original_new_candidate_state", String.class)) + .isEqualTo("DISPATCH_POSSIBLE"); + } + + @org.junit.jupiter.api.Test + void lostReplyRecoveryUsesOnlyExactReadbackAfterTheCreatePermissionWasClaimed() { + var claim = source.repository().claimOriginalNewCandidateInstallation(source.decision()); + assertThat(claim.consumeCreatePermission()).isTrue(); + var assignment = source.tenantTags().assignmentForTransition(TRANSITION_ID); + var binding = claim.candidate().bindingIdentity(); + String sessionKey = CanonicalGameplaySessionRedisKeys.session(assignment, binding.bindingRef()); + String characterKey = + CanonicalGameplaySessionRedisKeys.characterIndex(assignment, binding.bindingRef()); + String accountKey = + CanonicalGameplaySessionRedisKeys.accountTenantIndex(assignment, binding.bindingRef()); + String tenantKey = + CanonicalGameplaySessionRedisKeys.tenantIndex(assignment, binding.bindingRef()); + byte[] script; + try (var input = + getClass() + .getClassLoader() + .getResourceAsStream( + CanonicalGameplayOriginalNewCandidateRedisScriptContribution.RESOURCE_PATH)) { + if (input == null) throw new IllegalStateException("Candidate install script is missing"); + script = input.readAllBytes(); + } catch (java.io.IOException failure) { + throw new IllegalStateException("Cannot load candidate install script", failure); + } + String sha = admin.scriptLoad(script); + Long reply = + admin.evalsha( + sha, + io.lettuce.core.ScriptOutputType.INTEGER, + new byte[][] { + ascii(sessionKey), ascii(characterKey), ascii(accountKey), ascii(tenantKey) + }, + ascii(CanonicalGameplayOriginalNewCandidate.PURPOSE), + ascii(assignment.tenantId().toString()), + ascii(assignment.accountId().toString()), + ascii(assignment.playableStateNamespaceId().toString()), + ascii(assignment.characterId().toString()), + ascii(assignment.gameInstanceId().toString()), + ascii(assignment.sessionId()), + ascii(claim.candidate().transition().bindingGeneration().toString()), + ascii(assignment.tenantGameplayTag()), + claim.candidate().canonicalBytes()); + assertThat(reply).isEqualTo(1L); + // The owner is called as if the prior reply was lost. The SQL marker prevents a second eval. + var recovered = owner.installOnce(source.decision()); + assertThat(recovered.candidate()).isEqualTo(claim.candidate()); + assertThat(admin.get(ascii(recovered.sessionKey()))) + .containsExactly(recovered.exactCandidateBytes()); + } + + @org.junit.jupiter.api.Test + void resetAndCharacterConflictRemainUnresolvedWithoutRepair() { + var claim = source.repository().claimOriginalNewCandidateInstallation(source.decision()); + assertThat(claim.consumeCreatePermission()).isTrue(); + admin.flushdb(); + + assertThatThrownBy(() -> owner.installOnce(source.decision())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("install/readback is unavailable"); + assertThat(admin.dbsize()).isZero(); + assertThat( + source + .dsl() + .fetchSingle( + "SELECT original_new_candidate_state FROM game_session_canonical_binding_transition" + + " WHERE transition_id = ?", + TRANSITION_ID) + .get("original_new_candidate_state", String.class)) + .isEqualTo("DISPATCH_POSSIBLE"); + + var conflictSource = prepareSource(); + try { + var assignment = conflictSource.tenantTags().assignmentForTransition(TRANSITION_ID); + String characterKey = + CanonicalGameplaySessionRedisKeys.characterIndex( + assignment, conflictSource.identity().bindingRef()); + admin.set(ascii(characterKey), ascii("foreign-generation")); + var conflictOwner = + CanonicalGameplayOriginalNewCandidateRedisOwnerFactory.create( + ownerClient, + RedisScriptCatalog.loadInstalled(getClass().getClassLoader()), + conflictSource.repository(), + conflictSource.tenantTags()); + assertThatThrownBy(() -> conflictOwner.installOnce(conflictSource.decision())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("install/readback is unavailable"); + assertThat(admin.get(ascii(characterKey))).isEqualTo(ascii("foreign-generation")); + assertThat( + admin.type( + ascii( + CanonicalGameplaySessionRedisKeys.session( + assignment, conflictSource.identity().bindingRef())))) + .isEqualTo("none"); + } finally { + conflictSource.close(); + } + } + + @org.junit.jupiter.api.Test + void acquisitionIntentRaceRefusesBeforeAnyRedisMutationAndAmbientSqlNeverCallsRedis() { + var claimed = source.repository().claimOriginalNewCandidateInstallation(source.decision()); + assertThat(claimed.consumeCreatePermission()).isTrue(); + new CanonicalGameplayAccountAdmissionBarrierRepository(source.dsl()) + .beginFenceIntent(source.identity().accountId(), UUID.randomUUID()); + assertThatThrownBy(() -> owner.installOnce(source.decision())) + .isInstanceOf(RuntimeException.class); + assertThat(admin.dbsize()).isZero(); + + try { + TransactionSynchronizationManager.setActualTransactionActive(true); + assertThatThrownBy(() -> owner.installOnce(source.decision())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("ambient SQL transaction or synchronization"); + } finally { + TransactionSynchronizationManager.clear(); + } + assertThat(admin.dbsize()).isZero(); + + try { + TransactionSynchronizationManager.initSynchronization(); + assertThatThrownBy(() -> owner.installOnce(source.decision())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("ambient SQL transaction or synchronization"); + } finally { + TransactionSynchronizationManager.clearSynchronization(); + } + assertThat(admin.dbsize()).isZero(); + } + + private static String sourceSqlImage(TestSource source) { + return source + .dsl() + .fetchSingle( + "SELECT jsonb_build_array(" + + "(SELECT to_jsonb(t) FROM game_session_canonical_binding_transition t" + + " WHERE t.transition_id = ?)," + + "(SELECT to_jsonb(i) FROM game_session_canonical_gameplay_binding_inventory i" + + " WHERE i.transition_id = ?)," + + "(SELECT to_jsonb(r) FROM game_session_canonical_issuer_partition_reservation r" + + " WHERE r.transition_id = ?)," + + "(SELECT to_jsonb(a) FROM game_session_canonical_binding_account_index_obligation a" + + " WHERE a.transition_id = ?)," + + "(SELECT to_jsonb(i) FROM game_session_canonical_binding_issuer_index_obligation i" + + " WHERE i.transition_id = ?)," + + "(SELECT to_jsonb(r) FROM game_session_canonical_binding_region_bridge_obligation r" + + " WHERE r.transition_id = ?)," + + "(SELECT inventory_revision FROM game_session_canonical_binding_inventory_clock" + + " WHERE singleton_id = 1))::text", + TRANSITION_ID, + TRANSITION_ID, + TRANSITION_ID, + TRANSITION_ID, + TRANSITION_ID, + TRANSITION_ID) + .get(0, String.class); + } + + private TestSource prepareSource() { + String schema = "gs_original_new_candidate_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName("org.postgresql.Driver"); + String jdbcUrl = POSTGRES.getJdbcUrl(); + dataSource.setUrl(jdbcUrl + (jdbcUrl.contains("?") ? "&" : "?") + "currentSchema=" + schema); + dataSource.setUsername(POSTGRES.getUsername()); + dataSource.setPassword(POSTGRES.getPassword()); + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history") + .locations(MIGRATION_LOCATION) + .load() + .migrate(); + DSLContext dsl = DSL.using(dataSource, SQLDialect.POSTGRES); + var runtime = CanonicalGameplayBindingRuntimeTestFixtures.seedRunningLaunch(dataSource); + seedSyntheticVerifiedLegacyDisposition(dsl); + CanonicalGameplayBindingIdentity identity = + new CanonicalGameplayBindingIdentity( + UUID.randomUUID(), + runtime.canonicalTenantId(), + runtime.playableStateNamespaceId(), + UUID.randomUUID(), + runtime.playableStateScope(), + runtime.gameInstanceUuid(), + runtime.gameInstanceId(), + UUID.randomUUID().toString(), + UUID.randomUUID(), + BigInteger.valueOf(3), + ISSUER_ID, + BigInteger.ONE, + BigInteger.ONE, + BigInteger.valueOf(4), + BigInteger.valueOf(32)); + UUID transitionId = TRANSITION_ID; + CanonicalGameplayBindingInventoryRepository repository = + new CanonicalGameplayBindingInventoryRepository(dsl); + repository.prepare( + new CanonicalGameplayBindingTransitionRequest( + transitionId, + ACCOUNT_INDEX_FENCE, + identity, + new CanonicalIssuerReservationFenceEvidence( + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + BigInteger.ONE, + BigInteger.TWO, + BigInteger.ONE), + null, + null)); + CanonicalGameplayBindingProvisionalCasEvidence prepared = + repository.readProvisionalCasEvidence(transitionId); + var decision = + new CanonicalGameplayAdmissionDecision( + transitionId, + leaseEvidence( + identity, prepared.transition().bindingGeneration(), runtime.playableTarget()), + identity, + prepared.transition().bindingGeneration(), + null, + runtime.playableTarget()); + var tenantTags = + new CanonicalGameplayTenantGameplayTagRepository(dsl, runtime.targetNamespace(), 1); + return new TestSource(schema, dataSource, dsl, repository, tenantTags, identity, decision); + } + + private void advanceInventoryWithUnrelatedPreparedNew() { + CanonicalGameplayBindingIdentity original = source.identity(); + var unrelated = + new CanonicalGameplayBindingIdentity( + original.accountId(), + original.tenantId(), + original.playableStateNamespaceId(), + UUID.randomUUID(), + original.playableStateScope(), + original.gameInstanceId(), + original.runtimeGameInstanceId(), + UUID.randomUUID().toString(), + original.regionId(), + original.regionEpoch(), + original.issuerId(), + original.issuerAuthGeneration(), + original.issuerIndexLayoutVersion(), + original.issuerIndexPartitionCount(), + original.issuerIndexPartitionCapacity()); + source + .repository() + .prepare( + new CanonicalGameplayBindingTransitionRequest( + UUID.randomUUID(), + UUID.randomUUID(), + unrelated, + new CanonicalIssuerReservationFenceEvidence( + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + BigInteger.ONE, + BigInteger.TWO, + BigInteger.ONE), + null, + null)); + } + + private static void seedSyntheticVerifiedLegacyDisposition(DSLContext dsl) { + dsl.execute( + "UPDATE game_session_canonical_binding_inventory_clock" + + " SET inventory_revision = 1 WHERE singleton_id = 1"); + dsl.execute( + "UPDATE game_session_canonical_binding_legacy_disposition" + + " SET disposition_state = 'VERIFIED'," + + " cohort_id = '10101010-1010-4010-8010-101010101010'," + + " owner_operation_id = '20202020-2020-4020-8020-202020202020'," + + " legacy_writer_fence = '30303030-3030-4030-8030-303030303030'," + + " source_snapshot_revision = 1, canonical_inventory_revision = 1," + + " namespace_index_readback_revision = 1, evidence_digest = 'sha256:" + + "0000000000000000000000000000000000000000000000000000000000000000'" + + " WHERE singleton_id = 1"); + } + + private static AccountGameplayAdmissionLeaseEvidence leaseEvidence( + CanonicalGameplayBindingIdentity candidate, + BigInteger bindingGeneration, + net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget target) { + long now = System.currentTimeMillis(); + String nowSeconds = Long.toString(now / 1000L); + Map carrier = new LinkedHashMap<>(); + carrier.put("schema", AccountGameplayAdmissionLeaseEvidence.SCHEMA); + carrier.put("schemaVersion", "1"); + carrier.put("mode", "PUBLIC_PRODUCTION"); + carrier.put("leaseKind", AccountGameplayAdmissionLeaseEvidence.LeaseKind.NEW_BINDING.name()); + carrier.put("targetNamespace", target.targetNamespace()); + carrier.put( + "callerWorkload", + "spiffe://firemud/ns/" + target.targetNamespace() + "/sa/game-session-service"); + carrier.put("requestId", UUID.randomUUID().toString()); + carrier.put("leaseId", UUID.randomUUID().toString()); + carrier.put("leaseFence", "1"); + Map scope = new LinkedHashMap<>(); + scope.put("accountId", candidate.accountId().toString()); + scope.put("tenantId", candidate.tenantId().toString()); + scope.put("realmId", target.realmId().toString()); + scope.put("worldSlug", target.worldSlug()); + scope.put("realmSlug", target.realmSlug()); + scope.put("playableStateNamespaceId", target.playableStateNamespaceId().toString()); + scope.put("playableStateScope", target.playableStateScope()); + scope.put("gameInstanceId", target.canonicalGameInstanceId().toString()); + scope.put("characterId", candidate.characterId().toString()); + scope.put("sessionId", candidate.sessionId()); + scope.put("bindingGeneration", bindingGeneration.toString()); + scope.put("catalogRevision", Long.toString(target.catalogRevision())); + scope.put("pointerVersion", Long.toString(target.pointerVersion())); + scope.put("regionId", candidate.regionId().toString()); + scope.put("regionEpoch", candidate.regionEpoch().toString()); + carrier.put("bindingScope", scope); + carrier.put( + "authorityTuple", + Map.of( + "issuerAuthGeneration", candidate.issuerAuthGeneration().toString(), + "accountAuthorityGeneration", "1", + "tenantAuthorityGeneration", Map.of(candidate.tenantId().toString(), "1"), + "membershipAuthorityGeneration", Map.of(candidate.tenantId().toString(), "1"), + "privateRealmGrantVersions", List.of())); + carrier.put("issuanceFence", "1"); + carrier.put( + "membershipBaseline", + Map.of( + "membershipLifecycleState", "ACTIVE", + "membershipVersion", Map.of(candidate.tenantId().toString(), "1"), + "membershipAuthorityGeneration", "1")); + String prefix = "account:auth-authority:v1:"; + List> checkpoints = new ArrayList<>(); + for (String stream : + List.of( + "account/" + candidate.accountId(), + "issuer/firemud-account-service", + "membership/" + candidate.accountId() + "/" + candidate.tenantId(), + "tenant/" + candidate.tenantId())) { + checkpoints.add( + Map.of( + "outboxStreamKey", + prefix + stream, + "outboxSequence", + stream.startsWith("membership/") || stream.startsWith("tenant/") ? "1" : "0")); + } + carrier.put("outboxCheckpoints", checkpoints); + carrier.put( + "tokenIdentityEvidence", + Map.ofEntries( + Map.entry("accountId", candidate.accountId().toString()), + Map.entry("operationId", UUID.randomUUID().toString()), + Map.entry("issuanceRequestId", UUID.randomUUID().toString()), + Map.entry("tokenJti", UUID.randomUUID().toString()), + Map.entry("tokenSHA256", "a".repeat(64)), + Map.entry("tokenProfile", "game-session-account-delegation"), + Map.entry("tokenGeneration", "1"), + Map.entry("issuanceFence", "1"), + Map.entry("tokenIdentityFence", "1"), + Map.entry("issuedAt", nowSeconds), + Map.entry("notBefore", nowSeconds), + Map.entry("expiresAt", Long.toString(now / 1000L + 60L)))); + carrier.put("evaluatedAt", Long.toString(now)); + carrier.put( + "expiresAt", + Long.toString(now + AccountGameplayAdmissionLeaseEvidence.MAX_DURATION_MILLIS)); + return AccountGameplayAdmissionLeaseEvidence.fromCarrier(carrier); + } + + private RedisClient createClient(String username, String password) { + RedisURI.Builder builder = + RedisURI.Builder.redis(REDIS.getHost(), REDIS.getMappedPort(PORT)) + .withTimeout(Duration.ofSeconds(3)); + if (username != null) builder.withAuthentication(username, password); + RedisClient client = RedisClient.create(builder.build()); + client.setOptions(ClientOptions.builder().autoReconnect(false).build()); + return client; + } + + private static byte[] ascii(String value) { + return value.getBytes(StandardCharsets.US_ASCII); + } + + private record TestSource( + String schema, + DriverManagerDataSource dataSource, + DSLContext dsl, + CanonicalGameplayBindingInventoryRepository repository, + CanonicalGameplayTenantGameplayTagRepository tenantTags, + CanonicalGameplayBindingIdentity identity, + CanonicalGameplayAdmissionDecision decision) + implements AutoCloseable { + @Override + public void close() { + try (var connection = + java.sql.DriverManager.getConnection( + POSTGRES.getJdbcUrl(), POSTGRES.getUsername(), POSTGRES.getPassword()); + var statement = connection.createStatement()) { + statement.execute("DROP SCHEMA IF EXISTS " + schema + " CASCADE"); + } catch (Exception failure) { + throw new IllegalStateException("Cannot drop candidate proof schema", failure); + } + } + } +} diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayProtectedIncarnationReceiverPostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayProtectedIncarnationReceiverPostgresIntegrationTest.java index 58f6f84bae..b326c1ca65 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayProtectedIncarnationReceiverPostgresIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayProtectedIncarnationReceiverPostgresIntegrationTest.java @@ -2,10 +2,20 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; import static org.mockito.Mockito.when; import com.google.protobuf.ByteString; +import io.lettuce.core.AclSetuserArgs; +import io.lettuce.core.RedisClient; +import io.lettuce.core.RedisURI; +import io.lettuce.core.api.StatefulRedisConnection; +import io.lettuce.core.protocol.CommandKeyword; +import io.lettuce.core.protocol.CommandType; import java.math.BigInteger; import java.nio.ByteBuffer; import java.nio.file.Path; @@ -21,12 +31,14 @@ import java.util.Map; import java.util.UUID; import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingIdentity; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingTransitionRequest; import net.firedevops.firemud.gamesession.binding.CanonicalIssuerReservationFenceEvidence; import net.firedevops.firemud.gamesession.dto.CanonicalGameplayLoginResult; import net.firedevops.firemud.gamesession.dto.InitialGameplayLoginAttemptCoordinates; +import net.firedevops.firemud.gamesession.service.CanonicalGameplayAccountInitialBarrierRedisScriptContribution; import net.firedevops.firemud.test.TestContainerImages; import org.flywaydb.core.Flyway; import org.jooq.DSLContext; @@ -34,6 +46,7 @@ import org.jooq.impl.DSL; import org.junit.jupiter.api.Test; import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.testcontainers.containers.GenericContainer; import org.testcontainers.containers.PostgreSQLContainer; import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; @@ -62,6 +75,158 @@ class CanonicalGameplayProtectedIncarnationReceiverPostgresIntegrationTest { static PostgreSQLContainer postgres = new PostgreSQLContainer<>(TestContainerImages.postgres()); + @Container + static GenericContainer redis = + new GenericContainer<>(TestContainerImages.redis()).withExposedPorts(6379); + + @Test + void initialOwnerComposesSqlSignedObservationAndRedisWithoutRecreatingResetOpen() + throws Exception { + for (BigInteger epoch : List.of(BigInteger.ZERO, BigInteger.valueOf(8))) { + try (Fixture.InitialFixture fixture = Fixture.InitialFixture.open(epoch); + InitialRedisFixture physical = InitialRedisFixture.open(); + CanonicalGameplayLoginResult login = fixture.originalLogin()) { + var owner = fixture.initialOwner(physical.ownerClient(), fixture.initialRepository); + var initialized = + owner.initializeOnce(fixture.original, login, fixture.tenantId, fixture.namespaceId); + assertThat(initialized) + .isInstanceOf(CanonicalGameplayAccountInitialOpenProof.CurrentOpen.class); + var opened = (CanonicalGameplayAccountInitialOpenProof.CurrentOpen) initialized; + assertThat(opened.sourceControlEpoch()).isEqualTo(epoch); + assertThat(opened.exactFields()).hasSize(9); + assertThat(physical.connection().sync().hgetall(opened.key())) + .isEqualTo(opened.exactFields()); + String retained = fixture.initialTargetPostimage(); + + var replay = owner.verifyCurrentOpen(fixture.original.requestId()); + assertThat(replay).isInstanceOf(CanonicalGameplayAccountInitialOpenProof.CurrentOpen.class); + assertThat(((CanonicalGameplayAccountInitialOpenProof.CurrentOpen) replay).exactFields()) + .isEqualTo(opened.exactFields()); + assertThat(fixture.initialTargetPostimage()).isEqualTo(retained); + + fixture.dsl.execute( + "UPDATE game_session_initial_gameplay_login_journal" + + " SET abandoned = true, abandoned_at = CURRENT_TIMESTAMP" + + " WHERE request_id = ?", + fixture.original.requestId()); + // The installed target is storage evidence independent of a later caller. The old LOGIN + // cannot create anything, while another binding may verify the same current target. + assertThat( + owner.verifyCurrentOpenForTarget( + fixture.accountId, fixture.tenantId, fixture.namespaceId)) + .isInstanceOf(CanonicalGameplayAccountInitialOpenProof.CurrentOpen.class); + assertThat( + owner.initializeOnce( + fixture.original, login, fixture.tenantId, fixture.namespaceId)) + .isInstanceOf(CanonicalGameplayAccountInitialOpenProof.Refused.class); + assertThat(physical.connection().sync().hgetall(opened.key())) + .isEqualTo(opened.exactFields()); + assertThat(fixture.initialTargetPostimage()).isEqualTo(retained); + + physical.connection().sync().del(opened.key()); + assertThat(owner.verifyCurrentOpen(fixture.original.requestId())) + .isInstanceOf(CanonicalGameplayAccountInitialOpenProof.Refused.class); + assertThat( + owner.initializeOnce( + fixture.original, login, fixture.tenantId, fixture.namespaceId)) + .isInstanceOf(CanonicalGameplayAccountInitialOpenProof.Refused.class); + assertThat(physical.connection().sync().exists(opened.key())).isZero(); + assertThat(fixture.initialTargetPostimage()).isEqualTo(retained); + } + } + } + + @Test + void initialOwnerRecoversLostSqlReceiptFromExactPhysicalOpenWithoutAnotherCreate() + throws Exception { + try (Fixture.InitialFixture fixture = Fixture.InitialFixture.open(); + InitialRedisFixture physical = InitialRedisFixture.open(); + CanonicalGameplayLoginResult login = fixture.originalLogin()) { + var repository = spy(fixture.initialRepository); + // Controlled receipt loss after the real SQL dispatch and real Redis write/readback. + doThrow(new IllegalStateException("Controlled loss of first SQL receipt")) + .doCallRealMethod() + .when(repository) + .acceptOpenReadback(eq(fixture.original.requestId()), any()); + var owner = fixture.initialOwner(physical.ownerClient(), repository); + assertThat( + owner.initializeOnce(fixture.original, login, fixture.tenantId, fixture.namespaceId)) + .isInstanceOf(CanonicalGameplayAccountInitialOpenProof.Refused.class); + assertThat(repository.readCurrent(fixture.original.requestId()).state()) + .isEqualTo( + CanonicalGameplayAccountInitialBarrierInitializerRepository.State.DISPATCH_POSSIBLE); + String key = + CanonicalGameplayAccountInitialBarrierKey.forTarget( + fixture.tenantTags.assignmentForInitialBarrierTarget(fixture.original.requestId()), + repository.readCurrent(fixture.original.requestId()).initializerId(), + fixture.original.requestId()); + Map firstPostimage = physical.connection().sync().hgetall(key); + + var recovered = + owner.initializeOnce(fixture.original, login, fixture.tenantId, fixture.namespaceId); + assertThat(recovered) + .isInstanceOf(CanonicalGameplayAccountInitialOpenProof.CurrentOpen.class); + assertThat(((CanonicalGameplayAccountInitialOpenProof.CurrentOpen) recovered).key()) + .isEqualTo(key); + assertThat(physical.connection().sync().hgetall(key)).isEqualTo(firstPostimage); + assertThat(repository.readCurrent(fixture.original.requestId()).state()) + .isEqualTo( + CanonicalGameplayAccountInitialBarrierInitializerRepository.State.OPEN_INSTALLED); + String retained = fixture.initialTargetPostimage(); + assertThat(owner.verifyCurrentOpen(fixture.original.requestId())) + .isInstanceOf(CanonicalGameplayAccountInitialOpenProof.CurrentOpen.class); + assertThat(fixture.initialTargetPostimage()).isEqualTo(retained); + } + } + + private record InitialRedisFixture( + RedisClient administrator, + StatefulRedisConnection connection, + RedisClient ownerClient) + implements AutoCloseable { + static InitialRedisFixture open() { + String principal = "gamesession_coord_app"; + String password = UUID.randomUUID().toString(); + RedisClient administrator = + RedisClient.create(RedisURI.create(redis.getHost(), redis.getMappedPort(6379))); + StatefulRedisConnection connection = administrator.connect(); + // This container is owned solely by this test class; each case removes only its own key. + connection + .sync() + .aclSetuser( + principal, + new AclSetuserArgs() + .reset() + .on() + .addPassword(password) + .keyPattern("session:game:*") + .addCommand(CommandType.HELLO) + .addCommand(CommandType.PING) + .addCommand(CommandType.CLIENT, CommandKeyword.SETINFO) + .addCommand(CommandType.ACL, CommandKeyword.WHOAMI) + .addCommand(CommandType.SCRIPT, CommandKeyword.LOAD) + .addCommand(CommandType.EVALSHA) + .addCommand(CommandType.TYPE) + .addCommand(CommandType.PTTL) + .addCommand(CommandType.HLEN) + .addCommand(CommandType.HGETALL) + .addCommand(CommandType.HSET)); + RedisClient owner = + RedisClient.create( + RedisURI.Builder.redis(redis.getHost(), redis.getMappedPort(6379)) + .withAuthentication(principal, password) + .build()); + return new InitialRedisFixture(administrator, connection, owner); + } + + @Override + public void close() { + connection.close(); + ownerClient.shutdown(Duration.ZERO, Duration.ofSeconds(2)); + administrator.shutdown(Duration.ZERO, Duration.ofSeconds(2)); + } + } + @Test void verifiesOnlySignedExactCurrentTargetAndRejectsReplayAndMismatches() throws Exception { try (Fixture fixture = Fixture.open()) { @@ -712,6 +877,10 @@ private InitialFixture( } private static InitialFixture open() throws Exception { + return open(BigInteger.valueOf(8)); + } + + private static InitialFixture open(BigInteger sourceControlEpoch) throws Exception { String schema = "gs_initial_incarnation_" + UUID.randomUUID().toString().replace("-", ""); DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName("org.postgresql.Driver"); @@ -769,7 +938,8 @@ private static InitialFixture open() throws Exception { transitionId, UUID.randomUUID(), identity, reservation, null, null)); dsl.execute( "UPDATE game_session_canonical_account_coverage_control" - + " SET last_operation_fence = 8 WHERE account_id = ?", + + " SET last_operation_fence = ? WHERE account_id = ?", + sourceControlEpoch, accountId); InitialGameplayLoginAttemptCoordinates original = @@ -845,6 +1015,54 @@ private CanonicalGameplayProtectedIncarnationReceiver receiver( Clock.fixed(NOW, ZoneOffset.UTC)); } + private CanonicalGameplayLoginResult originalLogin() { + UUID tokenJti = + dsl.fetchOne( + "SELECT verified_token_jti FROM game_session_initial_gameplay_login_journal" + + " WHERE request_id = ?", + original.requestId()) + .get(0, UUID.class); + return mockInitialLoginResult(original, accountId, tokenJti); + } + + private String initialTargetPostimage() { + return dsl.fetchOne( + "SELECT to_jsonb(t)::text FROM game_session_canonical_initial_account_barrier_target t" + + " WHERE initializer_id = ?", + initialRepository.readCurrent(original.requestId()).initializerId()) + .get(0, String.class); + } + + private CanonicalGameplayAccountInitialBarrierRedisOwner initialOwner( + RedisClient client, + CanonicalGameplayAccountInitialBarrierInitializerRepository repository) { + var configuration = + new CanonicalGameplayProtectedIncarnationReceiver.TrustedConfiguration( + ATTESTOR_BINDING, + ACCEPTED_ATTESTATION_DIGEST, + Map.of(KEY_ID, (java.security.interfaces.RSAPublicKey) keyPair.getPublic()), + expectedEvidence, + ACL_DIGEST, + CONFIG_DIGEST, + 16 * 1024, + 1, + Duration.ofSeconds(30)); + var receiver = + new CanonicalGameplayProtectedIncarnationReceiver( + repository, + tenantTags, + new ControlledSigner(keyPair), + configuration, + Clock.systemUTC()); + return new CanonicalGameplayAccountInitialBarrierRedisOwner( + client, + RedisScriptCatalog.fromContributions( + List.of(new CanonicalGameplayAccountInitialBarrierRedisScriptContribution())), + repository, + tenantTags, + receiver); + } + private InitialGameplayLoginAttemptCoordinates original() { return original; } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountGameplayAdmissionLeaseClientTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountGameplayAdmissionLeaseClientTest.java index 8168fe8b97..fe2c51762b 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountGameplayAdmissionLeaseClientTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountGameplayAdmissionLeaseClientTest.java @@ -21,6 +21,7 @@ import java.security.MessageDigest; import java.time.Instant; import java.util.ArrayList; +import java.util.Base64; import java.util.HexFormat; import java.util.LinkedHashMap; import java.util.List; @@ -33,12 +34,17 @@ import net.firedevops.firemud.account.v1.AccountGameplayAdmissionLeaseResponse; import net.firedevops.firemud.account.v1.AccountGameplayAdmissionLeaseServiceGrpc; import net.firedevops.firemud.account.v1.AcquireGameplayAdmissionLeaseRequest; +import net.firedevops.firemud.account.v1.ConfirmOriginalNewGameplayAdmissionRequest; import net.firedevops.firemud.account.v1.FinalizeGameplayAdmissionLeaseRequest; +import net.firedevops.firemud.account.v1.IssueOriginalNewGameplayCredentialRequest; +import net.firedevops.firemud.account.v1.OriginalNewAdmissionConfirmationResponse; import net.firedevops.firemud.account.v1.ReadGameplayAdmissionLeaseRequest; import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseGrpcCodec; import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseGrpcCodec.AcquireRequest; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseGrpcCodec.OriginalAckReceiptEvidence; import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseGrpcCodec.OriginalLeaseRequest; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseGrpcCodec.OriginalNewCredential; import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseGrpcCodec.State; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.Candidate; @@ -51,6 +57,7 @@ import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; import net.firedevops.firemud.common.grpc.GrpcRequestBytePolicy; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold; import net.firedevops.firemud.test.LoopbackMtlsTestPki; @@ -59,6 +66,7 @@ import org.junit.jupiter.api.Timeout; import org.junit.jupiter.api.io.TempDir; import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.databind.json.JsonMapper; /** Controlled Account peer transport proof; the returned lease is codec evidence only. */ @Timeout(60) @@ -76,6 +84,7 @@ class AccountGameplayAdmissionLeaseClientTest { private static final UUID HOLD_FENCE = UUID.fromString("66666666-6666-4666-8666-666666666666"); private static final UUID DECISION_ID = UUID.fromString("77777777-7777-4777-8777-777777777777"); private static final String HIGH = "9007199254740993"; + private static final JsonMapper JSON = JsonMapper.builder().build(); @TempDir static Path directory; private static LoopbackMtlsTestPki.Pki pki; @@ -222,6 +231,145 @@ public void abortGameplayAdmissionLease( } } + @Test + void originalNewRpcCarriesOpaqueCredentialAndConfirmsOnlyAccountReadbackAnchors() + throws Exception { + var observed = new CopyOnWriteArrayList(); + var deadlines = new CopyOnWriteArrayList(); + var issuedRequests = new CopyOnWriteArrayList(); + var confirmationRequests = + new CopyOnWriteArrayList(); + byte[] handle = new byte[32]; + java.util.Arrays.fill(handle, (byte) 0x2a); + Server server = + server( + "account-server", + new AccountGameplayAdmissionLeaseServiceGrpc + .AccountGameplayAdmissionLeaseServiceImplBase() { + @Override + public void issueOriginalNewGameplayCredential( + IssueOriginalNewGameplayCredentialRequest request, + StreamObserver observer) { + capture(observed, deadlines); + issuedRequests.add(request); + try { + var parsed = + AccountGameplayAdmissionLeaseGrpcCodec.parseIssueOriginalNewCredentialRequest( + request); + var lease = parsed.originalLeaseEvidence(); + Map carrier = lease.carrier(); + Map scope = object(carrier, "bindingScope"); + Map claims = testBoundClaims(lease); + String compactJwt = testCompactJwt(claims); + UUID lineage = UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + UUID tokenJti = UUID.fromString("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"); + OriginalNewCredential credential = + AccountGameplayAdmissionLeaseGrpcCodec.originalNewCredential( + compactJwt, + handle, + lineage, + tokenJti, + jwtSha256(compactJwt), + Long.parseLong((String) carrier.get("issuanceFence")), + UUID.fromString((String) carrier.get("leaseId")), + lease.leaseFence().longValueExact(), + "102", + checkpointsSha256(carrier.get("outboxCheckpoints"))); + var ack = + OriginalAckReceiptEvidence.fromFields( + 1, + UUID.fromString((String) carrier.get("requestId")), + UUID.fromString((String) scope.get("accountId")), + UUID.fromString((String) carrier.get("leaseId")), + lease.leaseFence().longValueExact(), + lease.sha256(), + DECISION_ID, + 1_015_000L, + "101", + 1_014_999L, + "102"); + observer.onNext( + AccountGameplayAdmissionLeaseGrpcCodec.toIssueOriginalNewCredentialResponse( + parsed, lease, State.COMMITTED, DECISION_ID, ack, credential)); + observer.onCompleted(); + credential.close(); + } catch (RuntimeException malformed) { + observer.onError(Status.INVALID_ARGUMENT.asRuntimeException()); + } + } + + @Override + public void confirmOriginalNewGameplayAdmission( + ConfirmOriginalNewGameplayAdmissionRequest request, + StreamObserver observer) { + capture(observed, deadlines); + confirmationRequests.add(request); + var parsed = + AccountGameplayAdmissionLeaseGrpcCodec + .parseConfirmOriginalNewGameplayAdmissionRequest(request); + var lease = parsed.originalLeaseEvidence(); + observer.onNext( + AccountGameplayAdmissionLeaseGrpcCodec + .toConfirmOriginalNewGameplayAdmissionResponse( + parsed, + UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), + UUID.fromString((String) lease.carrier().get("leaseId")), + lease.leaseFence().longValueExact(), + 1_020_000L, + 1_320_000L, + "c".repeat(64))); + observer.onCompleted(); + } + }); + try (var client = client(server)) { + client.init(); + byte[] originalLease = lease().canonicalJson().getBytes(StandardCharsets.UTF_8); + OriginalNewCredential received = + client.issueOriginalNewBoundGameplayCredential(JWT, originalLease); + byte[] receivedHandle = received.opaqueRebindHandle(); + try { + assertThat(receivedHandle).containsExactly(handle); + } finally { + java.util.Arrays.fill(receivedHandle, (byte) 0); + } + assertThat(received.toString()).doesNotContain(JWT, HexFormat.of().formatHex(handle)); + var confirmation = client.confirmOriginalNewGameplayAdmission(JWT, originalLease); + + assertThat(observed).containsExactly(GAME_SESSION_PEER, GAME_SESSION_PEER); + assertThat(issuedRequests) + .singleElement() + .satisfies( + request -> { + assertThat(request.getPresentedInitialGsaCompactJwt(0)).isEqualTo(JWT); + assertThat(request.getOriginalLeaseEvidenceUtf8(0).toByteArray()) + .containsExactly(originalLease); + }); + assertThat(confirmation.lineageId()) + .isEqualTo(UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa")); + assertThat(confirmation.continuityExpiresAtMillis()).isEqualTo(1_320_000L); + assertThat(confirmationRequests) + .singleElement() + .satisfies( + request -> { + assertThat(request.getPresentedInitialGsaCompactJwt(0)).isEqualTo(JWT); + assertThat(request.getOriginalLeaseEvidenceUtf8(0).toByteArray()) + .containsExactly(originalLease); + }); + assertThat(deadlines) + .hasSize(2) + .allSatisfy( + deadline -> { + long remainingMillis = deadline.timeRemaining(TimeUnit.MILLISECONDS); + assertThat(remainingMillis).isPositive().isLessThanOrEqualTo(5_000L); + }); + received.close(); + java.util.Arrays.fill(originalLease, (byte) 0); + } finally { + java.util.Arrays.fill(handle, (byte) 0); + stop(server); + } + } + @Test void wrongAccountRoleAndNamespaceAreRejectedBeforeServerHandlerReceivesJwt() throws Exception { for (String identity : List.of("wrong-role", "foreign-namespace")) { @@ -730,6 +878,64 @@ private static AccountGameplayAdmissionLeaseEvidence lease() { return AccountGameplayAdmissionLeaseEvidence.fromCarrier(value); } + private static Map testBoundClaims(AccountGameplayAdmissionLeaseEvidence lease) { + Map carrier = lease.carrier(); + Map scope = object(carrier, "bindingScope"); + Map baseline = object(carrier, "membershipBaseline"); + long issuedAt = Instant.now().getEpochSecond(); + Map claims = new LinkedHashMap<>(); + claims.put("iss", GameSessionAccountDelegationProfile.ISSUER); + claims.put("sub", scope.get("accountId")); + claims.put("jti", "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"); + claims.put("accountId", scope.get("accountId")); + claims.put("aud", GameSessionAccountDelegationProfile.AUDIENCE); + claims.put("iat", issuedAt); + claims.put("nbf", issuedAt); + claims.put("exp", issuedAt + 120L); + claims.put("tokenGeneration", "1"); + claims.put("authorityTuple", carrier.get("authorityTuple")); + claims.put("membershipVersion", baseline.get("membershipVersion")); + claims.put("issuanceFence", carrier.get("issuanceFence")); + claims.put("tenantId", scope.get("tenantId")); + return claims; + } + + private static String testCompactJwt(Map claims) { + try { + String header = + Base64.getUrlEncoder() + .withoutPadding() + .encodeToString( + "{\"alg\":\"RS256\",\"kid\":\"controlled-test\"}" + .getBytes(StandardCharsets.UTF_8)); + String payload = + Base64.getUrlEncoder().withoutPadding().encodeToString(JSON.writeValueAsBytes(claims)); + return header + "." + payload + ".c2ln"; + } catch (Exception malformed) { + throw new IllegalStateException("Controlled JWT fixture could not be encoded", malformed); + } + } + + private static String checkpointsSha256(Object checkpoints) { + byte[] canonical = null; + try { + canonical = Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(checkpoints)); + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(canonical)); + } catch (Exception malformed) { + throw new IllegalStateException( + "Controlled checkpoint fixture could not be hashed", malformed); + } finally { + if (canonical != null) java.util.Arrays.fill(canonical, (byte) 0); + } + } + + private static Map object(Map source, String field) { + Object value = source.get(field); + if (!(value instanceof Map object)) + throw new IllegalArgumentException("Fixture map required"); + return object; + } + private static String jwtSha256(String jwt) { try { return HexFormat.of() diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierRedisOwnerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierRedisOwnerTest.java index d0124cad6b..0cf078dcd0 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierRedisOwnerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierRedisOwnerTest.java @@ -124,8 +124,7 @@ void missingPhysicalValueAfterPossibleDispatchRefusesWithoutFreshScriptAttempt() .isEqualTo( new CanonicalGameplayAccountInitialOpenProof.Refused( CanonicalGameplayAccountInitialOpenProof.Reason.REMOTE_OUTCOME_UNCERTAIN)); - verify(repository) - .beginOrRead(eq(original), any(), eq(tenantId), eq(namespaceId)); + verify(repository).beginOrRead(eq(original), any(), eq(tenantId), eq(namespaceId)); verify(commands).type(any(byte[].class)); verifyNoInteractions(catalog); } @@ -306,8 +305,7 @@ void exactSameOriginalOpenReplayIsReadOnlyAndReturnsCurrentTypedProof() throws E assertThat(current.sourceControlEpoch()).isEqualTo(BigInteger.valueOf(8)); assertThat(current.exactFields()).isEqualTo(expected.fields()); verify(repository, org.mockito.Mockito.times(2)).readCurrent(requestId); - verify(repository) - .beginOrRead(eq(original), any(), eq(tenantId), eq(namespaceId)); + verify(repository).beginOrRead(eq(original), any(), eq(tenantId), eq(namespaceId)); verify(repository, org.mockito.Mockito.times(3)).requireNoAmbientTransaction(); verify(receiver, org.mockito.Mockito.times(2)).observeForInitialAccountBarrier(requestId); verifyNoInteractions(catalog); @@ -315,6 +313,170 @@ void exactSameOriginalOpenReplayIsReadOnlyAndReturnsCurrentTypedProof() throws E verify(commands, org.mockito.Mockito.never()).evalsha(any(), any(), any(), any()); } + @Test + @SuppressWarnings({"unchecked", "rawtypes"}) + void installedOpenCanBeResolvedByExactTargetAndOnlyPerformsFreshReadback() throws Exception { + UUID requestId = UUID.randomUUID(); + UUID callerContextId = UUID.randomUUID(); + UUID initializerId = UUID.randomUUID(); + UUID accountId = UUID.randomUUID(); + UUID tenantId = UUID.randomUUID(); + UUID namespaceId = UUID.randomUUID(); + String tag = "g8-" + "b".repeat(32); + var snapshot = + new CanonicalGameplayAccountInitialBarrierInitializerRepository.InitializerSnapshot( + initializerId, + requestId, + callerContextId, + 17L, + accountId, + tenantId, + namespaceId, + DIGEST, + "NO_ACTIVE_ACCOUNT_WIDE_FLOW", + BigInteger.valueOf(8), + BigInteger.valueOf(4), + DIGEST, + CanonicalGameplayAccountInitialBarrierInitializerRepository.State.OPEN_INSTALLED, + DIGEST, + DIGEST, + DIGEST, + 1_000L, + 1_100L, + 31_000L, + DIGEST, + DIGEST); + var assignment = mock(CanonicalGameplayTenantGameplayTagRepository.Assignment.class); + when(assignment.isInitialBarrierTarget()).thenReturn(true); + when(assignment.initialBarrierInitializerId()).thenReturn(initializerId); + when(assignment.initialBarrierOriginalRequestId()).thenReturn(requestId); + when(assignment.accountId()).thenReturn(accountId); + when(assignment.tenantId()).thenReturn(tenantId); + when(assignment.playableStateNamespaceId()).thenReturn(namespaceId); + when(assignment.tenantGameplayTag()).thenReturn(tag); + var repository = mock(CanonicalGameplayAccountInitialBarrierInitializerRepository.class); + when(repository.readInstalledOpenForTarget(accountId, tenantId, namespaceId)) + .thenReturn(snapshot); + when(repository.readCurrent(requestId)).thenReturn(snapshot); + var tenantTags = mock(CanonicalGameplayTenantGameplayTagRepository.class); + when(tenantTags.assignmentForInitialBarrierTarget(requestId)).thenReturn(assignment); + var observation = initialObservation(snapshot); + var receiver = mock(CanonicalGameplayProtectedIncarnationReceiver.class); + when(receiver.observeForInitialAccountBarrier(requestId)).thenReturn(observation); + + var expected = + CanonicalGameplayAccountInitialBarrierValue.open( + accountId, tenantId, namespaceId, tag, initializerId, BigInteger.valueOf(8), DIGEST); + Map raw = new HashMap<>(); + expected + .fields() + .forEach( + (field, value) -> + raw.put( + field.getBytes(StandardCharsets.US_ASCII), + value.getBytes(StandardCharsets.US_ASCII))); + RedisClient redis = mock(RedisClient.class); + StatefulRedisConnection connection = mock(StatefulRedisConnection.class); + RedisAsyncCommands commands = mock(RedisAsyncCommands.class); + when(redis.connect(any(ByteArrayCodec.class))).thenReturn(connection); + when(connection.isOpen()).thenReturn(true); + when(connection.async()).thenReturn(commands); + doReturn(future("gamesession_coord_app")).when(commands).aclWhoami(); + doReturn(future("hash")).when(commands).type(any(byte[].class)); + doReturn(future(-1L)).when(commands).pttl(any(byte[].class)); + doReturn(future(9L)).when(commands).hlen(any(byte[].class)); + doReturn(future(raw)).when(commands).hgetall(any(byte[].class)); + RedisScriptCatalog catalog = mock(RedisScriptCatalog.class); + var owner = + new CanonicalGameplayAccountInitialBarrierRedisOwner( + redis, catalog, repository, tenantTags, receiver); + + var proof = owner.verifyCurrentOpenForTarget(accountId, tenantId, namespaceId); + + assertThat(proof).isInstanceOf(CanonicalGameplayAccountInitialOpenProof.CurrentOpen.class); + var current = (CanonicalGameplayAccountInitialOpenProof.CurrentOpen) proof; + assertThat(current.originalRequestId()).isEqualTo(requestId); + assertThat(current.exactFields()).isEqualTo(expected.fields()); + verify(repository).readInstalledOpenForTarget(accountId, tenantId, namespaceId); + verify(repository, org.mockito.Mockito.times(2)).readCurrent(requestId); + verify(tenantTags).assignmentForInitialBarrierTarget(requestId); + verify(receiver, org.mockito.Mockito.times(2)).observeForInitialAccountBarrier(requestId); + verifyNoInteractions(catalog); + verify(commands).hgetall(any(byte[].class)); + verify(commands, org.mockito.Mockito.never()).evalsha(any(), any(), any(), any()); + } + + @Test + void missingAmbiguousAndStaleTargetResolutionNeverReachPhysicalReadOrCreate() { + UUID missingAccount = UUID.randomUUID(); + UUID ambiguousAccount = UUID.randomUUID(); + UUID staleAccount = UUID.randomUUID(); + UUID tenantId = UUID.randomUUID(); + UUID namespaceId = UUID.randomUUID(); + var repository = mock(CanonicalGameplayAccountInitialBarrierInitializerRepository.class); + when(repository.readInstalledOpenForTarget(missingAccount, tenantId, namespaceId)) + .thenThrow(new IllegalStateException("no installed target")); + when(repository.readInstalledOpenForTarget(ambiguousAccount, tenantId, namespaceId)) + .thenThrow(new IllegalStateException("multiple installed targets")); + when(repository.readInstalledOpenForTarget(staleAccount, tenantId, namespaceId)) + .thenThrow(new IllegalStateException("NO_ACTIVE source changed")); + var tenantTags = mock(CanonicalGameplayTenantGameplayTagRepository.class); + var receiver = mock(CanonicalGameplayProtectedIncarnationReceiver.class); + RedisClient redis = mock(RedisClient.class); + RedisScriptCatalog catalog = mock(RedisScriptCatalog.class); + var owner = + new CanonicalGameplayAccountInitialBarrierRedisOwner( + redis, catalog, repository, tenantTags, receiver); + + var missing = owner.verifyCurrentOpenForTarget(missingAccount, tenantId, namespaceId); + var ambiguous = owner.verifyCurrentOpenForTarget(ambiguousAccount, tenantId, namespaceId); + var stale = owner.verifyCurrentOpenForTarget(staleAccount, tenantId, namespaceId); + + var refused = + new CanonicalGameplayAccountInitialOpenProof.Refused( + CanonicalGameplayAccountInitialOpenProof.Reason.SOURCE_CONTROL_UNAVAILABLE); + assertThat(missing).isEqualTo(refused); + assertThat(ambiguous).isEqualTo(refused); + assertThat(stale).isEqualTo(refused); + verify(repository).readInstalledOpenForTarget(missingAccount, tenantId, namespaceId); + verify(repository).readInstalledOpenForTarget(ambiguousAccount, tenantId, namespaceId); + verify(repository).readInstalledOpenForTarget(staleAccount, tenantId, namespaceId); + verifyNoInteractions(tenantTags, receiver, redis, catalog); + } + + @Test + void nonInstalledTargetIsRefusedWithoutFresheningOrRecreatingIt() { + UUID accountId = UUID.randomUUID(); + UUID tenantId = UUID.randomUUID(); + UUID namespaceId = UUID.randomUUID(); + var never = + snapshot( + UUID.randomUUID(), + new InitialGameplayLoginAttemptCoordinates(UUID.randomUUID(), UUID.randomUUID(), 17L), + accountId, + tenantId, + namespaceId, + CanonicalGameplayAccountInitialBarrierInitializerRepository.State.NEVER_DISPATCHED); + var repository = mock(CanonicalGameplayAccountInitialBarrierInitializerRepository.class); + when(repository.readInstalledOpenForTarget(accountId, tenantId, namespaceId)).thenReturn(never); + var tenantTags = mock(CanonicalGameplayTenantGameplayTagRepository.class); + var receiver = mock(CanonicalGameplayProtectedIncarnationReceiver.class); + RedisClient redis = mock(RedisClient.class); + RedisScriptCatalog catalog = mock(RedisScriptCatalog.class); + var owner = + new CanonicalGameplayAccountInitialBarrierRedisOwner( + redis, catalog, repository, tenantTags, receiver); + + var proof = owner.verifyCurrentOpenForTarget(accountId, tenantId, namespaceId); + + assertThat(proof) + .isEqualTo( + new CanonicalGameplayAccountInitialOpenProof.Refused( + CanonicalGameplayAccountInitialOpenProof.Reason.TARGET_NEVER_DISPATCHED)); + verify(repository).readInstalledOpenForTarget(accountId, tenantId, namespaceId); + verifyNoInteractions(tenantTags, receiver, redis, catalog); + } + @Test @SuppressWarnings({"unchecked", "rawtypes"}) void ambiguousDispatchRetryRequiresExactOpenReadbackBeforeCompletingOriginalReceipt() diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewAuthenticatedSessionTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewAuthenticatedSessionTest.java new file mode 100644 index 0000000000..5a1918e2b6 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewAuthenticatedSessionTest.java @@ -0,0 +1,709 @@ +package net.firedevops.firemud.gamesession.repository; + +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.ArrayNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.MessageDigest; +import java.security.Signature; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Base64; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseGrpcCodec; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.security.AccountPublicJwksCache; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingIdentity; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionOwnerProof.Outcome; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionRequest.OriginKind; +import net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +class CanonicalGameplayOriginalNewAuthenticatedSessionTest { + private static final ObjectMapper JSON = new ObjectMapper(); + private static final Clock CLOCK = + Clock.fixed(Instant.parse("2026-10-27T00:00:00Z"), ZoneOffset.UTC); + private static final UUID ACCOUNT_ID = uuid("11111111-1111-4111-8111-111111111111"); + private static final UUID TENANT_ID = uuid("22222222-2222-4222-8222-222222222222"); + private static final UUID PLAYABLE_NAMESPACE_ID = uuid("33333333-3333-4333-8333-333333333333"); + private static final UUID CHARACTER_ID = uuid("44444444-4444-4444-8444-444444444444"); + private static final UUID GAME_INSTANCE_ID = uuid("55555555-5555-4555-8555-555555555555"); + private static final UUID SESSION_ID = uuid("66666666-6666-4666-8666-666666666666"); + private static final UUID REGION_ID = uuid("77777777-7777-4777-8777-777777777777"); + private static final UUID REALM_ID = uuid("88888888-8888-4888-8888-888888888888"); + private static final UUID VERSION_ID = uuid("99999999-9999-4999-8999-999999999999"); + private static final UUID REQUEST_ID = uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + private static final UUID LEASE_ID = uuid("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"); + private static final UUID BINDING_DECISION_ID = uuid("cccccccc-cccc-4ccc-8ccc-cccccccccccc"); + private static final UUID RESERVATION_ID = uuid("dddddddd-dddd-4ddd-8ddd-dddddddddddd"); + private static final UUID RESERVATION_FENCE = uuid("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"); + private static final UUID ACCOUNT_INDEX_FENCE = uuid("ffffffff-ffff-4fff-8fff-ffffffffffff"); + private static final UUID COVERAGE_OPERATION_ID = uuid("10101010-1010-4010-8010-101010101010"); + private static final UUID LOGIN_JTI = uuid("12121212-1212-4212-8212-121212121212"); + private static final UUID LINEAGE_ID = uuid("13131313-1313-4313-8313-131313131313"); + private static final UUID BOUND_JTI = uuid("14141414-1414-4414-8414-141414141414"); + private static final UUID OTHER_ID = uuid("15151515-1515-4515-8515-151515151515"); + private static final String NAMESPACE = "test"; + private static final String GAME_SESSION_PEER = + "spiffe://firemud/ns/test/sa/game-session-service"; + private static final String HANDLE_HEX = + "00112233445566778899aabbccddeeff00112233445566778899aabbccddeeff"; + private static final byte[] HANDLE = HexFormat.of().parseHex(HANDLE_HEX); + private static final String ONE = "1"; + private static final String TOKEN_FENCE = "7"; + private static final long NOW_SECONDS = CLOCK.instant().getEpochSecond(); + private static final long SESSION_DURATION_MILLIS = 120_000L; + private static KeyPair ACCOUNT_SIGNING_KEYS; + + @BeforeAll + static void generateControlledAccountSigningKey() throws Exception { + KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); + generator.initialize(3072); + ACCOUNT_SIGNING_KEYS = generator.generateKeyPair(); + } + + @Test + void buildsNonPersistableTemplateAndAcceptsExactFinalCasReadback() throws Exception { + try (Fixture fixture = fixture(claims -> {}); + var template = template(fixture)) { + byte[] templateBytes = template.finalCasTemplateBytes(); + String templateJson = new String(templateBytes, StandardCharsets.UTF_8); + assertThat(templateJson) + .contains("__ORIGINAL_NEW_ADMISSION_AT_MS__") + .contains("__ORIGINAL_NEW_CONTINUITY_EXPIRES_AT_MS__") + .doesNotContain(fixture.compactJwt) + .doesNotContain("\"lineageId\"") + .doesNotContain("\"authTokenJti\""); + assertThatThrownBy( + () -> + CanonicalGameplayOriginalNewAuthenticatedSession.parseFinalized( + templateBytes, CLOCK)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Canonical ORIGINAL_NEW authenticated session is invalid"); + + long admissionAt = CLOCK.millis() + 100L; + byte[] finalBytes = finalizeTemplate(templateBytes, admissionAt, SESSION_DURATION_MILLIS); + try (var finalized = template.requireFinalizedReadback(finalBytes)) { + assertThat(finalized.originalCandidate().bindingDecisionId()) + .isEqualTo(BINDING_DECISION_ID); + assertThat(finalized.admissionAtMillis()).isEqualTo(admissionAt); + assertThat(finalized.continuityBindingExpiresAtMillis()) + .isEqualTo(admissionAt + SESSION_DURATION_MILLIS); + assertThat(finalized.authTokenHash()).isEqualTo(hash(fixture.compactJwt)); + assertThat(finalized.authTokenIssuedAt()).isEqualTo(NOW_SECONDS); + assertThat(finalized.authTokenExpiresAt()).isEqualTo(NOW_SECONDS + 240L); + assertThat(finalized.tokenGeneration()).isEqualTo("1"); + assertThat(finalized.issuanceFence()).isEqualTo(TOKEN_FENCE); + assertThat(finalized.canonicalSessionDurationMillis()).isEqualTo(SESSION_DURATION_MILLIS); + byte[] returnedHandle = finalized.opaqueRebindHandle(); + try { + assertThat(returnedHandle).containsExactly(HANDLE); + } finally { + Arrays.fill(returnedHandle, (byte) 0); + } + byte[] exactBytes = finalized.canonicalBytes(); + try { + assertThat(exactBytes).containsExactly(finalBytes); + } finally { + Arrays.fill(exactBytes, (byte) 0); + } + assertThat(finalized.toString()).doesNotContain(HANDLE_HEX, fixture.compactJwt); + } finally { + Arrays.fill(templateBytes, (byte) 0); + Arrays.fill(finalBytes, (byte) 0); + } + } + } + + @Test + void accountSignatureAndBoundClaimsMustMatchTheOriginalLeaseAndCredential() throws Exception { + try (Fixture valid = fixture(claims -> {})) { + try (var template = template(valid)) { + assertThat(template.toString()).doesNotContain(valid.compactJwt, HANDLE_HEX); + } + } + + try (Fixture unscoped = + fixture( + claims -> { + claims.remove("tenantId"); + claims.put("authorityTuple", unscopedTuple()); + claims.put("membershipVersion", Map.of()); + })) { + assertVerifierDenies(unscoped); + } + + try (Fixture mismatchedTenant = + fixture(claims -> claims.put("tenantId", OTHER_ID.toString()))) { + assertVerifierDenies(mismatchedTenant); + } + + try (Fixture roles = fixture(claims -> claims.put("globalRoles", List.of()))) { + assertVerifierDenies(roles); + } + + try (Fixture expired = + fixture( + claims -> { + claims.put("exp", NOW_SECONDS - 1L); + claims.put("nbf", NOW_SECONDS - 5L); + })) { + assertVerifierDenies(expired); + } + + try (Fixture futureIat = + fixture( + claims -> { + claims.put("iat", NOW_SECONDS + 6L); + claims.put("nbf", NOW_SECONDS + 6L); + claims.put("exp", NOW_SECONDS + 100L); + })) { + assertVerifierDenies(futureIat); + } + + try (Fixture wrongJti = fixture(claims -> claims.put("jti", OTHER_ID.toString()))) { + assertVerifierDenies(wrongJti); + } + + KeyPairGenerator wrongGenerator = KeyPairGenerator.getInstance("RSA"); + wrongGenerator.initialize(2048); + try (Fixture wrongSignature = fixture(claims -> {}, wrongGenerator.generateKeyPair())) { + assertVerifierDenies(wrongSignature); + } + + try (Fixture valid = fixture(claims -> {}); + var wrongHash = + AccountGameplayAdmissionLeaseGrpcCodec.originalNewCredential( + valid.compactJwt, + HANDLE, + LINEAGE_ID, + BOUND_JTI, + "f".repeat(64), + Long.parseLong(TOKEN_FENCE), + LEASE_ID, + 1L, + "42", + hash( + canonical( + valid.candidate.leaseEvidence().carrier().get("outboxCheckpoints"))))) { + assertThatThrownBy(() -> valid.verifier.verify(valid.candidate, wrongHash)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Original NEW bound credential is invalid"); + } + + try (Fixture wrongFence = fixture(claims -> claims.put("issuanceFence", "8"))) { + assertVerifierDenies(wrongFence); + } + + try (Fixture wrongMembership = + fixture(claims -> claims.put("membershipVersion", Map.of(TENANT_ID.toString(), "10")))) { + assertVerifierDenies(wrongMembership); + } + + try (Fixture wrongTuple = + fixture( + claims -> + claims.put( + "authorityTuple", + Map.of( + "issuerAuthGeneration", + "1", + "accountAuthorityGeneration", + "1", + "tenantAuthorityGeneration", + Map.of(TENANT_ID.toString(), "3"), + "membershipAuthorityGeneration", + Map.of(TENANT_ID.toString(), "3"), + "privateRealmGrantVersions", + List.of())))) { + assertVerifierDenies(wrongTuple); + } + } + + @Test + void strictFinalReaderRejectsUnknownDuplicateTrailingMalformedAndOversizeJson() throws Exception { + try (Fixture fixture = fixture(claims -> {}); + var template = template(fixture)) { + byte[] candidate = template.finalCasTemplateBytes(); + byte[] complete = finalizeTemplate(candidate, CLOCK.millis() + 100L, SESSION_DURATION_MILLIS); + try { + assertDenied(addRootField(complete, "lineageId", "not-persisted")); + String duplicate = + new String(complete, StandardCharsets.UTF_8) + .replaceFirst("\\{", "{\"schemaVersion\":2,"); + assertDenied(duplicate.getBytes(StandardCharsets.UTF_8)); + byte[] trailing = Arrays.copyOf(complete, complete.length + 3); + trailing[complete.length] = ' '; + trailing[complete.length + 1] = '{'; + trailing[complete.length + 2] = '}'; + assertDenied(trailing); + assertDenied(new byte[] {(byte) 0xc3, (byte) 0x28}); + assertDenied( + new byte[CanonicalGameplayOriginalNewAuthenticatedSession.MAX_SESSION_BYTES + 1]); + } finally { + Arrays.fill(candidate, (byte) 0); + Arrays.fill(complete, (byte) 0); + } + } + } + + @Test + void strictFinalReaderRejectsMissingNullPlaceholderAndChangedAnchors() throws Exception { + try (Fixture fixture = fixture(claims -> {}); + var template = template(fixture)) { + byte[] templateBytes = template.finalCasTemplateBytes(); + byte[] complete = + finalizeTemplate(templateBytes, CLOCK.millis() + 100L, SESSION_DURATION_MILLIS); + try { + assertDenied(mutate(complete, root -> root.remove("rebindHandle"))); + assertDenied(mutate(complete, root -> root.putNull("membershipBaseline"))); + assertDenied(mutate(complete, root -> root.put("bindingGeneration", "2"))); + assertDenied(mutate(complete, root -> root.put("schemaVersion", 4294967298L))); + assertDenied(mutate(complete, root -> root.put("issuanceFence", "8"))); + assertDenied(mutate(complete, root -> root.put("tokenGeneration", "2"))); + assertDenied(mutate(complete, root -> root.put("continuityBindingExpiresAt", "1"))); + assertDenied(mutate(complete, root -> root.put("admissionAt", "9223372036854775807"))); + assertDenied( + mutate( + complete, + root -> ((ObjectNode) root.get("originalCandidate")).put("unexpected", "field"))); + assertDenied( + mutate( + complete, + root -> + ((ObjectNode) root.get("membershipBaseline")) + .put("membershipAuthorityGeneration", "8"))); + assertDenied( + mutate( + complete, + root -> + ((ObjectNode) root.get("authorityTuple")) + .put("accountAuthorityGeneration", "2"))); + assertDenied( + mutate( + complete, root -> ((ArrayNode) root.get("outboxCheckpoints")).add("unexpected"))); + } finally { + Arrays.fill(templateBytes, (byte) 0); + Arrays.fill(complete, (byte) 0); + } + } + } + + @Test + void finalCasReadbackAllowsOnlyAdmissionAndContinuityTimeSlotsToChange() throws Exception { + try (Fixture fixture = fixture(claims -> {}); + var template = template(fixture)) { + byte[] templateBytes = template.finalCasTemplateBytes(); + byte[] complete = + finalizeTemplate(templateBytes, CLOCK.millis() + 100L, SESSION_DURATION_MILLIS); + byte[] changed = + mutate( + complete, + root -> { + long admissionAt = Long.parseLong(root.get("admissionAt").textValue()); + root.put("canonicalSessionDurationMillis", "119999"); + root.put("continuityBindingExpiresAt", Long.toString(admissionAt + 119_999L)); + }); + try { + assertThatThrownBy(() -> template.requireFinalizedReadback(changed)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Canonical ORIGINAL_NEW authenticated session is invalid"); + } finally { + Arrays.fill(templateBytes, (byte) 0); + Arrays.fill(complete, (byte) 0); + Arrays.fill(changed, (byte) 0); + } + } + } + + private static void assertVerifierDenies(Fixture fixture) { + assertThatThrownBy(() -> template(fixture)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Original NEW bound credential is invalid"); + } + + private static CanonicalGameplayOriginalNewAuthenticatedSession.Template template( + Fixture fixture) { + return CanonicalGameplayOriginalNewAuthenticatedSession.template( + fixture.candidate, fixture.credential, fixture.verifier, SESSION_DURATION_MILLIS); + } + + private static void assertDenied(byte[] bytes) { + try { + assertThatThrownBy( + () -> CanonicalGameplayOriginalNewAuthenticatedSession.parseFinalized(bytes, CLOCK)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Canonical ORIGINAL_NEW authenticated session is invalid"); + } finally { + Arrays.fill(bytes, (byte) 0); + } + } + + private static byte[] finalizeTemplate(byte[] template, long admissionAt, long duration) + throws Exception { + ObjectNode root = (ObjectNode) JSON.readTree(template); + root.put("admissionAt", Long.toString(admissionAt)); + root.put("continuityBindingExpiresAt", Long.toString(Math.addExact(admissionAt, duration))); + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(root)); + } + + private static byte[] mutate(byte[] input, java.util.function.Consumer mutation) + throws Exception { + ObjectNode root = (ObjectNode) JSON.readTree(input); + mutation.accept(root); + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(root)); + } + + private static byte[] addRootField(byte[] input, String name, String value) throws Exception { + return mutate(input, root -> root.put(name, value)); + } + + private static Fixture fixture(java.util.function.Consumer> mutateClaims) + throws Exception { + return fixture(mutateClaims, ACCOUNT_SIGNING_KEYS); + } + + private static Fixture fixture( + java.util.function.Consumer> mutateClaims, KeyPair signingKey) + throws Exception { + AccountGameplayAdmissionLeaseEvidence lease = lease(); + CanonicalGameplayOriginalNewCandidate candidate = candidate(lease); + Map claims = boundClaims(lease); + mutateClaims.accept(claims); + String compactJwt = sign(claims, signingKey); + String tokenHash = hash(compactJwt); + String checkpointsSha256 = hash(canonical(lease.carrier().get("outboxCheckpoints"))); + AccountGameplayAdmissionLeaseGrpcCodec.OriginalNewCredential credential = + AccountGameplayAdmissionLeaseGrpcCodec.originalNewCredential( + compactJwt, + HANDLE, + LINEAGE_ID, + BOUND_JTI, + tokenHash, + Long.parseLong(TOKEN_FENCE), + LEASE_ID, + 1L, + "42", + checkpointsSha256); + return new Fixture(candidate, credential, compactJwt, verifier()); + } + + private static CanonicalGameplayOriginalNewCandidate candidate( + AccountGameplayAdmissionLeaseEvidence lease) { + CanonicalGameplayBindingIdentity binding = + new CanonicalGameplayBindingIdentity( + ACCOUNT_ID, + TENANT_ID, + PLAYABLE_NAMESPACE_ID, + CHARACTER_ID, + "SHARED", + GAME_INSTANCE_ID, + 77L, + SESSION_ID.toString(), + REGION_ID, + BigInteger.ONE, + GameSessionAccountDelegationProfile.ISSUER, + BigInteger.ONE, + BigInteger.ONE, + BigInteger.ONE, + BigInteger.ONE); + CanonicalPlayableTarget target = + new CanonicalPlayableTarget( + NAMESPACE, + "tenant", + TENANT_ID, + "world", + "World", + REALM_ID, + "realm", + "Realm", + 42L, + 77L, + PLAYABLE_NAMESPACE_ID, + "SHARED", + GAME_INSTANCE_ID, + VERSION_ID, + 3L, + 5L, + 6L, + "a".repeat(64), + 1L, + REQUEST_ID.toString(), + "b".repeat(64), + OriginKind.NO_PRIOR_POINTER, + null, + OTHER_ID, + RESERVATION_FENCE, + "sha256:" + "c".repeat(64), + 100L, + "sha256:" + "d".repeat(64), + Outcome.COMMITTED, + false, + Instant.parse("2026-10-26T00:00:00Z"), + "PRESEEDED_ONLY"); + var bindingRef = binding.bindingRef(); + var transition = + new CanonicalGameplayOriginalNewCandidate.TransitionSource( + BINDING_DECISION_ID, + bindingRef, + BigInteger.ONE, + RESERVATION_ID, + RESERVATION_FENCE, + ACCOUNT_INDEX_FENCE); + var reservation = + new CanonicalGameplayOriginalNewCandidate.ReservationSource( + RESERVATION_ID, + bindingRef, + BigInteger.ONE, + BINDING_DECISION_ID, + BigInteger.ZERO, + RESERVATION_FENCE, + COVERAGE_OPERATION_ID, + BigInteger.ONE, + BigInteger.ONE, + BigInteger.ONE); + return new CanonicalGameplayOriginalNewCandidate( + BINDING_DECISION_ID, lease, binding, target, transition, reservation); + } + + private static AccountGameplayAdmissionLeaseEvidence lease() { + Map value = new LinkedHashMap<>(); + value.put("schema", AccountGameplayAdmissionLeaseEvidence.SCHEMA); + value.put("schemaVersion", "1"); + value.put("mode", "PUBLIC_PRODUCTION"); + value.put("targetNamespace", NAMESPACE); + value.put("callerWorkload", GAME_SESSION_PEER); + value.put("requestId", REQUEST_ID.toString()); + value.put("leaseId", LEASE_ID.toString()); + value.put("leaseFence", ONE); + value.put("leaseKind", "NEW_BINDING"); + Map scope = new LinkedHashMap<>(); + scope.put("accountId", ACCOUNT_ID.toString()); + scope.put("tenantId", TENANT_ID.toString()); + scope.put("realmId", REALM_ID.toString()); + scope.put("worldSlug", "world"); + scope.put("realmSlug", "realm"); + scope.put("playableStateNamespaceId", PLAYABLE_NAMESPACE_ID.toString()); + scope.put("playableStateScope", "SHARED"); + scope.put("gameInstanceId", GAME_INSTANCE_ID.toString()); + scope.put("characterId", CHARACTER_ID.toString()); + scope.put("sessionId", SESSION_ID.toString()); + scope.put("bindingGeneration", ONE); + scope.put("catalogRevision", "5"); + scope.put("pointerVersion", "6"); + scope.put("regionId", REGION_ID.toString()); + scope.put("regionEpoch", ONE); + value.put("bindingScope", scope); + value.put( + "authorityTuple", + Map.of( + "issuerAuthGeneration", ONE, + "accountAuthorityGeneration", ONE, + "tenantAuthorityGeneration", Map.of(TENANT_ID.toString(), "2"), + "membershipAuthorityGeneration", Map.of(TENANT_ID.toString(), "3"), + "privateRealmGrantVersions", List.of())); + value.put("issuanceFence", TOKEN_FENCE); + value.put( + "membershipBaseline", + Map.of( + "membershipLifecycleState", + "ACTIVE", + "membershipVersion", + Map.of(TENANT_ID.toString(), "9"), + "membershipAuthorityGeneration", + "3")); + value.put("outboxCheckpoints", checkpoints()); + value.put( + "tokenIdentityEvidence", + Map.ofEntries( + Map.entry("accountId", ACCOUNT_ID.toString()), + Map.entry("operationId", OTHER_ID.toString()), + Map.entry("issuanceRequestId", REQUEST_ID.toString()), + Map.entry("tokenJti", LOGIN_JTI.toString()), + Map.entry("tokenSHA256", "e".repeat(64)), + Map.entry("tokenGeneration", ONE), + Map.entry("issuanceFence", TOKEN_FENCE), + Map.entry("tokenIdentityFence", ONE), + Map.entry("tokenProfile", GameSessionAccountDelegationProfile.PROFILE), + Map.entry("issuedAt", Long.toString(NOW_SECONDS - 1)), + Map.entry("notBefore", Long.toString(NOW_SECONDS - 1)), + Map.entry("expiresAt", Long.toString(NOW_SECONDS + 299)))); + value.put("evaluatedAt", Long.toString(CLOCK.millis())); + value.put("expiresAt", Long.toString(CLOCK.millis() + 15_000L)); + return AccountGameplayAdmissionLeaseEvidence.fromCarrier(value); + } + + private static List> checkpoints() { + List> result = new ArrayList<>(); + for (String suffix : + List.of( + "account/" + ACCOUNT_ID, + "issuer/" + GameSessionAccountDelegationProfile.ISSUER, + "membership/" + ACCOUNT_ID + "/" + TENANT_ID, + "tenant/" + TENANT_ID)) { + result.add( + Map.of( + "outboxStreamKey", + "account:auth-authority:v1:" + suffix, + "outboxSequence", + suffix.startsWith("membership/") || suffix.startsWith("tenant/") ? "9" : "0")); + } + return List.copyOf(result); + } + + private static Map boundClaims(AccountGameplayAdmissionLeaseEvidence lease) { + Map claims = new LinkedHashMap<>(); + claims.put("iss", GameSessionAccountDelegationProfile.ISSUER); + claims.put("sub", ACCOUNT_ID.toString()); + claims.put("jti", BOUND_JTI.toString()); + claims.put("accountId", ACCOUNT_ID.toString()); + claims.put("aud", GameSessionAccountDelegationProfile.AUDIENCE); + claims.put("iat", NOW_SECONDS); + claims.put("nbf", NOW_SECONDS); + claims.put("exp", NOW_SECONDS + 240L); + claims.put("tokenGeneration", ONE); + claims.put("authorityTuple", lease.carrier().get("authorityTuple")); + claims.put( + "membershipVersion", + ((Map) lease.carrier().get("membershipBaseline")).get("membershipVersion")); + claims.put("issuanceFence", TOKEN_FENCE); + claims.put("tenantId", TENANT_ID.toString()); + return claims; + } + + private static Map unscopedTuple() { + return Map.of( + "issuerAuthGeneration", ONE, + "accountAuthorityGeneration", ONE, + "tenantAuthorityGeneration", Map.of(), + "membershipAuthorityGeneration", Map.of(), + "privateRealmGrantVersions", List.of()); + } + + private static String sign(Map claims, KeyPair keyPair) throws Exception { + String header = + Base64.getUrlEncoder() + .withoutPadding() + .encodeToString( + "{\"alg\":\"RS256\",\"kid\":\"original-new-test\",\"typ\":\"JWT\"}" + .getBytes(StandardCharsets.UTF_8)); + String payload = + Base64.getUrlEncoder().withoutPadding().encodeToString(JSON.writeValueAsBytes(claims)); + String signingInput = header + "." + payload; + Signature signer = Signature.getInstance("SHA256withRSA"); + signer.initSign(keyPair.getPrivate()); + signer.update(signingInput.getBytes(StandardCharsets.US_ASCII)); + return signingInput + + "." + + Base64.getUrlEncoder().withoutPadding().encodeToString(signer.sign()); + } + + private static CanonicalGameplayOriginalNewBoundCredentialVerifier verifier() throws Exception { + var pin = + new AccountPublicJwksCache.SourceIdentity( + "test", + "cluster-a", + "11111111-1111-4111-8111-111111111111", + "test", + "22222222-2222-4222-8222-222222222222", + "33333333-3333-4333-8333-333333333333", + "binding-7", + "https://kubernetes.example:6443", + "a".repeat(64)); + var publicKey = (java.security.interfaces.RSAPublicKey) ACCOUNT_SIGNING_KEYS.getPublic(); + String jwks = + JSON.writeValueAsString( + Map.of( + "keys", + List.of( + Map.of( + "kty", + "RSA", + "use", + "sig", + "alg", + "RS256", + "kid", + "original-new-test", + "n", + Base64.getUrlEncoder() + .withoutPadding() + .encodeToString(unsigned(publicKey.getModulus().toByteArray())), + "e", + Base64.getUrlEncoder() + .withoutPadding() + .encodeToString( + unsigned(publicKey.getPublicExponent().toByteArray())))))); + var cache = + new AccountPublicJwksCache( + () -> + new AccountPublicJwksCache.PublicJwksSnapshot( + pin, jwks.getBytes(StandardCharsets.UTF_8)), + pin, + CLOCK, + Duration.ofSeconds(30)); + return new CanonicalGameplayOriginalNewBoundCredentialVerifier(cache, CLOCK); + } + + private static String canonical(Object value) throws Exception { + return new String( + Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)), + StandardCharsets.UTF_8); + } + + private static String hash(String value) throws Exception { + return hash(value.getBytes(StandardCharsets.US_ASCII)); + } + + private static String hash(byte[] value) throws Exception { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value)); + } + + private static byte[] unsigned(byte[] bytes) { + return bytes.length > 1 && bytes[0] == 0 ? Arrays.copyOfRange(bytes, 1, bytes.length) : bytes; + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } + + private static final class Fixture implements AutoCloseable { + private final CanonicalGameplayOriginalNewCandidate candidate; + private final AccountGameplayAdmissionLeaseGrpcCodec.OriginalNewCredential credential; + private final String compactJwt; + private final CanonicalGameplayOriginalNewBoundCredentialVerifier verifier; + + private Fixture( + CanonicalGameplayOriginalNewCandidate candidate, + AccountGameplayAdmissionLeaseGrpcCodec.OriginalNewCredential credential, + String compactJwt, + CanonicalGameplayOriginalNewBoundCredentialVerifier verifier) { + this.candidate = candidate; + this.credential = credential; + this.compactJwt = compactJwt; + this.verifier = verifier; + } + + @Override + public void close() { + credential.close(); + } + } +} From 19cfad4bcdaa10b9bf39d5838e12490f1e7f1635 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 27 Oct 2026 13:04:41 +1300 Subject: [PATCH 06/26] Allocate Account NEW migrations above the receiving parent frontier --- .../microservices/account-service/runtime-and-data.md | 2 +- design/project-management/ai-observations.md | 5 +++++ .../implementation-tracking/player-access-and-session.md | 4 ++-- ...12__account_original_new_bound_gameplay_credentials.sql} | 0 ...1013__account_original_ack_pg18_historical_recovery.sql} | 0 ...playAdmissionProtectedEntryPrototypeIntegrationTest.java | 6 +++--- 6 files changed, 11 insertions(+), 6 deletions(-) rename services/account-service/src/main/resources/db/migration/{V161__account_original_new_bound_gameplay_credentials.sql => V1012__account_original_new_bound_gameplay_credentials.sql} (100%) rename services/account-service/src/main/resources/db/migration/{V162__account_original_ack_pg18_historical_recovery.sql => V1013__account_original_ack_pg18_historical_recovery.sql} (100%) diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index 25bd8a75d5..79559fb8ac 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -18,7 +18,7 @@ The manually composed admission acquisition owner reads the retained original Ac Account has an unregistered initial private gameplay LOGIN source slice for request-bound credential digests, signer and JWKS trust, pending and committed registry ownership, authority projection reads, and encrypted response recovery. Before its final Account transaction, the commit source publishes the current issuer and Account projections and requires an exact matching observation; publication or observation failure denies the commit. Caller currentness and response recovery may use an older committed signer generation only while the exact original public-key fingerprint remains in the current trusted JWKS and current owner evidence, including the original issuance JTI, still matches; the applicable authority, API, source, expiry, and compromise fences remain required. The source fixes the explicitly approved `game-session-account-delegation` profile and has no caller-selected profile or property bypass. It adds no endpoint or runtime registration; deployed ACL/TLS, signer-key custody, caller authentication, consumer authorization, gameplay admission, and runtime activation remain unproved. See the [Player Access and Session tracker](../../../project-management/implementation-tracking/player-access-and-session.md#initial-private-gameplay-login-issuance-source-intake) for exact unit and physical fixture proof scope. -Account's unregistered original-ACK owner preserves the original physical COMMIT and its separately committed receipt. Forward V162 extends historical receipt recovery to PostgreSQL 18 while retaining V144/V146 and the original evidence. The private owner captures one fixed snapshot and WAL fence, releases its SQL locks, positively observes coverage of that unchanged fence, and independently compares the exact receipt. Focused PostgreSQL 18 proof covers this recovery boundary. This source remains unregistered and supplies no caller authentication or gameplay admission. Migration provenance, proof and remaining gaps belong to the [Player Access and Session tracker](../../../project-management/implementation-tracking/player-access-and-session.md#account-fresh-original-ack-storage-preparation). +Account's unregistered original-ACK owner preserves the original physical COMMIT and its separately committed receipt. Forward V1013 extends historical receipt recovery to PostgreSQL 18 while retaining V144/V146 and the original evidence. The private owner captures one fixed snapshot and WAL fence, releases its SQL locks, positively observes coverage of that unchanged fence, and independently compares the exact receipt. Focused PostgreSQL 18 proof covers this recovery boundary. This source remains unregistered and supplies no caller authentication or gameplay admission. Migration provenance, proof and remaining gaps belong to the [Player Access and Session tracker](../../../project-management/implementation-tracking/player-access-and-session.md#account-fresh-original-ack-storage-preparation). Account V40 adds owner-proven sequence-zero source baselines to the inherited V30–V39 authority-storage and retention-safety foundation; V74–V89 preserve that baseline and add source/global-role guards, draft-source writer exclusions and fences, immutable reset/logout/security-operation receipts, creator and tenant-bootstrap provenance, individual Creator Party and hosted-terms/environment-binding persistence, and source-change journals. V90–V97 add persistence relations and guards for source-currentness work across Account, control-UI issuance, selected-publication authorization/settlement, and Game Logic. V98 adds durable hosted-terms disclosure handoff and immutable source-evidence relations with database transition guards. These DDL stages establish persistence and source-writer fence relationships; they do not activate owner writers, legal authority verification, dispatch, or consumers. New repository-created Accounts receive the V40 source baseline; retained pre-V40 rows are neither backfilled nor admitted. Password-reset completion atomically claims and consumes its token, updates the Account, appends the canonical event and receipt, and reads back current source evidence in the owner transaction. If an earlier source intent remains `WAITING`, the request returns retryable `AUTH_UNAVAILABLE`; it does not wait on a thread for settlement, and an exact retry retains the original operation identity. A `WAITING` reset intent retains the Argon2 password verifier needed by that retry; terminal source commit or abort clears the verifier while preserving its digest and immutable source binding and receipt. Finite receipt retention remains unresolved under the owning retention policy; no lifetime is selected here. Logout-all production remains unregistered and unwired. These persistence primitives do not provide public JOIN, target-currentness protection, or runtime activation. Exact physical and local proof limits are recorded in 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. diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index f6a465620f..10c46d7e99 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -463,3 +463,8 @@ Entry format: - Context: #2972 R763 passed 23 of 25 native cases; actual bound issuance and a populated historical receipt upgrade refused durability because the captured global insert position remained 56 bytes beyond flush. The exact record type is unknown. - Observation: PostgreSQL background WAL flushing considers full pages and asynchronous transaction work; an unrelated partial-page tail need not advance during a bounded read. Raising a polling count or lowering the proof fence would not establish the required durability. - Qualified recovery: retain the SQL-issued snapshot and exact upper fence in a private pending capability, finish its capture transaction, then explicitly observe flush coverage of that same fence outside SQL locks and independently compare the original immutable receipt. No reader COMMIT authenticates the original clock, and no marker, forced flush or replacement timing is introduced. R766 passes all 26 selected PostgreSQL/Redis cases, including quiet-server frozen-fence coverage, unchanged retained migration rows and lost-confirmation recovery; the previous failed aggregates remain recorded. + +- `2026-10-27`: Apply the existing Flyway frontier check before publishing receiving migrations + - Context: #3320 CI job `121922001160` rejected new Account V161/V162 below the effective parent frontier V1011. The prior 2026-10-15 observation already described this service/shared-history ordering risk; the local receiving checks omitted `checkFlywayVersions` against the exact PR parent. + - Consequence and correction: fresh-schema tests passed while the proposed migration order was unsuitable for an existing parent deployment. Move only these new, unapplied migrations to V1012/V1013, preserve all parent migration names/checksums, and prove populated upgrade plus the canonical frontier check against the published parent. No out-of-order execution or host change is authorized. + - Outcome: R768 passes the actual-parent frontier guard, jOOQ generation and all 26 selected PostgreSQL/Redis cases with the V1012→V1013 upgrade; integration static/format and documentation checks pass, and all five observed containers are independently absent. Replacement hosted CI is still required. 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 be878b746b..4f482f1c77 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -8,7 +8,7 @@ This is a non-normative implementation tracker for player access and session. Ca ### Canonical NEW admission components -The receiving #2972 boundary adds unregistered issuer LIVE/tenant OPEN and Account INITIAL OPEN owners, exact nonadmitting original-NEW candidate installation, and Account-owned generation-1 bound credential/opaque-handle issuance with a strict immediate session consumer. It remains a preparation boundary: the concrete final controller CAS, committed Game Session result reader and whole-flow coordinator are not supplied by this publication. Account final confirmation fails closed without its authenticated final-read dependency. R765 passes all 49 selected receipt/owner unit cases, production and unit static checks, formatting and documentation checks. R766 passes all 26 selected PostgreSQL/Redis cases and integration static/format checks, including genuine original COMMIT and independent receipt recovery, populated V161→V162 retention, same-transaction and stale-snapshot refusal, and actual bound issuance with unchanged replay. Its owned SQL fault occurs after real Redis activation; unavailable or changed controlled Game Session final reads leave SQL unconfirmed, and a fresh exact read confirms the same credential and expiry. The Game Session final-read callback and signer custody remain controlled inputs. Source hashes match the passing native scope and all five observed containers are independently absent. Earlier failed aggregates remain failed. These results do not establish the complete Game Session final-CAS flow, production custody, default registration or activation. +The receiving #2972 boundary adds unregistered issuer LIVE/tenant OPEN and Account INITIAL OPEN owners, exact nonadmitting original-NEW candidate installation, and Account-owned generation-1 bound credential/opaque-handle issuance with a strict immediate session consumer. It remains a preparation boundary: the concrete final controller CAS, committed Game Session result reader and whole-flow coordinator are not supplied by this publication. Account final confirmation fails closed without its authenticated final-read dependency. R765 passes all 49 selected receipt/owner unit cases, production and unit static checks, formatting and documentation checks. R768 passes all 26 selected PostgreSQL/Redis cases and integration static/format checks, including genuine original COMMIT and independent receipt recovery, populated V1012→V1013 retention, same-transaction and stale-snapshot refusal, and actual bound issuance with unchanged replay. Its owned SQL fault occurs after real Redis activation; unavailable or changed controlled Game Session final reads leave SQL unconfirmed, and a fresh exact read confirms the same credential and expiry. The Game Session final-read callback and signer custody remain controlled inputs. Source hashes match the passing native scope and all five observed containers are independently absent. Earlier failed aggregates remain failed. These results do not establish the complete Game Session final-CAS flow, production custody, default registration or activation. The Account gameplay-admission lease and the unregistered Game Session receiver remain separate authority boundaries. The unregistered Account verifier uses the pinned trusted JWKS and fixed gameplay-delegation profile, selects the current `COMMITTED`/`ACTIVE` issuance by verified JTI, and compares the full immutable token identity, hash and authority; it retains no presented JWT and makes no membership, entitlement or lease decision. Focused acquisition proof joins the exact recovered JWT to actual current issuance, physical Coordination Redis and the same-connection Account source graph, preserving the original pending lease on retry. R494 freshly passes 104 Account unit cases and eight selected PostgreSQL/Redis cases, with affected static analysis and formatting. Its manual TLS receiver exercises all four generated RPCs with the exact recovered Account JWT and current issuance/registry and SQL sources, then performs PostgreSQL 18 physical COMMIT and independent durable original-ACK insertion/readback. The original lease attempt and ACK are immutable. The original physical-commit executor retains focused PostgreSQL component proof, and the Game Session lease client has controlled mTLS proof; that earlier proof retained the PostgreSQL 18 historical-reader denial. The receiving V162 qualification below extends that owner without changing the original evidence. The reverse Game Session target/decision response and protected signer/materializer evidence remain controlled. Exact metadata and cleanup-obligation recovery revalidate the current caller/global Account/token under Account-first SQL locks without requiring a superseded tenant admission baseline; new acquisition and first finalization retain full tenant-source checks. These results do not prove genuine Game Session authority, cleanup delivery, final controller admission, production custody or activation. Token-retirement, orphan-cleanup delivery and admitted binding remain open. @@ -278,7 +278,7 @@ This preparation is owned by AA-1.3 in [Capability Status](#capability-status), The receiving Account cut imports the preserved original-ACK storage preparation from `codex/gameplay-game-design-publication-storage-foundation-20261009` at `d66d36951d3df780641e0ef04819f15df52ddc39` plus its uncommitted PostgreSQL 18 fresh-path changes. Only the receiving migration filenames are allocated anew: V140 ← source V118 (lease operations), V141 ← V119 (unknown-decision abort), V142 ← V120 (original-finalization stamp and experimental confirmation storage), V143 ← V121 (global pending fences), V144 ← V122 (original-ACK receipt), V145 ← V136 (experimental confirmation write retirement), and V146 ← V139 (PostgreSQL 18 fresh-insert guard). Their SQL bytes, including historical version comments, are preserved. Source V122 retains SHA-256 `c4f66ce16c77514717cbc9d2e0d65bc8c8ee0882239371d8518f587a0ef53490`, matching the historical `2cb445617f584d25c805f5c08e9dde67fff4efc4` migration; no donor renumbering or external migration application is performed. -The unregistered executors and receipt repository preserve the exact original operation, source identity, finalization XID, unchanged expiry and original clock bound. Fresh original and independent receipt COMMITs remain PostgreSQL 18-only. A retained COMMITTED retry cannot mint another original acknowledgement. Forward V162 extends the existing historical reader to PostgreSQL 18 as well as its previously supported PostgreSQL 16, retaining the fixed snapshot, WAL upper fence, independently committed receipt, Account-first row locks and bounded flush-coverage observation. It never writes a marker, forces a flush or restamps timing. R766 freshly passes the 25-case PostgreSQL prototype: the populated V161→V162 case retains pre-upgrade PostgreSQL 18 denial and proves unchanged operation/receipt row images and `xmin`; restarted-owner and lost-receipt-acknowledgement recovery preserve original timing. The private pending capture is not durability proof. The executor positively observes actual flush coverage of its exact frozen fence after the capture transaction releases its locks, then independently compares the entire receipt. R763 exposed the strict in-transaction reader’s quiet-server WAL-tail liveness limit; its two failures remain recorded. Unit coverage includes unavailable flush observations and changed readback, while a deterministic physical WAL-unavailable case remains unqualified. PostgreSQL 16 and other server majors have not been rerun in this receiving scope. This is storage recovery, with no renewal of admission authority or production registration. +The unregistered executors and receipt repository preserve the exact original operation, source identity, finalization XID, unchanged expiry and original clock bound. Fresh original and independent receipt COMMITs remain PostgreSQL 18-only. A retained COMMITTED retry cannot mint another original acknowledgement. Forward V1013 extends the existing historical reader to PostgreSQL 18 as well as its previously supported PostgreSQL 16, retaining the fixed snapshot, WAL upper fence, independently committed receipt, Account-first row locks and bounded flush-coverage observation. It never writes a marker, forces a flush or restamps timing. R768 freshly passes the 25-case PostgreSQL prototype: the populated V1012→V1013 case retains pre-upgrade PostgreSQL 18 denial and proves unchanged operation/receipt row images and `xmin`; restarted-owner and lost-receipt-acknowledgement recovery preserve original timing. The private pending capture is not durability proof. The executor positively observes actual flush coverage of its exact frozen fence after the capture transaction releases its locks, then independently compares the entire receipt. R763 exposed the strict in-transaction reader’s quiet-server WAL-tail liveness limit; its two failures remain recorded. Unit coverage includes unavailable flush observations and changed readback, while a deterministic physical WAL-unavailable case remains unqualified. PostgreSQL 16 and other server majors have not been rerun in this receiving scope. This is storage recovery, with no renewal of admission authority or production registration. ### Restricted original-claim evidence continuation preparation diff --git a/services/account-service/src/main/resources/db/migration/V161__account_original_new_bound_gameplay_credentials.sql b/services/account-service/src/main/resources/db/migration/V1012__account_original_new_bound_gameplay_credentials.sql similarity index 100% rename from services/account-service/src/main/resources/db/migration/V161__account_original_new_bound_gameplay_credentials.sql rename to services/account-service/src/main/resources/db/migration/V1012__account_original_new_bound_gameplay_credentials.sql diff --git a/services/account-service/src/main/resources/db/migration/V162__account_original_ack_pg18_historical_recovery.sql b/services/account-service/src/main/resources/db/migration/V1013__account_original_ack_pg18_historical_recovery.sql similarity index 100% rename from services/account-service/src/main/resources/db/migration/V162__account_original_ack_pg18_historical_recovery.sql rename to services/account-service/src/main/resources/db/migration/V1013__account_original_ack_pg18_historical_recovery.sql diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java index d8a54ecc18..e3f51576fb 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java @@ -471,8 +471,8 @@ void historicalRecoveryCannotSeeReceiptCommittedAfterItsFixedSnapshot() throws E } @Test - void v162QualifiesRetainedPg18ReceiptWithoutChangingHistoricalStorage() { - var context = context("161"); + void v1013QualifiesRetainedPg18ReceiptWithoutChangingHistoricalStorage() { + var context = context("1012"); var ack = finalized(context, 15000); var expected = new AccountGameplayAdmissionOriginalAckReceiptCommitExecutor(context.admin()).confirm(ack); @@ -492,7 +492,7 @@ void v162QualifiesRetainedPg18ReceiptWithoutChangingHistoricalStorage() { .defaultSchema(context.schema()) .placeholders(Map.of("serviceSchema", context.schema())) .locations("classpath:db/migration") - .target("162") + .target("1013") .load() .migrate(); assertThat( From 6f2c4c3a82e133deaa3d9fee5ff8df410b8ed580 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 27 Oct 2026 13:39:08 +1300 Subject: [PATCH 07/26] Preserve retained credentials and frozen cutoff cleanup progress --- .../AccountGameplayDelegationSigner.java | 7 +- .../AccountGameplayDelegationSignerTest.java | 43 +++++ ...meplayAccountInitialBarrierRedisOwner.java | 17 +- ...eplayIssuerAdmissionBarrierRepository.java | 4 +- ...eplayIssuerAdmissionControlRepository.java | 34 ++-- ...meplayOriginalNewAuthenticatedSession.java | 12 +- ...lGameplayProtectedIncarnationReceiver.java | 1 - ...ssionBarrierRepositoryIntegrationTest.java | 148 ++++++++++++++++-- ...nationReceiverPostgresIntegrationTest.java | 4 +- 9 files changed, 226 insertions(+), 44 deletions(-) diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationSigner.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationSigner.java index 1150798d8f..fd57932553 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationSigner.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationSigner.java @@ -475,11 +475,10 @@ public VerifiedOriginalNewBoundCredential verifyOriginalNewBoundCredential( byte[] finalJwks = null; try { CurrentSigner initial = accountTransaction.execute(status -> currentCommittedSigner()); - if (initial == null - || !genesis.accountId().equals(accountAuthority.accountId()) - || !genesis.signerKid().equals(initial.expectedIdentity().kid()) - || !genesis.signerGeneration().equals(initial.expectedIdentity().generation())) + if (initial == null || !genesis.accountId().equals(accountAuthority.accountId())) throw unavailable(); + // Recovery verifies the frozen JWT's original key against today's trusted JWKS. + // A completed rotation can retain that key without making it the active signer. SourceIdentity pin = trustedJwksSource.sourceIdentity(); initialJwks = requireExactTrustedSnapshot(initial, pin, trustedJwksSource.load()); byte[] pinned = initialJwks; diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationSignerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationSignerTest.java index fa42afe6de..44674f3587 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationSignerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationSignerTest.java @@ -271,6 +271,49 @@ void originalNewCredentialUsesBoundClaimsWhileLoginRetainsItsUnscopedShape() thr .validateClaims(castClaims(boundClaims)); assertThat(result.toString()) .doesNotContain(new String(boundJwt.get(), StandardCharsets.US_ASCII)); + var genesis = + mock( + net.firedevops.firemud.accountservice.repository + .AccountOriginalNewBoundGameplayIssuanceRepository.Genesis.class); + when(genesis.accountId()).thenReturn(ACCOUNT_ID); + when(genesis.lineageId()).thenReturn(lineageId); + when(genesis.tokenJti()).thenReturn(boundJti); + when(genesis.tokenHash()).thenReturn(result.compactTokenSha256()); + when(genesis.signerKid()).thenReturn(result.kid()); + when(genesis.signerGeneration()).thenReturn(result.signerGeneration()); + when(genesis.issuedAtEpochSecond()).thenReturn(NOW.getEpochSecond()); + when(genesis.notBeforeEpochSecond()).thenReturn(NOW.getEpochSecond()); + when(genesis.expiresAtEpochSecond()).thenReturn(NOW.plusSeconds(120).getEpochSecond()); + when(genesis.issuanceFence()).thenReturn(fixture.authoritySnapshot.issuanceFence()); + String savedBoundJwt = new String(boundJwt.get(), StandardCharsets.US_ASCII); + fixture.replaceCommittedEvidence(ownerEvidence(mismatchedPair, "43", "account-key-43")); + fixture.sourceJwks.set( + jwksJson(signerPair, KID, mismatchedPair, "account-key-43") + .getBytes(StandardCharsets.UTF_8)); + Files.writeString(fixture.privateRoot.resolve("current.key"), "unavailable private material"); + var recovered = + fixture.signer.verifyOriginalNewBoundCredential( + savedBoundJwt, + genesis, + fixture.authoritySnapshot, + tenantId.toString(), + tuple, + Map.of(tenantId.toString(), "8")); + assertThat(recovered.tokenSha256()).isEqualTo(result.compactTokenSha256()); + assertThat(recovered.lineageId()).isEqualTo(lineageId); + assertThat(recovered.tokenJti()).isEqualTo(boundJti); + fixture.sourceJwks.set( + jwksJson(mismatchedPair, "account-key-43").getBytes(StandardCharsets.UTF_8)); + assertThrows( + AccountGameplayDelegationSigner.SigningUnavailableException.class, + () -> + fixture.signer.verifyOriginalNewBoundCredential( + savedBoundJwt, + genesis, + fixture.authoritySnapshot, + tenantId.toString(), + tuple, + Map.of(tenantId.toString(), "8"))); Arrays.fill(loginJwt.get(), (byte) 0); Arrays.fill(boundJwt.get(), (byte) 0); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierRedisOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierRedisOwner.java index 691c0fb6f3..91d57d5521 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierRedisOwner.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierRedisOwner.java @@ -259,15 +259,14 @@ private void tryCreateOnce( requireNoAmbientTransaction(); RedisScriptDescriptor descriptor = requireDescriptor(); byte[] script = scriptSource(descriptor); - CanonicalGameplayAccountInitialBarrierValue value = - CanonicalGameplayAccountInitialBarrierValue.open( - snapshot.accountId(), - snapshot.tenantId(), - snapshot.playableStateNamespaceId(), - assignment.tenantGameplayTag(), - snapshot.initializerId(), - snapshot.sourceControlEpoch(), - before.incarnationDigest()); + CanonicalGameplayAccountInitialBarrierValue.open( + snapshot.accountId(), + snapshot.tenantId(), + snapshot.playableStateNamespaceId(), + assignment.tenantGameplayTag(), + snapshot.initializerId(), + snapshot.sourceControlEpoch(), + before.incarnationDigest()); String key = CanonicalGameplayAccountInitialBarrierKey.forTarget( assignment, snapshot.initializerId(), snapshot.originalRequestId()); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepository.java index 35c69a26d0..ed91c70ae9 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepository.java @@ -369,7 +369,7 @@ public void recordOpenReadback( CanonicalGameplayIssuerAdmissionControlRepository.requireOpenInTransaction( transaction, anchor, current); Record initializer = - transaction.fetchOne( + transaction.fetchSingle( "SELECT * FROM " + INITIALIZER + " WHERE operation_id = ? AND issuer_id = ? FOR UPDATE", @@ -795,7 +795,7 @@ private boolean claimFirstCreatePermit( "Original initializer no longer belongs to the current OPEN live control"); } Record saved = - transaction.fetchOne( + transaction.fetchSingle( "SELECT * FROM " + INITIALIZER + " WHERE operation_id = ? AND issuer_id = ? FOR UPDATE", diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionControlRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionControlRepository.java index 809f0ac613..c6410fbccf 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionControlRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionControlRepository.java @@ -125,7 +125,6 @@ CanonicalGameplayIssuerAdmissionControlValue beginCutoff( || !"CUTOFF_PENDING".equals(text(priorOperation, "operation_state"))) { throw conflict("Issuer cutoff retry differs from its exact pending operation"); } - verifyFrozenCohort(transaction, control); verifyCutoffTargets(transaction, control); return control; } @@ -170,7 +169,6 @@ CanonicalGameplayIssuerAdmissionControlValue beginCutoff( updateControl(transaction, pending, control.liveBarrierEpoch()); insertCohortRows(transaction, pending.currentOperationId(), rows); insertCutoffTargets(transaction, pending, targets, tagByTarget); - verifyFrozenCohort(transaction, pending); verifyCutoffTargets(transaction, pending); return pending; }); @@ -206,14 +204,12 @@ CanonicalGameplayIssuerAdmissionControlValue completeCutoff( && control.state() == CanonicalGameplayIssuerAdmissionControlValue.State.INSTALLED) { requireCutoffOperationCurrent(transaction, control); - verifyFrozenCohort(transaction, control); verifyCutoffTargets(transaction, control); return control; } throw conflict("The exact current cutoff is not pending completion"); } requireCutoffOperationCurrent(transaction, control); - verifyFrozenCohort(transaction, control); verifyCutoffTargets(transaction, control); Record remaining = transaction.fetchOne( @@ -272,7 +268,6 @@ void verifyCurrentCutoffTarget( throw conflict("A CLOSED target requires the current pending issuer cutoff"); } requireCutoffOperationCurrent(transaction, control); - verifyFrozenCohort(transaction, control); verifyCutoffTargets(transaction, control); Record target = transaction.fetchOne( @@ -616,14 +611,30 @@ private static void insertCutoffTargets( } } - private static void verifyFrozenCohort( + private static List verifyFrozenCohort( DSLContext transaction, CanonicalGameplayIssuerAdmissionControlValue control) { + // Terminal cleanup may advance live source revisions after intent. Resolve every target only + // from the original retained JSON and its retained transition/reservation dependencies. List rows = transaction .fetch( - "SELECT * FROM " + "WITH frozen AS (SELECT *, source_row_json::jsonb AS source FROM " + COHORT - + " WHERE operation_id = ? AND issuer_id = ? ORDER BY row_ordinal", + + " WHERE operation_id = ? AND issuer_id = ?)" + + " SELECT c.*, (scope.source ->> 'tenant_id')::uuid AS tenant_id," + + " (scope.source ->> 'playable_state_namespace_id')::uuid" + + " AS playable_state_namespace_id FROM frozen c" + + " LEFT JOIN frozen transition ON transition.source_kind = 'TRANSITION'" + + " AND transition.source_key = c.source ->> 'transition_id'" + + " LEFT JOIN frozen reservation ON reservation.source_kind = 'RESERVATION'" + + " AND reservation.source_key = c.source ->> 'reservation_id'" + + " CROSS JOIN LATERAL (SELECT CASE" + + " WHEN c.source_kind IN ('BINDING', 'TRANSITION', 'RESERVATION'," + + " 'PENDING_INITIALIZER') THEN c.source" + + " WHEN c.source_kind IN ('ACCOUNT_OBLIGATION', 'ISSUER_OBLIGATION'," + + " 'REGION_OBLIGATION', 'LOCAL_OPERATION') THEN transition.source" + + " WHEN c.source_kind = 'BOOTSTRAP_MEMBER_OPERATION' THEN reservation.source" + + " END AS source) scope ORDER BY c.row_ordinal", control.currentOperationId(), ISSUER) .map( @@ -641,8 +652,8 @@ private static void verifyFrozenCohort( text(row, "source_key"), integer(row, "source_inventory_revision"), json, - null, - null, + uuid(row, "tenant_id"), + uuid(row, "playable_state_namespace_id"), null, storedDigest); }); @@ -667,6 +678,7 @@ private static void verifyFrozenCohort( || !digestCohort(rows).equals(control.cohortDigest())) { throw conflict("Issuer cutoff cohort no longer matches its frozen complete digest"); } + return rows; } private static String requireCurrentTenantTagMapping(DSLContext transaction, UUID tenantId) { @@ -698,7 +710,7 @@ private static void verifyCutoffTargets( control.currentOperationId(), ISSUER); Map> cohortTargets = - groupTargets(captureCutoffCohort(transaction, control.inventorySnapshotRevision())); + groupTargets(verifyFrozenCohort(transaction, control)); if (rows.size() != cohortTargets.size()) { throw conflict("Issuer cutoff target set differs from its complete frozen cohort"); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewAuthenticatedSession.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewAuthenticatedSession.java index 931c526903..84b3bfda37 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewAuthenticatedSession.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewAuthenticatedSession.java @@ -164,7 +164,7 @@ public static Finalized parseFinalized(byte[] encoded, Clock clock) { long continuityExpiresAtMillis = positiveDecimal(continuityExpires); long tokenIssuedAtSeconds = positiveDecimal(issuedAt); long tokenExpiresAtSeconds = positiveDecimal(expiresAt); - long issuanceFenceValue = positiveDecimal(issuanceFence); + positiveDecimal(issuanceFence); long durationMillis = positiveDecimal(duration); requireCanonicalDuration(durationMillis); if (!"1".equals(tokenGeneration)) throw invalid(); @@ -202,7 +202,7 @@ public static Finalized parseFinalized(byte[] encoded, Clock clock) { handle); } catch (RuntimeException rejected) { throw invalid(); - } catch (Exception malformed) { + } catch (IOException malformed) { throw invalid(); } finally { wipe(handle); @@ -242,7 +242,7 @@ private static byte[] makeTemplate( root.set("outboxCheckpoints", JSON.valueToTree(lease.get("outboxCheckpoints"))); root.put("canonicalSessionDurationMillis", Long.toString(canonicalSessionDurationMillis)); return canonicalNode(root); - } catch (Exception malformed) { + } catch (IOException | RuntimeException malformed) { throw invalid(); } finally { wipe(handle); @@ -265,7 +265,7 @@ private static void requireTemplateOnlyHasTimePlaceholders(byte[] templateBytes) if (containsPlaceholder(value)) throw invalid(); } }); - } catch (Exception malformed) { + } catch (IOException | RuntimeException malformed) { throw invalid(); } } @@ -306,7 +306,7 @@ private static void requireBindingAnchors( ObjectNode root, CanonicalGameplayOriginalNewCandidate candidate, AccountGameplayAdmissionLeaseEvidence lease) - throws Exception { + throws IOException { if (!candidate .transition() .bindingGeneration() @@ -318,7 +318,7 @@ private static void requireBindingAnchors( requireCanonicalEqual(root.get("outboxCheckpoints"), carrier.get("outboxCheckpoints")); } - private static void requireCanonicalEqual(JsonNode node, Object source) throws Exception { + private static void requireCanonicalEqual(JsonNode node, Object source) throws IOException { byte[] left = canonicalNode(node); byte[] right = Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(source)); try { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayProtectedIncarnationReceiver.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayProtectedIncarnationReceiver.java index d8bc245f03..7c99ac70b7 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayProtectedIncarnationReceiver.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayProtectedIncarnationReceiver.java @@ -986,7 +986,6 @@ record CurrentContext( } else { Objects.requireNonNull(originalCallerContextId, "originalCallerContextId"); Objects.requireNonNull(sourceControlState, "sourceControlState"); - Objects.requireNonNull(sourceControlEpoch, "sourceControlEpoch"); Objects.requireNonNull(accountLoginEvidenceDigest, "accountLoginEvidenceDigest"); Objects.requireNonNull(sourceControlDigest, "sourceControlDigest"); if (originalAttemptFence <= 0L diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepositoryIntegrationTest.java index b4445c546c..25920a0a9f 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepositoryIntegrationTest.java @@ -39,6 +39,8 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.testcontainers.containers.GenericContainer; import org.testcontainers.containers.PostgreSQLContainer; @@ -387,7 +389,7 @@ void cutoffClosesAnAbortedOriginTargetAndRetainsItsFrozenInitializer() { state .fixture() .dsl() - .fetchOne( + .fetchSingle( "SELECT status FROM game_session_canonical_binding_transition" + " WHERE transition_id = ?", state.fixture().transitionId()) @@ -437,6 +439,137 @@ void cutoffClosesAnAbortedOriginTargetAndRetainsItsFrozenInitializer() { .containsExactly(closed.exactPhysicalPayload()); } + @Test + void cutoffCompletesFromFrozenSourcesAfterTheProvisionalOriginAborts() { + FixtureState state = fixtureState(); + var opened = state.owner().initializeAndRead(state.fixture().originalOperationId()); + UUID cutoffOperationId = UUID.randomUUID(); + UUID requestId = UUID.randomUUID(); + var pending = state.repository().beginCutoff(cutoffOperationId, requestId); + var target = state.repository().readPreparedCutoffTargets(cutoffOperationId).getFirst(); + List frozenRows = + state + .fixture() + .dsl() + .fetch( + "SELECT to_jsonb(c)::text AS image FROM" + + " game_session_canonical_issuer_admission_cohort_row c" + + " WHERE operation_id = ? ORDER BY row_ordinal", + cutoffOperationId) + .getValues("image", String.class); + var frozenTarget = + state + .fixture() + .dsl() + .fetchSingle( + "SELECT target_source_digest, closed_payload_digest FROM" + + " game_session_canonical_issuer_admission_cutoff_target" + + " WHERE operation_id = ?", + cutoffOperationId); + + new CanonicalGameplayBindingInventoryRepository(state.fixture().dsl()) + .recordFirstNewAccountAbort(state.fixture().source(), UUID.randomUUID()); + var transition = + state + .fixture() + .dsl() + .fetchSingle( + "SELECT status, inventory_revision FROM game_session_canonical_binding_transition" + + " WHERE transition_id = ?", + state.fixture().transitionId()); + assertThat(transition.get("status", String.class)).isEqualTo("ABORTED"); + assertThat(transition.get("inventory_revision", java.math.BigDecimal.class).toBigIntegerExact()) + .isGreaterThan(pending.inventorySnapshotRevision()); + var retry = state.repository().beginCutoff(cutoffOperationId, requestId); + assertThat(retry.cohortDigest()).isEqualTo(pending.cohortDigest()); + assertThat(retry.cohortRowCount()).isEqualTo(pending.cohortRowCount()); + assertThat(retry.liveBarrierEpoch()).isEqualTo(pending.liveBarrierEpoch()); + assertThatThrownBy(() -> state.repository().completeCutoff(cutoffOperationId)) + .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class); + assertThat(target.expectedOpenValue().exactBytes()) + .containsExactly(opened.exactPhysicalPayload()); + var closed = + state + .owner() + .closeAndRead( + cutoffOperationId, + target.closedValue().tenantId(), + target.closedValue().playableStateNamespaceId()); + assertThat(closed.scriptOutcome()).isEqualTo(3L); + assertThat(closed.exactPhysicalPayload()).containsExactly(target.closedValue().exactBytes()); + var installed = state.repository().completeCutoff(cutoffOperationId); + assertThat(installed.state()) + .isEqualTo(CanonicalGameplayIssuerAdmissionControlValue.State.INSTALLED); + assertThat(installed.liveBarrierEpoch()).isEqualTo(pending.liveBarrierEpoch()); + assertThat(installed.cohortDigest()).isEqualTo(pending.cohortDigest()); + assertThat( + state + .fixture() + .dsl() + .fetch( + "SELECT to_jsonb(c)::text AS image FROM" + + " game_session_canonical_issuer_admission_cohort_row c" + + " WHERE operation_id = ? ORDER BY row_ordinal", + cutoffOperationId) + .getValues("image", String.class)) + .containsExactlyElementsOf(frozenRows); + var completedTarget = + state + .fixture() + .dsl() + .fetchSingle( + "SELECT target_source_digest, closed_payload_digest, target_state," + + " exact_closed_readback_bytes FROM game_session_canonical_issuer_admission_cutoff_target" + + " WHERE operation_id = ?", + cutoffOperationId); + assertThat(completedTarget.get("target_source_digest", String.class)) + .isEqualTo(frozenTarget.get("target_source_digest", String.class)); + assertThat(completedTarget.get("closed_payload_digest", String.class)) + .isEqualTo(frozenTarget.get("closed_payload_digest", String.class)); + assertThat(completedTarget.get("target_state", String.class)).isEqualTo("CLOSED"); + assertThat(completedTarget.get("exact_closed_readback_bytes", byte[].class)) + .containsExactly(target.closedValue().exactBytes()); + assertThatThrownBy(() -> state.owner().initializeAndRead(state.fixture().originalOperationId())) + .isInstanceOf(IllegalStateException.class); + } + + @ParameterizedTest + @ValueSource(strings = {"SOURCE_BYTES", "MISSING_SOURCE", "MISSING_TARGET", "TARGET_DIGEST"}) + void cutoffRefusesChangedOrMissingFrozenEvidence(String corruption) { + FixtureState state = fixtureState(); + state.owner().initializeAndRead(state.fixture().originalOperationId()); + UUID cutoffOperationId = UUID.randomUUID(); + state.repository().beginCutoff(cutoffOperationId, UUID.randomUUID()); + var target = state.repository().readPreparedCutoffTargets(cutoffOperationId).getFirst(); + // Controlled corruption of retained SQL evidence; no trigger or runtime guard is bypassed. + String mutation = + switch (corruption) { + case "SOURCE_BYTES" -> + "UPDATE game_session_canonical_issuer_admission_cohort_row" + + " SET source_row_json = source_row_json || ' ' WHERE operation_id = ?"; + case "MISSING_SOURCE" -> + "DELETE FROM game_session_canonical_issuer_admission_cohort_row WHERE operation_id = ?"; + case "MISSING_TARGET" -> + "DELETE FROM game_session_canonical_issuer_admission_cutoff_target WHERE operation_id = ?"; + case "TARGET_DIGEST" -> + "UPDATE game_session_canonical_issuer_admission_cutoff_target" + + " SET target_source_digest = 'sha256:' || repeat('0', 64) WHERE operation_id = ?"; + default -> throw new IllegalArgumentException(corruption); + }; + assertThat(state.fixture().dsl().execute(mutation, cutoffOperationId)).isPositive(); + assertThatThrownBy( + () -> + state + .repository() + .readPreparedCutoffTarget( + cutoffOperationId, + target.closedValue().tenantId(), + target.closedValue().playableStateNamespaceId())) + .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class); + assertThatThrownBy(() -> state.repository().completeCutoff(cutoffOperationId)) + .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class); + } + @Test void reusesFrozenTargetInitializerAcrossOperationsRevisionProgressAndOriginAbort() { FixtureState state = fixtureState(); @@ -459,7 +592,7 @@ void reusesFrozenTargetInitializerAcrossOperationsRevisionProgressAndOriginAbort state .fixture() .dsl() - .fetchOne( + .fetchSingle( "SELECT status FROM game_session_canonical_binding_transition" + " WHERE transition_id = ?", state.fixture().transitionId()) @@ -561,6 +694,8 @@ private FixtureState fixtureState() { Candidate actualCandidate = fixture.candidate(); CanonicalGameplayBindingIdentity identity = identity(actualCandidate); fixture.publish(controlledLeaseEvidence(identity, fixture.generation(), fixture.target())); + // Controlled upstream Account current-source and stable-incarnation inputs; native SQL/Redis + // owners execute below, but this fixture does not establish production source custody. var currentState = new AtomicReference<>(currentIssuerState(actualCandidate)); var sourceReader = (CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerStateSource) @@ -585,11 +720,6 @@ private FixtureState fixtureState() { currentState); } - private CanonicalGameplayIssuerBindingLocalOperation prepareCurrentOperation( - FixtureState state, String seed) { - return prepareCurrentOperation(state, seed, state.candidate().accountId()); - } - private CanonicalGameplayIssuerBindingLocalOperation prepareCurrentOperation( FixtureState state, String seed, UUID accountId) { Candidate candidate = state.candidate(); @@ -811,7 +941,7 @@ private static String initializationState(FixtureState state, UUID operationId) return state .fixture() .dsl() - .fetchOne( + .fetchSingle( "SELECT initialization_state FROM game_session_canonical_issuer_admission_initializer" + " WHERE operation_id = ?", operationId) @@ -822,7 +952,7 @@ private static long countReceipt(FixtureState state, UUID operationId) { return state .fixture() .dsl() - .fetchOne( + .fetchSingle( "SELECT count(*) AS receipt_count" + " FROM game_session_canonical_issuer_admission_initializer_receipt" + " WHERE operation_id = ?", diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayProtectedIncarnationReceiverPostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayProtectedIncarnationReceiverPostgresIntegrationTest.java index b326c1ca65..0ac444f51d 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayProtectedIncarnationReceiverPostgresIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayProtectedIncarnationReceiverPostgresIntegrationTest.java @@ -1017,7 +1017,7 @@ private CanonicalGameplayProtectedIncarnationReceiver receiver( private CanonicalGameplayLoginResult originalLogin() { UUID tokenJti = - dsl.fetchOne( + dsl.fetchSingle( "SELECT verified_token_jti FROM game_session_initial_gameplay_login_journal" + " WHERE request_id = ?", original.requestId()) @@ -1026,7 +1026,7 @@ private CanonicalGameplayLoginResult originalLogin() { } private String initialTargetPostimage() { - return dsl.fetchOne( + return dsl.fetchSingle( "SELECT to_jsonb(t)::text FROM game_session_canonical_initial_account_barrier_target t" + " WHERE initializer_id = ?", initialRepository.readCurrent(original.requestId()).initializerId()) From 6b2533017b44a38d1dd5dc115bb24bb9ecf15812 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 27 Oct 2026 13:54:13 +1300 Subject: [PATCH 08/26] test: align manual Account admission RPC inventory --- .../AccountGameplayAdmissionLeaseGrpcServiceTest.java | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayAdmissionLeaseGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayAdmissionLeaseGrpcServiceTest.java index 1dea26640e..18c4aa8b0c 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayAdmissionLeaseGrpcServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayAdmissionLeaseGrpcServiceTest.java @@ -164,14 +164,16 @@ void rejectsNullOversizedAndClosedShapeRequestsBeforeCallingOwner() { } @Test - void manualFactoryExposesExactlyTheFourPurposeSpecificMethodsWithoutSpringRegistration() { + void manualFactoryExposesExactlyTheSixPurposeSpecificMethodsWithoutSpringRegistration() { assertThat(service.bindService().getServiceDescriptor().getMethods()) .extracting(method -> method.getFullMethodName()) .containsExactlyInAnyOrder( "account.v1.AccountGameplayAdmissionLeaseService/AcquireGameplayAdmissionLease", "account.v1.AccountGameplayAdmissionLeaseService/FinalizeGameplayAdmissionLease", "account.v1.AccountGameplayAdmissionLeaseService/ReadGameplayAdmissionLease", - "account.v1.AccountGameplayAdmissionLeaseService/AbortGameplayAdmissionLease"); + "account.v1.AccountGameplayAdmissionLeaseService/AbortGameplayAdmissionLease", + "account.v1.AccountGameplayAdmissionLeaseService/IssueOriginalNewGameplayCredential", + "account.v1.AccountGameplayAdmissionLeaseService/ConfirmOriginalNewGameplayAdmission"); } @Test From 18bea71a41876e8f85a49271f8e078ffd8a6c7b8 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 27 Oct 2026 15:43:38 +1300 Subject: [PATCH 09/26] Initialize real issuer OPEN owner in inherited registration-bound proof --- ...suerBindingLocalOperationRepositoryIntegrationTest.java | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalOperationRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalOperationRepositoryIntegrationTest.java index 25eb83d084..c28c487e73 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalOperationRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalOperationRepositoryIntegrationTest.java @@ -444,8 +444,11 @@ void ordinaryNewPhysicalOperationBoundRefuses257thBeforePreparationAndRetainsExa var currentState = new CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState( intent.sourceCheckpoint(), stableIncarnation("physical-operation-bound")); - initialCoverageOwner(dsl, () -> currentState) - .completeInitialBootstrap(intent.operationId(), bootstrapRequestId); + var anchor = + initialCoverageOwner(dsl, () -> currentState) + .completeInitialBootstrap(intent.operationId(), bootstrapRequestId); + new CanonicalGameplayIssuerAdmissionControlRepository(dsl) + .installInitialOpen(anchor, () -> currentState); var repository = new CanonicalGameplayIssuerBindingLocalOperationRepository(dsl, () -> currentState); // Every retained registration is created by the actual SQL owner. No local projection or From 722b7a332c5d9b41bb4bd587ab3e8d254408716d Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 27 Oct 2026 15:55:38 +1300 Subject: [PATCH 10/26] Qualify nullable issuer event lineage through its actual OPEN owner --- ...layIssuerBindingLocalOperationRepositoryIntegrationTest.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalOperationRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalOperationRepositoryIntegrationTest.java index 89612f2865..d1d6fe4c24 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalOperationRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalOperationRepositoryIntegrationTest.java @@ -474,6 +474,8 @@ void localIssuerOwnerRetainsPairedNullSourceEventEvidence() { var anchor = initialCoverageOwner(dsl, () -> currentState) .completeInitialBootstrap(intent.operationId(), intent.requestId()); + new CanonicalGameplayIssuerAdmissionControlRepository(dsl) + .installInitialOpen(anchor, () -> currentState); var operation = new CanonicalGameplayIssuerBindingLocalOperationRepository(dsl, () -> currentState) .beginOrResumeOrdinaryNew( From 2f13c6b1b2ec33c4f7139746f61117d8a89fd2e2 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 29 Oct 2026 02:46:18 +1300 Subject: [PATCH 11/26] Separate issuer and initial-account readiness from credential preparation --- .../account-service/runtime-and-data.md | 2 +- .../game-session-service/runtime-and-data.md | 4 +- ...em-architecture-jwt-and-token-contracts.md | 2 - .../architecture/system-architecture-redis.md | 2 - .../system-architecture-session-behavior.md | 2 - design/project-management/ai-observations.md | 6 + .../player-access-and-session.md | 8 +- .../v1/account_gameplay_admission_lease.proto | 54 +- ...ntOriginalNewFinalAdmissionReadClient.java | 154 --- .../AccountGameplayTokenIdentityFence.java | 31 +- ...ssionOriginalAckReceiptCommitExecutor.java | 69 +- ...AdmissionOriginalAckReceiptRepository.java | 44 +- ...tGameplayTokenIdentityFenceRepository.java | 73 +- ...iginalNewBoundGameplayCredentialOwner.java | 1198 ----------------- ...nalNewBoundGameplayIssuanceRepository.java | 935 ------------- ...ountGameplayAdmissionLeaseGrpcService.java | 112 +- ...ntGameplayAdmissionLeaseManualFactory.java | 45 - ...ntGameplayAdmissionLeaseWorkloadGuard.java | 36 - .../AccountGameplayDelegationRedisClient.java | 240 ---- .../AccountGameplayDelegationSigner.java | 307 ----- ...ccountGameplayDelegationTokenRegistry.java | 123 -- .../AccountMountedJwtSignerBundle.java | 154 --- ...riginal_new_bound_gameplay_credentials.sql | 370 ----- ..._original_ack_pg18_historical_recovery.sql | 142 -- ...nitiveAbortCompositionIntegrationTest.java | 45 +- ...rotectedEntryPrototypeIntegrationTest.java | 514 +------ ...ameplayCredentialOwnerIntegrationTest.java | 693 ---------- ...nOriginalAckReceiptCommitExecutorTest.java | 239 +--- ...eplayTokenIdentityFenceRepositoryTest.java | 70 +- ...alNewBoundGameplayCredentialOwnerTest.java | 50 - ...GameplayAdmissionLeaseGrpcServiceTest.java | 6 +- .../AccountGameplayDelegationSignerTest.java | 143 -- ...ccountGameplayAdmissionLeaseGrpcCodec.java | 612 +-------- ...ntGameplayAdmissionLeaseGrpcCodecTest.java | 152 --- .../AccountGameplayAdmissionLeaseClient.java | 74 +- ...calGameplayBindingInventoryRepository.java | 326 ----- .../CanonicalGameplayIssuerCohortSql.java | 11 +- ...meplayOriginalNewAuthenticatedSession.java | 587 -------- ...layOriginalNewBoundCredentialVerifier.java | 318 ----- ...CanonicalGameplayOriginalNewCandidate.java | 219 --- ...icalGameplayOriginalNewCandidateCodec.java | 731 ---------- ...ameplayOriginalNewCandidateRedisOwner.java | 547 -------- ...OriginalNewCandidateRedisOwnerFactory.java | 22 - ...alNewCandidateRedisScriptContribution.java | 52 - ...on.redis.contracts.RedisScriptContribution | 1 - ...al_original_new_candidate_installation.sql | 106 -- ...session-original-new-candidate-install.lua | 79 -- ...ession-original-new-candidate-install.json | 40 - ...calGameplayBindingRuntimeTestFixtures.java | 2 +- ...rtitionBuildRepositoryIntegrationTest.java | 14 - ...NewCandidateRedisOwnerIntegrationTest.java | 659 --------- ...ccountControlMigrationIntegrationTest.java | 462 +++++++ ...countGameplayAdmissionLeaseClientTest.java | 206 --- ...ayOriginalNewAuthenticatedSessionTest.java | 709 ---------- ...nicalGameplayOriginalNewCandidateTest.java | 535 -------- 55 files changed, 567 insertions(+), 11770 deletions(-) delete mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/AccountOriginalNewFinalAdmissionReadClient.java delete mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountOriginalNewBoundGameplayCredentialOwner.java delete mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountOriginalNewBoundGameplayIssuanceRepository.java delete mode 100644 services/account-service/src/main/resources/db/migration/V1012__account_original_new_bound_gameplay_credentials.sql delete mode 100644 services/account-service/src/main/resources/db/migration/V1013__account_original_ack_pg18_historical_recovery.sql delete mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountOriginalNewBoundGameplayCredentialOwnerIntegrationTest.java delete mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountOriginalNewBoundGameplayCredentialOwnerTest.java delete mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewAuthenticatedSession.java delete mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewBoundCredentialVerifier.java delete mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCandidate.java delete mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCandidateCodec.java delete mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCandidateRedisOwner.java delete mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCandidateRedisOwnerFactory.java delete mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayOriginalNewCandidateRedisScriptContribution.java delete mode 100644 services/game-session-service/src/main/resources/db/migration/V1048__canonical_original_new_candidate_installation.sql delete mode 100644 services/game-session-service/src/main/resources/redis/lua/game-session-original-new-candidate-install.lua delete mode 100644 services/game-session-service/src/main/resources/redis/scripts/game-session-original-new-candidate-install.json delete mode 100644 services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCandidateRedisOwnerIntegrationTest.java create mode 100644 services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRetainedFirstNewAbortAccountControlMigrationIntegrationTest.java delete mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewAuthenticatedSessionTest.java delete mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCandidateTest.java diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index 79559fb8ac..78cfff2898 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -18,7 +18,7 @@ The manually composed admission acquisition owner reads the retained original Ac Account has an unregistered initial private gameplay LOGIN source slice for request-bound credential digests, signer and JWKS trust, pending and committed registry ownership, authority projection reads, and encrypted response recovery. Before its final Account transaction, the commit source publishes the current issuer and Account projections and requires an exact matching observation; publication or observation failure denies the commit. Caller currentness and response recovery may use an older committed signer generation only while the exact original public-key fingerprint remains in the current trusted JWKS and current owner evidence, including the original issuance JTI, still matches; the applicable authority, API, source, expiry, and compromise fences remain required. The source fixes the explicitly approved `game-session-account-delegation` profile and has no caller-selected profile or property bypass. It adds no endpoint or runtime registration; deployed ACL/TLS, signer-key custody, caller authentication, consumer authorization, gameplay admission, and runtime activation remain unproved. See the [Player Access and Session tracker](../../../project-management/implementation-tracking/player-access-and-session.md#initial-private-gameplay-login-issuance-source-intake) for exact unit and physical fixture proof scope. -Account's unregistered original-ACK owner preserves the original physical COMMIT and its separately committed receipt. Forward V1013 extends historical receipt recovery to PostgreSQL 18 while retaining V144/V146 and the original evidence. The private owner captures one fixed snapshot and WAL fence, releases its SQL locks, positively observes coverage of that unchanged fence, and independently compares the exact receipt. Focused PostgreSQL 18 proof covers this recovery boundary. This source remains unregistered and supplies no caller authentication or gameplay admission. Migration provenance, proof and remaining gaps belong to the [Player Access and Session tracker](../../../project-management/implementation-tracking/player-access-and-session.md#account-fresh-original-ack-storage-preparation). +Account's unregistered original-ACK storage seam requires PostgreSQL 18 for fresh operations: the original executor performs a writable SERIALIZABLE physical COMMIT on its enlisted connection and returns an opaque acknowledgement only after observing the database clock before unchanged expiry; a separate transaction commits the exact receipt. Receiving V146 changes only the fresh receipt-insert guard, preserving the donor V122 SQL unchanged as receiving V144. Its historical durable reader remains PostgreSQL 16-only, so lost-acknowledgement recovery and retained-receipt retries remain denied on PostgreSQL 18. This storage evidence does not authenticate a caller, establish current Account ownership or admission, authorize gameplay, or register runtime behavior. Migration provenance and pending receiving proof are recorded in the [Player Access and Session tracker](../../../project-management/implementation-tracking/player-access-and-session.md#account-fresh-original-ack-storage-preparation). Account V40 adds owner-proven sequence-zero source baselines to the inherited V30–V39 authority-storage and retention-safety foundation; V74–V89 preserve that baseline and add source/global-role guards, draft-source writer exclusions and fences, immutable reset/logout/security-operation receipts, creator and tenant-bootstrap provenance, individual Creator Party and hosted-terms/environment-binding persistence, and source-change journals. V90–V97 add persistence relations and guards for source-currentness work across Account, control-UI issuance, selected-publication authorization/settlement, and Game Logic. V98 adds durable hosted-terms disclosure handoff and immutable source-evidence relations with database transition guards. These DDL stages establish persistence and source-writer fence relationships; they do not activate owner writers, legal authority verification, dispatch, or consumers. New repository-created Accounts receive the V40 source baseline; retained pre-V40 rows are neither backfilled nor admitted. Password-reset completion atomically claims and consumes its token, updates the Account, appends the canonical event and receipt, and reads back current source evidence in the owner transaction. If an earlier source intent remains `WAITING`, the request returns retryable `AUTH_UNAVAILABLE`; it does not wait on a thread for settlement, and an exact retry retains the original operation identity. A `WAITING` reset intent retains the Argon2 password verifier needed by that retry; terminal source commit or abort clears the verifier while preserving its digest and immutable source binding and receipt. Finite receipt retention remains unresolved under the owning retention policy; no lifetime is selected here. Logout-all production remains unregistered and unwired. These persistence primitives do not provide public JOIN, target-currentness protection, or runtime activation. Exact physical and local proof limits are recorded in 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. diff --git a/design/architecture/microservices/game-session-service/runtime-and-data.md b/design/architecture/microservices/game-session-service/runtime-and-data.md index ee9f6047e8..79e5e042a2 100644 --- a/design/architecture/microservices/game-session-service/runtime-and-data.md +++ b/design/architecture/microservices/game-session-service/runtime-and-data.md @@ -10,11 +10,11 @@ The service runtime model assumes replaceable workers, not authoritative in-proc The sections below define the target-state runtime contract. Current implementation and proof status is: -- **Local NEW issuer preparation:** the unregistered Game Session sources now manually compose the initial issuer anchor, ordinary post-baseline one-key member/capacity projection, issuer-local release, and original-operation terminal-capacity retirement, each with exact physical readback and controlled Account checkpoint and stable-incarnation collaborators. Ordinary ADD revalidates the target’s current Account authority, while terminal cleanup and non-target accounting preserve captured Account provenance. Completed-original bootstrap retries return retained installation evidence; current physical verification remains separate. The focused component proofs do not establish operational source or incarnation custody. A separate admitting issuer acknowledgement, issuer barrier/`OPEN`, final CAS, and admission remain absent. Operational source/incarnation custody, legacy recovery, production PKI, runtime registration, and activation remain open; see the [Player Access tracker](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-new-admission-components) for proof attribution and limits. The [issuer anchor owner](../../system-architecture-redis.md#installed-issuer-anchor-for-ordinary-new) defines the physical contract. +- **Local NEW issuer preparation:** the unregistered Game Session sources now manually compose the initial issuer anchor, ordinary post-baseline one-key member/capacity projection, issuer-local release, and original-operation terminal-capacity retirement, each with exact physical readback and controlled Account checkpoint and stable-incarnation collaborators. Ordinary ADD revalidates the target’s current Account authority, while terminal cleanup and non-target accounting preserve captured Account provenance. Completed-original bootstrap retries return retained installation evidence; current physical verification remains separate. The focused component proofs do not establish operational source or incarnation custody. The unregistered readiness owners additionally retain a separate binding-local issuer acknowledgement, live issuer admission control and tenant-local issuer OPEN/cutoff evidence. These do not supply the final session CAS or admission. Operational source/incarnation custody, legacy recovery, production PKI, runtime registration, and activation remain open; see the [Player Access tracker](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-new-admission-components) for proof attribution and limits. The [issuer anchor owner](../../system-architecture-redis.md#installed-issuer-anchor-for-ordinary-new) defines the physical contract. - **Local NEW account-member repair:** the unregistered owner prepares the original binding-local operation, performs one global account-member write and physical readback outside SQL, then accepts its exact acknowledgement in SQL. This supplies `ADD_OR_RETAIN` evidence only; the candidate remains provisional. Account-wide lifecycle writers, remaining index and region acknowledgements, and the guarded final admission CAS remain open. See [Session Behavior](../../system-architecture-session-behavior.md#global-account-active-binding-index) and [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-new-admission-components). -- **Account-fence intent and CLOSED target preparation:** local sources persist account acquisition intent and cohort, tenant-to-gameplay-tag mapping, protected current observations, a one-key CLOSED installer/readback, and immutable per-target receipts. A receipt is historical AS-OF evidence; targets remain `REQUIRED`. Operational protected-incarnation authority, all-target `INSTALLED`, barrier `OPEN`, token release, final admitting CAS, and production admission remain unproved. See [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-new-admission-components) for proof attribution and limits. +- **Account-fence intent and CLOSED target preparation:** local sources persist account acquisition intent and cohort, tenant-to-gameplay-tag mapping, protected current observations, a one-key CLOSED installer/readback, and immutable per-target receipts. A receipt is historical AS-OF evidence; targets remain `REQUIRED`. A separate unregistered INITIAL-only Account OPEN owner retains its original login/control source, target, possible dispatch and exact readback; pending initializers participate in the next acquisition cohort. This arm cannot reopen a CLOSED or uncertain target and does not complete account-wide acquisition or release. Operational protected-incarnation authority, all-target `INSTALLED`, token release, final admitting CAS and production admission remain unproved. See [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-new-admission-components) for proof attribution and limits. - **Current first-party receiving boundary:** Game Session's prepared receiver verifies the Gateway-signed context and rechecks the canonical target and retained private-handle evidence. When that first-party context is present, bare `LOGIN` and `PLAY` return `FIRST_PARTY_AUTHORITY_UNAVAILABLE` before legacy Account authentication, Entity resolution, or gameplay binding effects. Recovery from registry loss still requires the persisted compact JWS to remain valid; registry loss does not extend its expiry. The public Gateway cookie path is currently denied and its gameplay-route readiness is `OUT_OF_SERVICE`; no first-party wire success or admission is claimed. Account context production, shared replay fencing, and dedicated Gateway key qualification remain open. diff --git a/design/architecture/system-architecture-jwt-and-token-contracts.md b/design/architecture/system-architecture-jwt-and-token-contracts.md index 888128fb89..556027a428 100644 --- a/design/architecture/system-architecture-jwt-and-token-contracts.md +++ b/design/architecture/system-architecture-jwt-and-token-contracts.md @@ -382,8 +382,6 @@ Exact route identity and known route-class selection precede claim-shape and aud `tokenGeneration` is distinct from every field in `authorityTuple` and from `issuanceFence`. It binds refresh/replacement ordering for one token lineage; it does not grant scope, replace current authority checks, or serve as restart authority by itself. Game Session uses the durable protected single-use rebind handle in the gameplay binding when a restart or takeover owner no longer has the raw private delegation JWT; Account consumes that handle and returns the next `tokenGeneration` value plus replacement handle under the binding/fence protocol. `membershipVersion` remains separate from `authorityTuple.membershipAuthorityGeneration` and must be checked independently. -For the original public-production `NEW` binding, Account creates one fresh `ORIGINAL_NEW` bound-token lineage anchored to the immutable original binding and lease/transition after the original Account commit. Its first `tokenGeneration` is exactly `1` within that lineage and its signed `jti` is distinct from the unscoped `LOGIN` lineage, row and `jti`; the original signed `LOGIN` evidence remains unchanged. The existing Account issuance and registry owner persists the original issuance identity, complete frozen claims and protected credential/handle result once and links them to the exact original committed receipt. Concurrent requests and exact retries for the same original binding/lease reuse that genesis; they cannot start another lineage, remint, extend expiry or substitute replacement/REBIND. Current profile, source and issuance-fence checks remain independent of token generation and Game Session barrier epochs. The original lease bytes remain immutable, and unavailable protected recovery fails closed. [Session Behavior](./system-architecture-session-behavior.md#canonical-public-production-new-admission) owns publication of the complete authenticated binding and confirmation of its actual admission-time continuity anchor; a preissued handle is not usable before those original admission and currentness predicates are established. This genesis rule does not authorize general rotation, replacement or lineage migration. - For JWT-bearing authorization routes, the issued-token registry has only two structural exceptions: an explicitly public route in the route matrix whose contract requires no JWT, and the exact matrix-declared `gameplay-connect` Gateway handshake with its bounded single-use replay contract. No JWT-bearing route may turn registry absence into authorization. Pending-deletion routes use their separate opaque `pending-deletion-access` credential and dedicated registry contract; that lifecycle credential is not a JWT or a third issued-token-registry exception. The logout endpoints have a separate lifecycle-only reconciliation path: after local signature/profile/time/subject validation, `AuthLogout` may return the stored result only from a durable Account pending/committed intent or tombstone for that exact token, and `AuthLogoutAll` may return the stored result only from durable Account evidence that a prior logout-all superseded the presented authority. These retries create no authorization context and cannot be reused by any other route; a current or ambiguous token without matching durable evidence remains denied. JWT verification model (normative): diff --git a/design/architecture/system-architecture-redis.md b/design/architecture/system-architecture-redis.md index 89d6e87e25..057b13752c 100644 --- a/design/architecture/system-architecture-redis.md +++ b/design/architecture/system-architecture-redis.md @@ -301,8 +301,6 @@ Authenticated gameplay session keys capture: The authenticated gameplay payload is one complete canonical contract, not a compatibility family. Every authenticated gameplay binding must carry `schemaVersion=2`; a missing version, `schemaVersion=1`, or any other unsupported version fails closed before the record can be used for refresh, resume, rebind, takeover, admission, backend authorization, or recovery. There is no reduced authenticated payload for a non-resumable binding: terminal or cleanup state does not relax the schema or become retained admission evidence, and fresh `LOGIN`/`PLAY` is required to establish a new binding. Bootstrap/pre-auth context remains unauthenticated and is not an authenticated gameplay payload. -The original-`NEW` provisional artifact has a separate closed, non-admitting type at the same canonical session key. It is not an authenticated session schema and is rejected by authenticated readers, backend authorization and `PLAY`/`LOOK`. Its exact physical preimage is checked by the final tenant-local CAS; no unchecked side candidate or global key may substitute. [Session Behavior](./system-architecture-session-behavior.md#session-and-identity-management) owns the ordering from the original Account commit and complete credential to final admission, including the scope-dependent six- or seven-key set and confirmation of the actual admission-time continuity anchor. - `schemaVersion=2` is the canonical authenticated-session contract and requires the same common fields plus exactly ten authentication-specific fields: `authTokenHash`, `authTokenIssuedAt`, `authTokenExpiresAt`, `tokenGeneration`, `issuanceFence`, `rebindHandle`, `continuityBindingExpiresAt`, the complete `membershipBaseline`, the complete `authorityTuple`, and the complete `outboxCheckpoints` set. Readers, refresh, resume, rebind, admission, recovery, and CAS scripts must reject any authenticated record whose version is not exactly `2` or whose required field is absent, malformed, or unavailable for its declared type. The authentication identity, time, generation, fence, handle, and continuity fields are canonical scalar fields; `membershipBaseline` must instead be one complete same-snapshot object whose nested `membershipBaseline.membershipVersion` is exactly the one-tenant map `{tenantId: version}`, while `authorityTuple` is the complete object and `outboxCheckpoints` is the complete set. A missing baseline member or a multi-tenant, differently keyed, aggregate, scalarized, or otherwise malformed nested map fails closed. `membershipBaseline.membershipAuthorityGeneration` and `authorityTuple.membershipAuthorityGeneration` are both required in their owning objects and are compared independently; a duplicate standalone top-level `membershipAuthorityGeneration` is an invalid extra field and is rejected even when its value matches. The rotation `installationIdentity` is not an additional `schemaVersion=2` authenticated gameplay field. It is candidate-installation metadata carried by the lease-scoped acknowledgement and durable installation-attempt carriers, with the established shape `{rotationOperationId, leaseId, gameplayBindingId, installationFence}`. The durable installation attempt is keyed by the existing `rotationOperationId`; the first session-only CAS and the second fenced session-only CAS must carry and exact-compare that same linkage before the candidate can become admissible. No `installationIdentity` member, including `rotationOperationId`, is retained as an undeclared field in the final admissible gameplay binding. The `INSTALLING` candidate remains non-admissible until the matching acknowledgement and second fenced CAS complete. diff --git a/design/architecture/system-architecture-session-behavior.md b/design/architecture/system-architecture-session-behavior.md index 0df4a73eec..5f04e3e3cf 100644 --- a/design/architecture/system-architecture-session-behavior.md +++ b/design/architecture/system-architecture-session-behavior.md @@ -207,8 +207,6 @@ Every `GameplayBindingInventory` row selected for an account-index operation rec The tenant-qualified repair protocol is mandatory and the untagged account key is never included in tenant-local Lua or session-only CAS. Before the tenant-local session CAS can publish an active or provisional binding, Game Session commits a PostgreSQL repair obligation containing the expected prior generation, candidate `bindingGeneration`, unique transition identity, desired account-index add/remove, and `accountIndexFence`. The shard-local CAS may publish the candidate only when the expected prior generation and current session owner/fence still match; it records `accountIndexState=REPAIR_REQUIRED`, so the candidate is provisional and non-admissible. The separate account-key operation carries the same transition identity and fence, adds or retains the generation-qualified candidate before removing an old member, and refuses a removal when the authoritative binding or durable obligation has a newer generation/fence. A stale add may remain as an extra projection for repair, but a stale remove must never hide a newer binding. Game Session acknowledges only an exact `accountIndexAcknowledgement` matching the schema below and the fenced add/remove outcome, then uses a follow-up tenant-local CAS to set `accountIndexState=ACKNOWLEDGED` only when the same candidate generation/fence and the acknowledgement's operation/snapshot carrier are still current and matching. A missing, stale, conflicting, cross-tenant, or unavailable member leaves the binding non-admissible and the account scope fenced. -An original `NEW` candidate before Account finalization is a distinct typed, non-admitting lease-bound artifact at the canonical session key, not an incomplete authenticated `schemaVersion=2` session. Its exact positive physical readback may support the original provisional decision and Account finalization, but every authenticated reader and `PLAY`/`LOOK` path rejects it. After the original Account commit, Account supplies the complete bound credential and protected opaque rebind handle from the unchanged original binding, membership baseline and checkpoints. Only the final checked tenant-local CAS replaces the exact candidate with the complete authenticated session and establishes `admissionAt` and the immutable continuity expiry. The preissued handle does not claim those future times; its original issuance record confirms them only from the authenticated original Game Session admission result, and missing confirmation recovers that same result without reminting or extending authority. - The exact account-index acknowledgement schema is: ```text diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 80d25697bd..255b9ee4a3 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -476,3 +476,9 @@ Entry format: - Reconsideration trigger: the original attempt is recovered and the exact parser/attribution cause and diagnostic behavior are verified. Gameplay reported the retained handles directly to FireController's owner; no database or runtime bypass was used. - Recovery: FireController identified six separately fingerprinted findings grouped into five comment containers. Parser fix `8f6e6121` recovered the same original attempt and all six exact findings; Gameplay verified the pinned head/base and finalized their native decisions. No trigger, allowance or controls changed. Full required controller CI was still pending at its owner's recovery handoff; native/race and packaged checks had passed. + +- `2026-10-29`: Quiet native proof and JVM process matching need distinct evidence. The full 256-cycle issuer retirement regression produced no fresh integration XML or Gradle log output for many minutes while its owned PostgreSQL commits continued; it ultimately passed with the other selected Game Session cases. A generic process-name filter also falsely suggested the executor had exited because the process name was `java`. Confirm exact owned PIDs and use a read-only thread dump or run-owned database progress before diagnosing a hang or disappearance. A quiet task, an absent grep match and old XML establish neither failure nor success; preserve the eventual terminal result and fresh reports. + +- `2026-10-29`: A new provider summary section blocked an otherwise attributed Hosted capture. CodeRabbit returned an inline finding plus an explicitly unverified finding under “Additional comments”; FireController rejected the unfamiliar inventory format instead of inventing an empty review. The original attempt and comparison remain held while its independent owner adds bounded decoding and recovers the same capture. Do not repost, spend another allowance or treat provider acknowledgement as zero findings; recovery is still pending at this checkpoint. + +- 2026-10-29: Follow-up to the retained Hosted additional-comment capture issue: FireController recovered the same original attempt after updating its summary parser; both findings were independently adjudicated without a replacement trigger or allowance reset. Existing MCP sessions did not understand the new source kind, so the release-matched worker-bound CLI supplied the evidence until host reconnection. 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 7a62ca3588..6cc554a005 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -8,13 +8,13 @@ This is a non-normative implementation tracker for player access and session. Ca ### Canonical NEW admission components -The current local correction adds explicit recovery for a stale, uninstalled initial issuer-bootstrap candidate. Forward V1038.3 retains its original intent, cohort and issued work, captures the new actual inventory cut under monotonic fences, and atomically binds immutable supersession lineage to current control. A strictly newer trusted layout separates old physical work; installed anchors remain ineligible. Account CI selection and migration task inputs now cover its Game Session owner-composition dependency, and the native registration-image and lost-reply proofs use their actual SQL/Lua contracts. R827 passes 31 of 32 focused cases; its remaining failure is a test assertion against the transaction wrapper rather than the nested PostgreSQL refusal. R828 then passes that complete recovery case with affected integration static and formatting checks. Together they qualify 32 distinct current-source cases, including two actual Account abort compositions; frontier, jOOQ, affected static, formatting and documentation checks pass. The new recovery sequence uses controlled Account terminal input through the actual Game Session abort owner, separately from those two authenticated Account compositions. This is focused proof, not a full service-suite, live layout rotation, retained-key cleanup or production-authority claim. +The receiving #3320 prerequisite contains unregistered issuer LIVE control, tenant-local issuer OPEN/cutoff owners and the separate binding-local issuer acknowledgement, together with INITIAL-only Account OPEN initialization. Ordinary binding preparation and issuer projection join current live issuer control; pending Account initializers are included in the acquisition cohort, and both barrier owners retain original dispatch and exact readback evidence without reopening uncertain or CLOSED targets. This readiness boundary does not contain original-NEW candidate installation, Account bound credential/handle issuance, the final controller CAS, committed Game Session result reader or whole-flow coordinator; those remain dependent preparation and final-admission work. Extraction receiving proof R849 passes 75 of 76 selected unit/native cases, including the full 256-cycle physical-retirement case; its aggregate remains failed because the historical Account fixture opened V1038 while invoking current issuer readiness. R855 then passes both the corrected current authenticated-owner composition and a separate populated V1038→V1038.1 migration-retention proof. Its aggregate failed only an unused private fixture overload; R856 passes affected Account static, formatting and documentation checks after removing that overload. The migration fixture uses controlled historical terminal rows, while the current composition independently proves real owner calls. Earlier component evidence below retains its original source attribution; this is focused receiving proof, not a complete service-suite or public admission result. Operational source/incarnation custody, production PKI, default registration, public admission and activation remain unproved. -The receiving #2972 boundary adds unregistered issuer LIVE/tenant OPEN and Account INITIAL OPEN owners, exact nonadmitting original-NEW candidate installation, and Account-owned generation-1 bound credential/opaque-handle issuance with a strict immediate session consumer. It remains a preparation boundary: the concrete final controller CAS, committed Game Session result reader and whole-flow coordinator are not supplied by this publication. Account final confirmation fails closed without its authenticated final-read dependency. R765 passes all 49 selected receipt/owner unit cases, production and unit static checks, formatting and documentation checks. R768 passes all 26 selected PostgreSQL/Redis cases and integration static/format checks, including genuine original COMMIT and independent receipt recovery, populated V1012→V1013 retention, same-transaction and stale-snapshot refusal, and actual bound issuance with unchanged replay. Its owned SQL fault occurs after real Redis activation; unavailable or changed controlled Game Session final reads leave SQL unconfirmed, and a fresh exact read confirms the same credential and expiry. The Game Session final-read callback and signer custody remain controlled inputs. Source hashes match the passing native scope and all five observed containers are independently absent. Earlier failed aggregates remain failed. These results do not establish the complete Game Session final-CAS flow, production custody, default registration or activation. +The current local correction adds explicit recovery for a stale, uninstalled initial issuer-bootstrap candidate. Forward V1038.3 retains its original intent, cohort and issued work, captures the new actual inventory cut under monotonic fences, and atomically binds immutable supersession lineage to current control. A strictly newer trusted layout separates old physical work; installed anchors remain ineligible. Account CI selection and migration task inputs now cover its Game Session owner-composition dependency, and the native registration-image and lost-reply proofs use their actual SQL/Lua contracts. R827 passes 31 of 32 focused cases; its remaining failure is a test assertion against the transaction wrapper rather than the nested PostgreSQL refusal. R828 then passes that complete recovery case with affected integration static and formatting checks. Together they qualify 32 distinct current-source cases, including two actual Account abort compositions; frontier, jOOQ, affected static, formatting and documentation checks pass. The new recovery sequence uses controlled Account terminal input through the actual Game Session abort owner, separately from those two authenticated Account compositions. This is focused proof, not a full service-suite, live layout rotation, retained-key cleanup or production-authority claim. The local issuer owners now reject plans that exceed the executable 256-member-operation bound per partition, including retained `RELEASED` lineage independently of logical active capacity. A blocked plan retains its complete cohort and planned work; physical preparation refuses before allocating operation rows. Fresh ordinary NEW registration also checks the same nonretired local-operation set under the inventory lock before allocating new identities or rows, while exact retries retain their original operation at the bound. Both bootstrap owners use one strict Account issuer source-event verifier. R791 freshly passes the four PostgreSQL boundary cases: 256 allowed, both 257-reservation overflow forms blocked, and ordinary registration refusal/retry with unchanged durable state. R793 then freshly passes all 26 selected PostgreSQL cases across the plan, ordinary-operation and intent owners, plus affected production/integration static analysis, formatting and documentation checks. This is focused owner proof, not a complete service-suite or public admission result. Default registration, external source custody and admission limits remain unchanged. -The Account gameplay-admission lease and the unregistered Game Session receiver remain separate authority boundaries. The unregistered Account verifier uses the pinned trusted JWKS and fixed gameplay-delegation profile, selects the current `COMMITTED`/`ACTIVE` issuance by verified JTI, and compares the full immutable token identity, hash and authority; it retains no presented JWT and makes no membership, entitlement or lease decision. Focused acquisition proof joins the exact recovered JWT to actual current issuance, physical Coordination Redis and the same-connection Account source graph, preserving the original pending lease on retry. R494 freshly passes 104 Account unit cases and eight selected PostgreSQL/Redis cases, with affected static analysis and formatting. Its manual TLS receiver exercises all four generated RPCs with the exact recovered Account JWT and current issuance/registry and SQL sources, then performs PostgreSQL 18 physical COMMIT and independent durable original-ACK insertion/readback. The original lease attempt and ACK are immutable. The original physical-commit executor retains focused PostgreSQL component proof, and the Game Session lease client has controlled mTLS proof; that earlier proof retained the PostgreSQL 18 historical-reader denial. The receiving V162 qualification below extends that owner without changing the original evidence. The reverse Game Session target/decision response and protected signer/materializer evidence remain controlled. Exact metadata and cleanup-obligation recovery revalidate the current caller/global Account/token under Account-first SQL locks without requiring a superseded tenant admission baseline; new acquisition and first finalization retain full tenant-source checks. These results do not prove genuine Game Session authority, cleanup delivery, final controller admission, production custody or activation. Token-retirement, orphan-cleanup delivery and admitted binding remain open. +The Account gameplay-admission lease and the unregistered Game Session receiver remain separate authority boundaries. The unregistered Account verifier uses the pinned trusted JWKS and fixed gameplay-delegation profile, selects the current `COMMITTED`/`ACTIVE` issuance by verified JTI, and compares the full immutable token identity, hash and authority; it retains no presented JWT and makes no membership, entitlement or lease decision. Focused acquisition proof joins the exact recovered JWT to actual current issuance, physical Coordination Redis and the same-connection Account source graph, preserving the original pending lease on retry. R494 freshly passes 104 Account unit cases and eight selected PostgreSQL/Redis cases, with affected static analysis and formatting. Its manual TLS receiver exercises all four generated RPCs with the exact recovered Account JWT and current issuance/registry and SQL sources, then performs PostgreSQL 18 physical COMMIT and independent durable original-ACK insertion/readback. The original lease attempt and ACK are immutable. The original physical-commit executor retains focused PostgreSQL component proof, and the Game Session lease client has controlled mTLS proof; the retained PostgreSQL 18 receipt-reader denial remains unchanged. The reverse Game Session target/decision response and protected signer/materializer evidence remain controlled. Exact metadata and cleanup-obligation recovery revalidate the current caller/global Account/token under Account-first SQL locks without requiring a superseded tenant admission baseline; new acquisition and first finalization retain full tenant-source checks. These results do not prove genuine Game Session authority, cleanup delivery, final controller admission, production custody or activation. Token-retirement, orphan-cleanup delivery and admitted binding remain open. The Game Session canonical inventory now retains Account's exact issuer string through the forward V1024→V1025 conversion. R488 passes 19 selected PostgreSQL cases, including populated-row migration preservation, restart, canonical writes, and refusal by the typed reader to reinterpret retained UUID issuers. This proves storage identity conversion only; issuer ownership and admission remain unqualified. @@ -282,7 +282,7 @@ This preparation is owned by AA-1.3 in [Capability Status](#capability-status), The receiving Account cut imports the preserved original-ACK storage preparation from `codex/gameplay-game-design-publication-storage-foundation-20261009` at `d66d36951d3df780641e0ef04819f15df52ddc39` plus its uncommitted PostgreSQL 18 fresh-path changes. Only the receiving migration filenames are allocated anew: V140 ← source V118 (lease operations), V141 ← V119 (unknown-decision abort), V142 ← V120 (original-finalization stamp and experimental confirmation storage), V143 ← V121 (global pending fences), V144 ← V122 (original-ACK receipt), V145 ← V136 (experimental confirmation write retirement), and V146 ← V139 (PostgreSQL 18 fresh-insert guard). Their SQL bytes, including historical version comments, are preserved. Source V122 retains SHA-256 `c4f66ce16c77514717cbc9d2e0d65bc8c8ee0882239371d8518f587a0ef53490`, matching the historical `2cb445617f584d25c805f5c08e9dde67fff4efc4` migration; no donor renumbering or external migration application is performed. -The unregistered executors and receipt repository preserve the exact original operation, source identity, finalization XID, unchanged expiry and original clock bound. Fresh original and independent receipt COMMITs remain PostgreSQL 18-only. A retained COMMITTED retry cannot mint another original acknowledgement. Forward V1013 extends the existing historical reader to PostgreSQL 18 as well as its previously supported PostgreSQL 16, retaining the fixed snapshot, WAL upper fence, independently committed receipt, Account-first row locks and bounded flush-coverage observation. It never writes a marker, forces a flush or restamps timing. R768 freshly passes the 25-case PostgreSQL prototype: the populated V1012→V1013 case retains pre-upgrade PostgreSQL 18 denial and proves unchanged operation/receipt row images and `xmin`; restarted-owner and lost-receipt-acknowledgement recovery preserve original timing. The private pending capture is not durability proof. The executor positively observes actual flush coverage of its exact frozen fence after the capture transaction releases its locks, then independently compares the entire receipt. R763 exposed the strict in-transaction reader’s quiet-server WAL-tail liveness limit; its two failures remain recorded. Unit coverage includes unavailable flush observations and changed readback, while a deterministic physical WAL-unavailable case remains unqualified. PostgreSQL 16 and other server majors have not been rerun in this receiving scope. This is storage recovery, with no renewal of admission authority or production registration. +The unregistered executors and receipt repository preserve the exact original operation, source identity, finalization XID, unchanged expiry and original clock bound. Fresh original and independent receipt COMMITs are explicitly PostgreSQL 18-only; retained COMMITTED retries cannot mint another acknowledgement, and the unchanged historical durable reader still denies PostgreSQL 18 recovery or retained-receipt retries. The `AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest` PostgreSQL prototype contains 18 `@Test` cases and uses the receiving canonical `AccountPostgresIntegrationFixture(true)` without importing another fixture or build dependencies. The copied unit proof sources are separate mocked-JDBC cases. Full-check selected the PostgreSQL cases, but they skipped because local Docker was unavailable; physical PostgreSQL proof remains pending the consolidated gate. No donor or earlier receiving result proves this new intake. Authentication, current ownership/admission, runtime registration, activation and playable capability status remain unchanged. Account-local storage consequences remain in [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#implementation-status). ### Restricted original-claim evidence continuation preparation diff --git a/protos/account/v1/account_gameplay_admission_lease.proto b/protos/account/v1/account_gameplay_admission_lease.proto index 227f22e0e0..2063a5022f 100644 --- a/protos/account/v1/account_gameplay_admission_lease.proto +++ b/protos/account/v1/account_gameplay_admission_lease.proto @@ -19,15 +19,6 @@ service AccountGameplayAdmissionLeaseService { returns (AccountGameplayAdmissionLeaseResponse); rpc AbortGameplayAdmissionLease(AbortGameplayAdmissionLeaseRequest) returns (AccountGameplayAdmissionLeaseResponse); - // Issues the first purpose-bound credential only after Account's original COMMITTED lease and - // independent original-ACK receipt have been re-read. The returned handle is internal to - // Game Session and is never forwarded to a player client. - rpc IssueOriginalNewGameplayCredential(IssueOriginalNewGameplayCredentialRequest) - returns (AccountGameplayAdmissionLeaseResponse); - // Requests exact recovery of the final Account confirmation. Account performs the protected - // original-final-admission read itself; this request carries no proof or timestamps. - rpc ConfirmOriginalNewGameplayAdmission(ConfirmOriginalNewGameplayAdmissionRequest) - returns (OriginalNewAdmissionConfirmationResponse); } // A new operation selector and expected current values only; Account still resolves and checks @@ -68,30 +59,6 @@ message AbortGameplayAdmissionLeaseRequest { repeated string binding_decision_uuid = 4; } -// Exact recovery or first issuance for one unchanged original NEW lease. The unscoped LOGIN GSA is -// only the authenticated caller; it is not the credential this operation produces. -message IssueOriginalNewGameplayCredentialRequest { - repeated uint32 schema_version = 1; - repeated string presented_initial_gsa_compact_jwt = 2; - repeated bytes original_lease_evidence_utf8 = 3; -} - -message ConfirmOriginalNewGameplayAdmissionRequest { - repeated uint32 schema_version = 1; - repeated string presented_initial_gsa_compact_jwt = 2; - repeated bytes original_lease_evidence_utf8 = 3; -} - -message OriginalNewAdmissionConfirmationResponse { - repeated uint32 schema_version = 1; - repeated string lineage_uuid = 2; - repeated string original_lease_uuid = 3; - repeated string original_lease_fence = 4; - repeated string admission_at_ms = 5; - repeated string continuity_expires_at_ms = 6; - repeated string confirmation_readback_sha256 = 7; -} - enum AccountGameplayAdmissionLeaseState { ACCOUNT_GAMEPLAY_ADMISSION_LEASE_STATE_UNSPECIFIED = 0; ACCOUNT_GAMEPLAY_ADMISSION_LEASE_STATE_PENDING = 1; @@ -99,7 +66,7 @@ enum AccountGameplayAdmissionLeaseState { ACCOUNT_GAMEPLAY_ADMISSION_LEASE_STATE_ABORTED = 3; } -// Lease operations return the same closed original-operation readback. Repeated fields preserve +// All four methods return the same closed original-operation readback. Repeated fields preserve // absence and duplicates for receiver validation. The lease bytes remain unchanged and complete. message AccountGameplayAdmissionLeaseResponse { repeated uint32 schema_version = 1; @@ -109,25 +76,6 @@ message AccountGameplayAdmissionLeaseResponse { // ABORTED-only pending cleanup obligation; this never reports cleanup completion. repeated string orphan_cleanup_uuid = 5; repeated AccountGameplayAdmissionOriginalAckReceiptEvidence original_ack_receipt = 6; - // Present only on IssueOriginalNewGameplayCredential. Kept separate so closed original lease - // evidence and its committed receipt remain byte-for-byte unchanged. - repeated OriginalNewGameplayCredentialResult original_new_credential = 7; -} - -// Protected Account result transported only to the authenticated Game Session service. The -// codec and recipient keep diagnostics redacted; the opaque handle is never client-visible. -message OriginalNewGameplayCredentialResult { - repeated uint32 schema_version = 1; - repeated string signed_bound_gsa_compact_jwt = 2; - repeated bytes opaque_rebind_handle = 3; - repeated string lineage_uuid = 4; - repeated string token_jti_uuid = 5; - repeated string token_sha256 = 6; - repeated string issuance_fence = 7; - repeated string original_lease_uuid = 8; - repeated string original_lease_fence = 9; - repeated string original_ack_receipt_xid = 10; - repeated string checkpoints_sha256 = 11; } // Complete durable AccountGameplayAdmissionOriginalAckReceipt shape. The operation identity and diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/AccountOriginalNewFinalAdmissionReadClient.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/AccountOriginalNewFinalAdmissionReadClient.java deleted file mode 100644 index e7ce40ef76..0000000000 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/AccountOriginalNewFinalAdmissionReadClient.java +++ /dev/null @@ -1,154 +0,0 @@ -package net.firedevops.firemud.accountservice.client; - -import java.util.Objects; -import java.util.UUID; - -/** - * Protected Account-to-Game-Session boundary for the actual ORIGINAL final-admission readback. - * - *

Account calls this source after its original credential has been issued. Implementations must - * perform the authenticated same-namespace Game Session final-result read themselves; no RPC - * caller-provided timestamp, boolean, candidate, or receipt can construct this result for Account. - * Until the canonical authenticated final-result reader is wired, no implementation is supplied and - * Account fails closed. - */ -@FunctionalInterface -public interface AccountOriginalNewFinalAdmissionReadClient { - AuthenticatedFinalAdmissionReadback readActualOriginalFinalAdmission( - ExpectedOriginalAdmission expected); - - /** Complete immutable Account anchors supplied to the protected Game Session read. */ - record ExpectedOriginalAdmission( - UUID requestId, - UUID accountId, - UUID tenantId, - UUID sessionId, - UUID bindingDecisionId, - UUID originalLeaseId, - long originalLeaseFence, - String originalLeaseEvidenceSha256, - UUID lineageId, - UUID tokenJti, - String tokenSha256, - long tokenGeneration, - long issuanceFence, - String bindingScopeSha256, - String membershipBaselineSha256, - String checkpointsSha256, - String rebindHandleSha256) { - public ExpectedOriginalAdmission { - requireUuid(requestId); - requireUuid(accountId); - requireUuid(tenantId); - requireUuid(sessionId); - requireUuid(bindingDecisionId); - requireUuid(originalLeaseId); - requireUuid(lineageId); - requireUuid(tokenJti); - requireSha256(originalLeaseEvidenceSha256); - requireSha256(tokenSha256); - requireSha256(bindingScopeSha256); - requireSha256(membershipBaselineSha256); - requireSha256(checkpointsSha256); - requireSha256(rebindHandleSha256); - if (originalLeaseFence <= 0L - || tokenGeneration != 1L - || issuanceFence <= 0L - || lineageId.equals(tokenJti)) throw invalid(); - } - - @Override - public String toString() { - return "ExpectedOriginalAdmission[redacted]"; - } - } - - /** - * Typed response only constructible by the protected reader implementation. Account exact- - * compares every anchor and checks the canonical continuity deadline before persisting it. - */ - final class AuthenticatedFinalAdmissionReadback { - private final int sessionSchemaVersion; - private final String admissionState; - private final ExpectedOriginalAdmission anchors; - private final long admissionAtMillis; - private final long continuityExpiresAtMillis; - private final long canonicalSessionDurationMillis; - private final String canonicalReadbackSha256; - - AuthenticatedFinalAdmissionReadback( - int sessionSchemaVersion, - String admissionState, - ExpectedOriginalAdmission anchors, - long admissionAtMillis, - long continuityExpiresAtMillis, - long canonicalSessionDurationMillis, - String canonicalReadbackSha256) { - this.sessionSchemaVersion = sessionSchemaVersion; - this.admissionState = Objects.requireNonNull(admissionState); - this.anchors = Objects.requireNonNull(anchors); - this.admissionAtMillis = admissionAtMillis; - this.continuityExpiresAtMillis = continuityExpiresAtMillis; - this.canonicalSessionDurationMillis = canonicalSessionDurationMillis; - this.canonicalReadbackSha256 = canonicalReadbackSha256; - requireSha256(canonicalReadbackSha256); - long expectedExpiry; - try { - expectedExpiry = Math.addExact(admissionAtMillis, canonicalSessionDurationMillis); - } catch (ArithmeticException malformed) { - throw invalid(); - } - if (sessionSchemaVersion != 2 - || !"COMPLETE".equals(admissionState) - || admissionAtMillis <= 0L - || canonicalSessionDurationMillis <= 0L - || continuityExpiresAtMillis != expectedExpiry) throw invalid(); - } - - public int sessionSchemaVersion() { - return sessionSchemaVersion; - } - - public String admissionState() { - return admissionState; - } - - public ExpectedOriginalAdmission anchors() { - return anchors; - } - - public long admissionAtMillis() { - return admissionAtMillis; - } - - public long continuityExpiresAtMillis() { - return continuityExpiresAtMillis; - } - - public long canonicalSessionDurationMillis() { - return canonicalSessionDurationMillis; - } - - public String canonicalReadbackSha256() { - return canonicalReadbackSha256; - } - - @Override - public String toString() { - return "AuthenticatedFinalAdmissionReadback[redacted]"; - } - } - - private static void requireUuid(UUID value) { - Objects.requireNonNull(value); - if (value.version() != 4 || value.variant() != 2) throw invalid(); - } - - private static void requireSha256(String value) { - if (value == null || !value.matches("[0-9a-f]{64}")) throw invalid(); - } - - private static IllegalArgumentException invalid() { - return new IllegalArgumentException("Protected original final-admission readback is malformed"); - } -} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountGameplayTokenIdentityFence.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountGameplayTokenIdentityFence.java index 98809bde8e..4f228b4732 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountGameplayTokenIdentityFence.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountGameplayTokenIdentityFence.java @@ -43,36 +43,13 @@ public record TokenIdentity( UUID tokenJti, long notBeforeEpochSecond, long tokenGeneration, - long issuanceFence, - SourceKind sourceKind) { - public TokenIdentity( - UUID accountId, - UUID operationId, - UUID issuanceRequestId, - String tokenSha256, - UUID tokenJti, - long notBeforeEpochSecond, - long tokenGeneration, - long issuanceFence) { - this( - accountId, - operationId, - issuanceRequestId, - tokenSha256, - tokenJti, - notBeforeEpochSecond, - tokenGeneration, - issuanceFence, - SourceKind.LOGIN); - } - + long issuanceFence) { public TokenIdentity { requireUuid(accountId); requireUuid(operationId); requireUuid(issuanceRequestId); requireUuid(tokenJti); requireDigest(tokenSha256); - Objects.requireNonNull(sourceKind); if (notBeforeEpochSecond <= 0L || tokenGeneration <= 0L || issuanceFence <= 0L) { throw new IllegalArgumentException("Positive exact token identity metadata required"); } @@ -84,12 +61,6 @@ public String toString() { } } - /** Distinguishes original unscoped LOGIN rows from fresh tenant-bound ORIGINAL-NEW lineages. */ - public enum SourceKind { - LOGIN, - ORIGINAL_NEW - } - private static void requireUuid(UUID value) { if (value == null || value.version() != 4 || value.variant() != 2) { throw new IllegalArgumentException("Canonical UUIDv4 required"); diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptCommitExecutor.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptCommitExecutor.java index 12f1484898..a3c6e2569a 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptCommitExecutor.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptCommitExecutor.java @@ -1,7 +1,6 @@ package net.firedevops.firemud.accountservice.repository; import java.sql.Connection; -import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; @@ -51,12 +50,13 @@ AccountGameplayAdmissionOriginalAckReceipt confirm( // row. rejectAmbient(); var read = - creation.inserted() - ? execute( - new ReceiptTransactionManager(dataSource), - repository -> - repository.readExact(acknowledgement.evidence(), acknowledgement.decisionId())) - : read(acknowledgement.evidence(), acknowledgement.decisionId()); + execute( + new ReceiptTransactionManager(dataSource), + repository -> + creation.inserted() + ? repository.readExact(acknowledgement.evidence(), acknowledgement.decisionId()) + : repository.readDurably( + acknowledgement.evidence(), acknowledgement.decisionId())); validate(read, acknowledgement.evidence(), acknowledgement.decisionId()); if (!created.equals(read)) throw denied(); return read; @@ -67,67 +67,14 @@ AccountGameplayAdmissionOriginalAckReceipt read( Objects.requireNonNull(evidence); Objects.requireNonNull(decisionId); rejectAmbient(); - var pending = - execute( - new ReceiptTransactionManager(dataSource), - repository -> repository.captureHistorical(evidence, decisionId)); - validate(pending.receipt(), evidence, decisionId); - // Capture completion is not proof of original timing or durability. Observe actual durable - // coverage of the exact SQL-issued upper fence, after releasing the capture's row locks. - awaitFrozenFenceCoverage(pending); - rejectAmbient(); var receipt = execute( new ReceiptTransactionManager(dataSource), - repository -> repository.readExact(evidence, decisionId)); + repository -> repository.readDurably(evidence, decisionId)); validate(receipt, evidence, decisionId); - if (!pending.receipt().equals(receipt)) throw denied(); return receipt; } - private void awaitFrozenFenceCoverage( - AccountGameplayAdmissionOriginalAckReceiptRepository.PendingHistoricalReceipt pending) { - rejectAmbient(); - try (Connection connection = dataSource.getConnection()) { - if (!connection.getAutoCommit() - || !"PostgreSQL".equals(connection.getMetaData().getDatabaseProductName())) - throw denied(); - try (PreparedStatement statement = - connection.prepareStatement( - "SELECT current_setting('server_version_num')::integer, pg_is_in_recovery(), " - + "current_setting('fsync'), pg_current_wal_flush_lsn() >= ?::pg_lsn")) { - statement.setQueryTimeout(1); - statement.setString(1, pending.walUpperFence()); - for (int observation = 0; observation < 50; observation++) { - boolean covered; - try (ResultSet result = statement.executeQuery()) { - if (!result.next()) throw denied(); - int version = result.getInt(1); - if (version < 180000 - || version >= 190000 - || result.getBoolean(2) - || !"on".equals(result.getString(3))) throw denied(); - covered = result.getBoolean(4); - if (result.wasNull() || result.next()) throw denied(); - } - if (covered) return; - if (observation < 49) { - try { - Thread.sleep(10L); - } catch (InterruptedException interrupted) { - Thread.currentThread().interrupt(); - throw denied(); - } - } - } - } - } catch (SQLException failure) { - throw new TransactionSystemException("Account receipt WAL coverage unavailable", failure); - } - throw new IllegalStateException( - "Original Account acknowledgement receipt WAL coverage unavailable"); - } - private static void validate( AccountGameplayAdmissionOriginalAckReceipt receipt, AccountGameplayAdmissionLeaseEvidence evidence, diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptRepository.java index b79d4f2ecc..ea0df8aeb8 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptRepository.java @@ -72,9 +72,7 @@ Creation create(OriginalCommitAcknowledgement acknowledgement) { return new Creation(receipt, wasInserted); } - /** - * Exact storage-only read after the sibling owner proved receipt COMMIT or frozen WAL coverage. - */ + /** Exact storage-only read for the sibling owner after it observed successful receipt COMMIT. */ AccountGameplayAdmissionOriginalAckReceipt readExact( AccountGameplayAdmissionLeaseEvidence evidence, UUID decisionId) { requireWritableSerializableTransaction(); @@ -84,24 +82,6 @@ AccountGameplayAdmissionOriginalAckReceipt readExact( return decode(row, exactCommitted(evidence, decisionId)); } - /** Captures exact pending evidence; this method alone proves no WAL durability. */ - PendingHistoricalReceipt captureHistorical( - AccountGameplayAdmissionLeaseEvidence evidence, UUID decisionId) { - requireWritableSerializableTransaction(); - UUID requestId = validateRequest(evidence, decisionId); - Record row = - dsl.fetchOne( - "SELECT (capture.captured_receipt).*, capture.wal_upper_fence::text AS wal_upper_fence " - + "FROM account_gameplay_admission_capture_original_ack_receipt(?, ?, ?) capture", - requestId, - evidence.sha256(), - decisionId); - if (row == null) throw unavailable(); - return new PendingHistoricalReceipt( - decode(row, exactCommitted(evidence, decisionId)), - required(row, "wal_upper_fence", String.class)); - } - /** Proves historical independent receipt durability without changing its original evidence. */ AccountGameplayAdmissionOriginalAckReceipt readDurably( AccountGameplayAdmissionLeaseEvidence evidence, UUID decisionId) { @@ -184,28 +164,6 @@ private static IllegalStateException unavailable() { "Original Account admission acknowledgement receipt unavailable"); } - /** Non-wire SQL-issued pending capability. Only captureHistorical can stamp its frozen fence. */ - static final class PendingHistoricalReceipt { - private final AccountGameplayAdmissionOriginalAckReceipt receipt; - private final String walUpperFence; - - private PendingHistoricalReceipt( - AccountGameplayAdmissionOriginalAckReceipt receipt, String walUpperFence) { - this.receipt = Objects.requireNonNull(receipt); - this.walUpperFence = Objects.requireNonNull(walUpperFence); - if (!walUpperFence.matches("(0|[1-9A-F][0-9A-F]{0,7})/(0|[1-9A-F][0-9A-F]{0,7})") - || "0/0".equals(walUpperFence)) throw unavailable(); - } - - AccountGameplayAdmissionOriginalAckReceipt receipt() { - return receipt; - } - - String walUpperFence() { - return walUpperFence; - } - } - record Creation(AccountGameplayAdmissionOriginalAckReceipt receipt, boolean inserted) { Creation { Objects.requireNonNull(receipt); diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayTokenIdentityFenceRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayTokenIdentityFenceRepository.java index 538a94f2d0..9f85b30fa6 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayTokenIdentityFenceRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayTokenIdentityFenceRepository.java @@ -8,7 +8,6 @@ import java.util.Objects; import java.util.UUID; import net.firedevops.firemud.accountservice.dto.AccountGameplayTokenIdentityFence; -import net.firedevops.firemud.accountservice.dto.AccountGameplayTokenIdentityFence.SourceKind; import net.firedevops.firemud.accountservice.dto.AccountGameplayTokenIdentityFence.State; import net.firedevops.firemud.accountservice.dto.AccountGameplayTokenIdentityFence.TokenIdentity; import org.jooq.DSLContext; @@ -29,7 +28,7 @@ public class AccountGameplayTokenIdentityFenceRepository { private static final String TABLE = "account_gameplay_token_identity_fences"; private static final String COLUMNS = "account_uuid, operation_id, issuance_request_id, token_hash, token_jti, " - + "not_before_epoch_second, token_generation, issuance_fence, source_kind, token_identity_fence, " + + "not_before_epoch_second, token_generation, issuance_fence, token_identity_fence, " + "state, revocation_request_id, revocation_digest"; private final DSLContext dsl; @@ -66,14 +65,13 @@ public AccountGameplayTokenIdentityFence requireActiveForUpdate(TokenIdentity id AccountGameplayTokenIdentityFence registerCommittedIssuance(TokenIdentity identity) { requireTransaction(); lockAccountForUpdate(identity.accountId()); - if (identity.sourceKind() != SourceKind.LOGIN) throw new TokenFenceUnavailableException(); dsl.execute( "INSERT INTO " + TABLE + " (account_uuid, operation_id, issuance_request_id, token_hash, " - + "token_jti, not_before_epoch_second, token_generation, issuance_fence, source_kind) " + + "token_jti, not_before_epoch_second, token_generation, issuance_fence) " + "SELECT account_uuid, operation_id, request_id, token_hash, token_jti, " - + "not_before_epoch_second, token_generation, issuance_fence, 'LOGIN' " + + "not_before_epoch_second, token_generation, issuance_fence " + "FROM account_gameplay_delegation_issuance_operations " + "WHERE operation_id = ? AND request_id = ? AND account_uuid = ? " + "AND token_hash = ? AND token_jti = ? AND not_before_epoch_second = ? " @@ -90,35 +88,6 @@ AccountGameplayTokenIdentityFence registerCommittedIssuance(TokenIdentity identi return requireActiveForUpdate(identity); } - /** Registers a committed ORIGINAL-NEW lineage in the same Account token-identity fence owner. */ - AccountGameplayTokenIdentityFence registerCommittedOriginalNewIssuance(TokenIdentity identity) { - requireTransaction(); - if (identity.sourceKind() != SourceKind.ORIGINAL_NEW) - throw new TokenFenceUnavailableException(); - lockAccountForUpdate(identity.accountId()); - dsl.execute( - "INSERT INTO " - + TABLE - + " (account_uuid, operation_id, issuance_request_id, token_hash, token_jti, " - + "not_before_epoch_second, token_generation, issuance_fence, source_kind) " - + "SELECT account_uuid, operation_id, request_id, token_hash, token_jti, " - + "not_before_epoch_second, token_generation, issuance_fence, 'ORIGINAL_NEW' " - + "FROM account_original_new_bound_gameplay_issuances " - + "WHERE operation_id = ? AND request_id = ? AND account_uuid = ? " - + "AND token_hash = ? AND token_jti = ? AND not_before_epoch_second = ? " - + "AND token_generation = ? AND issuance_fence = ? AND status = 'COMMITTED' " - + "ON CONFLICT (operation_id) DO NOTHING", - identity.operationId(), - identity.issuanceRequestId(), - identity.accountId(), - identity.tokenSha256(), - identity.tokenJti(), - identity.notBeforeEpochSecond(), - identity.tokenGeneration(), - identity.issuanceFence()); - return requireActiveForUpdate(identity); - } - /** Independent metadata readback, including the source COMMITTED identity, never registration. */ AccountGameplayTokenIdentityFence requireActiveReadback(TokenIdentity identity) { AccountGameplayTokenIdentityFence fence = requireExact(identity, false); @@ -175,10 +144,7 @@ public static String revocationDigest(TokenIdentity identity, UUID requestId) { } // All fields have fixed/canonical syntax, so the domain-separated framing is unambiguous. String input = - (identity.sourceKind() == SourceKind.LOGIN - ? "account-gameplay-token-revocation-intent/v1" - : "account-original-new-bound-gameplay-token-revocation-intent/v1") - + "\n" + "account-gameplay-token-revocation-intent/v1\n" + requestId + "\n" + identity.accountId() @@ -208,11 +174,10 @@ public static String revocationDigest(TokenIdentity identity, UUID requestId) { } private AccountGameplayTokenIdentityFence requireExact(TokenIdentity identity, boolean lock) { - if (identity.sourceKind() == SourceKind.LOGIN - && dsl.fetchOne( - "SELECT request_id FROM account_initial_gameplay_login_disposals WHERE request_id = ?", - identity.issuanceRequestId()) - != null) throw new TokenRevokedException(); + if (dsl.fetchOne( + "SELECT request_id FROM account_initial_gameplay_login_disposals WHERE request_id = ?", + identity.issuanceRequestId()) + != null) throw new TokenRevokedException(); return requireExactStoredIdentity(identity, lock); } @@ -231,15 +196,10 @@ private AccountGameplayTokenIdentityFence requireExactStoredIdentity( if (row == null) throw new TokenFenceUnavailableException(); AccountGameplayTokenIdentityFence fence = decode(row); if (!identity.equals(fence.identity())) throw new TokenFenceUnavailableException(); - String sourceTable = - identity.sourceKind() == SourceKind.LOGIN - ? "account_gameplay_delegation_issuance_operations" - : "account_original_new_bound_gameplay_issuances"; Record source = dsl.fetchOne( - "SELECT operation_id FROM " - + sourceTable - + " WHERE operation_id = ? AND request_id = ? AND account_uuid = ? AND token_hash = ? " + "SELECT operation_id FROM account_gameplay_delegation_issuance_operations " + + "WHERE operation_id = ? AND request_id = ? AND account_uuid = ? AND token_hash = ? " + "AND token_jti = ? AND not_before_epoch_second = ? AND token_generation = ? " + "AND issuance_fence = ? AND status = 'COMMITTED'", identity.operationId(), @@ -258,15 +218,10 @@ private static AccountGameplayTokenIdentityFence decode(Record row) { try { return new AccountGameplayTokenIdentityFence( new TokenIdentity( - row.get("account_uuid", UUID.class), - row.get("operation_id", UUID.class), - row.get("issuance_request_id", UUID.class), - row.get("token_hash", String.class), - row.get("token_jti", UUID.class), - row.get("not_before_epoch_second", Long.class), - row.get("token_generation", Long.class), - row.get("issuance_fence", Long.class), - SourceKind.valueOf(row.get("source_kind", String.class))), + row.get("account_uuid", UUID.class), row.get("operation_id", UUID.class), + row.get("issuance_request_id", UUID.class), row.get("token_hash", String.class), + row.get("token_jti", UUID.class), row.get("not_before_epoch_second", Long.class), + row.get("token_generation", Long.class), row.get("issuance_fence", Long.class)), row.get("token_identity_fence", Long.class), State.valueOf(row.get("state", String.class)), row.get("revocation_request_id", UUID.class), diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountOriginalNewBoundGameplayCredentialOwner.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountOriginalNewBoundGameplayCredentialOwner.java deleted file mode 100644 index 651e671521..0000000000 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountOriginalNewBoundGameplayCredentialOwner.java +++ /dev/null @@ -1,1198 +0,0 @@ -package net.firedevops.firemud.accountservice.repository; - -import io.grpc.Status; -import java.nio.ByteBuffer; -import java.nio.charset.StandardCharsets; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.security.SecureRandom; -import java.time.Clock; -import java.time.Instant; -import java.util.Arrays; -import java.util.HexFormat; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; -import java.util.UUID; -import javax.sql.DataSource; -import net.firedevops.firemud.accountservice.client.AccountOriginalNewFinalAdmissionReadClient; -import net.firedevops.firemud.accountservice.client.AccountOriginalNewFinalAdmissionReadClient.AuthenticatedFinalAdmissionReadback; -import net.firedevops.firemud.accountservice.client.AccountOriginalNewFinalAdmissionReadClient.ExpectedOriginalAdmission; -import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionLeaseOperation; -import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionLeaseOperation.State; -import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionOriginalAckReceipt; -import net.firedevops.firemud.accountservice.dto.AccountGameplayTokenIdentityFence.SourceKind; -import net.firedevops.firemud.accountservice.dto.AccountGameplayTokenIdentityFence.TokenIdentity; -import net.firedevops.firemud.accountservice.repository.AccountOriginalNewBoundGameplayIssuanceRepository.Genesis; -import net.firedevops.firemud.accountservice.service.session.AccountGameplayAdmissionCallerVerifier; -import net.firedevops.firemud.accountservice.service.session.AccountGameplayAdmissionCallerVerifier.VerifiedCaller; -import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationRedisClient; -import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationRedisClient.PendingRegistrationReceipt; -import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationSigner; -import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationSigner.OriginalNewBoundSignedCandidate; -import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationTokenRegistry; -import net.firedevops.firemud.accountservice.service.session.AccountResponseEnvelopeCryptography; -import net.firedevops.firemud.accountservice.service.session.AccountResponseEnvelopeCryptography.Binding; -import net.firedevops.firemud.accountservice.service.session.AccountResponseEnvelopeCryptography.EncryptedResponseEnvelope; -import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; -import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseGrpcCodec; -import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseGrpcCodec.OriginalNewCredential; -import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; -import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; -import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; -import net.firedevops.firemud.common.security.GameSessionAccountDelegationRegistryRecord; -import net.firedevops.firemud.common.security.GameSessionAccountDelegationRegistryRecord.AccountAuthoritySnapshot; -import net.firedevops.firemud.common.security.GameSessionAccountDelegationRegistryRecord.EvidenceBundleReference; -import net.firedevops.firemud.common.security.GameSessionAccountDelegationRegistryRecord.IssuanceBinding; -import net.firedevops.firemud.common.security.SessionContext; -import org.jooq.DSLContext; -import org.jooq.SQLDialect; -import org.jooq.impl.DSL; -import org.springframework.jdbc.datasource.ConnectionHolder; -import org.springframework.jdbc.datasource.DataSourceTransactionManager; -import org.springframework.transaction.TransactionDefinition; -import org.springframework.transaction.support.TransactionSynchronizationManager; -import org.springframework.transaction.support.TransactionTemplate; -import tools.jackson.databind.json.JsonMapper; - -/** - * Manually composed Account owner for the first bound ORIGINAL-NEW gameplay credential. - * - *

The caller's LOGIN token is only authentication for this operation. The new token and its - * opaque handle are anchored to one immutable original NEW lease plus its separately durable ACK. - * This owner does not install a Game Session admission, activate a session, or implement REBIND. - */ -public final class AccountOriginalNewBoundGameplayCredentialOwner { - private static final String GAME_SESSION_SERVICE = "game-session-service"; - private static final String ENVELOPE_OPERATION = "original-new-bound-gameplay-credential"; - private static final JsonMapper JSON = JsonMapper.builder().build(); - - private final DataSource dataSource; - private final String workloadNamespace; - private final AccountGameplayAdmissionCallerVerifier callerVerifier; - private final AccountGameplayAdmissionOriginalAckReceiptCommitExecutor receiptExecutor; - private final AccountGameplayDelegationSigner signer; - private final AccountGameplayDelegationTokenRegistry tokenRegistry; - private final AccountResponseEnvelopeCryptography responseCryptography; - private final AccountOriginalNewFinalAdmissionReadClient finalAdmissionReadClient; - private final Clock clock; - private final SecureRandom secureRandom; - - public AccountOriginalNewBoundGameplayCredentialOwner( - DataSource dataSource, - String workloadNamespace, - AccountGameplayAdmissionCallerVerifier callerVerifier, - AccountGameplayDelegationSigner signer, - AccountGameplayDelegationTokenRegistry tokenRegistry, - AccountResponseEnvelopeCryptography responseCryptography, - Clock clock) { - this( - dataSource, - workloadNamespace, - callerVerifier, - signer, - tokenRegistry, - responseCryptography, - clock, - null, - new SecureRandom()); - } - - /** Explicitly protected final-admission reader; absent reader leaves confirmation fail-closed. */ - public AccountOriginalNewBoundGameplayCredentialOwner( - DataSource dataSource, - String workloadNamespace, - AccountGameplayAdmissionCallerVerifier callerVerifier, - AccountGameplayDelegationSigner signer, - AccountGameplayDelegationTokenRegistry tokenRegistry, - AccountResponseEnvelopeCryptography responseCryptography, - Clock clock, - AccountOriginalNewFinalAdmissionReadClient finalAdmissionReadClient) { - this( - dataSource, - workloadNamespace, - callerVerifier, - signer, - tokenRegistry, - responseCryptography, - clock, - Objects.requireNonNull(finalAdmissionReadClient), - new SecureRandom()); - } - - AccountOriginalNewBoundGameplayCredentialOwner( - DataSource dataSource, - String workloadNamespace, - AccountGameplayAdmissionCallerVerifier callerVerifier, - AccountGameplayDelegationSigner signer, - AccountGameplayDelegationTokenRegistry tokenRegistry, - AccountResponseEnvelopeCryptography responseCryptography, - Clock clock, - SecureRandom secureRandom) { - this( - dataSource, - workloadNamespace, - callerVerifier, - signer, - tokenRegistry, - responseCryptography, - clock, - null, - secureRandom); - } - - private AccountOriginalNewBoundGameplayCredentialOwner( - DataSource dataSource, - String workloadNamespace, - AccountGameplayAdmissionCallerVerifier callerVerifier, - AccountGameplayDelegationSigner signer, - AccountGameplayDelegationTokenRegistry tokenRegistry, - AccountResponseEnvelopeCryptography responseCryptography, - Clock clock, - AccountOriginalNewFinalAdmissionReadClient finalAdmissionReadClient, - SecureRandom secureRandom) { - this.dataSource = Objects.requireNonNull(dataSource, "Account DataSource is required"); - if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { - throw new IllegalArgumentException("Canonical Account workload namespace required"); - } - this.workloadNamespace = workloadNamespace; - this.callerVerifier = Objects.requireNonNull(callerVerifier); - this.receiptExecutor = new AccountGameplayAdmissionOriginalAckReceiptCommitExecutor(dataSource); - this.signer = Objects.requireNonNull(signer); - this.tokenRegistry = Objects.requireNonNull(tokenRegistry); - this.responseCryptography = Objects.requireNonNull(responseCryptography); - this.finalAdmissionReadClient = finalAdmissionReadClient; - this.clock = Objects.requireNonNull(clock); - this.secureRandom = Objects.requireNonNull(secureRandom); - } - - /** Issues once after the durable original COMMITTED lease and ACK are independently read back. */ - public OriginalNewCredential issue( - String presentedInitialGsACompactJwt, AccountGameplayAdmissionLeaseEvidence requestedLease) { - GrpcPeerIdentity peer = requireGameSessionCaller(); - requireNoAmbientSql(); - Objects.requireNonNull(requestedLease, "Original NEW lease is required"); - VerifiedCaller caller = verifyCaller(presentedInitialGsACompactJwt, peer); - requireCallerMatchesLease(caller, peer, requestedLease); - - SourceRead initial = readCurrentOriginalSource(caller, requestedLease); - if (initial.operation().state() != State.COMMITTED - || initial.operation().bindingDecisionId() == null) throw unavailable(); - AccountGameplayAdmissionOriginalAckReceipt receipt = - receiptExecutor.read(requestedLease, initial.operation().bindingDecisionId()); - requireExactReceipt(receipt, initial.operation(), requestedLease); - - long nowSeconds = clock.instant().getEpochSecond(); - if (nowSeconds <= 0L) throw unavailable(); - UUID newLineageId = UUID.randomUUID(); - UUID newTokenJti = UUID.randomUUID(); - while (newTokenJti.equals(newLineageId) || newTokenJti.equals(caller.identity().tokenJti())) { - newTokenJti = UUID.randomUUID(); - } - UUID frozenNewTokenJti = newTokenJti; - long expirySeconds; - try { - expirySeconds = - Math.addExact(nowSeconds, GameSessionAccountDelegationProfile.MAX_TOKEN_LIFETIME_SECONDS); - } catch (ArithmeticException malformed) { - throw unavailable(); - } - - Genesis genesis = - inWritableSerializableTransaction( - dsl -> - new AccountOriginalNewBoundGameplayIssuanceRepository(dsl) - .beginGenesis( - requestedLease, - receipt, - newLineageId, - frozenNewTokenJti, - nowSeconds, - nowSeconds, - expirySeconds)); - - if (genesis.tokenHash() == null) { - genesis = signAndPersistCandidate(caller, requestedLease, receipt, genesis); - } - if (genesis.tokenHash() == null || genesis.encryptedResultEnvelopeBytes() == null) { - throw unavailable(); - } - - final String receiptDigest; - if (genesis.status() == AccountOriginalNewBoundGameplayIssuanceRepository.Status.COMMITTED) { - receiptDigest = genesis.committedRegistryReceiptSha256(); - if (receiptDigest == null) throw unavailable(); - if (genesis.confirmedAdmissionAtMillis() != null) { - tokenRegistry.requireExactOriginalNewActiveRecord(genesis); - } else { - // Reasserts the same immutable PENDING bytes and deadline. The original SQL receipt digest - // remains frozen; this retry does not replace it with a later WAITAOF observation. - tokenRegistry.registerOriginalNewPending(genesis); - } - } else { - PendingRegistrationReceipt redisReceipt = tokenRegistry.registerOriginalNewPending(genesis); - receiptDigest = pendingRegistryReceiptDigest(redisReceipt); - } - - // Network registration has completed with no SQL lock held. Re-authenticate the original - // caller, then atomically commit this exact issuance and create its independent token fence. - VerifiedCaller currentCaller = verifyCaller(presentedInitialGsACompactJwt, peer); - if (!AccountGameplayDelegationIssuanceRepository.CommittedCandidateVerificationData - .hasSameOwnerEvidence(caller.currentCandidate(), currentCaller.currentCandidate())) { - throw unavailable(); - } - final Genesis exactGenesisForCommit = genesis; - Genesis committed = - inWritableSerializableTransaction( - dsl -> { - SourceRead current = readCurrentOriginalSource(dsl, currentCaller, requestedLease); - requireSameOriginalOperation(initial.operation(), current.operation()); - AccountOriginalNewBoundGameplayIssuanceRepository issuance = - new AccountOriginalNewBoundGameplayIssuanceRepository(dsl); - Genesis stored = issuance.readByLease(leaseId(requestedLease)); - requireSameGenesisIdentity(exactGenesisForCommit, stored); - Genesis committedResult = issuance.commit(stored, receiptDigest); - var fenceRepository = new AccountGameplayTokenIdentityFenceRepository(dsl); - var tokenIdentity = - new TokenIdentity( - committedResult.accountId(), - committedResult.lineageId(), - committedResult.requestId(), - committedResult.tokenHash(), - committedResult.tokenJti(), - committedResult.notBeforeEpochSecond(), - committedResult.tokenGeneration(), - committedResult.issuanceFence(), - SourceKind.ORIGINAL_NEW); - fenceRepository.registerCommittedOriginalNewIssuance(tokenIdentity); - return committedResult; - }); - - // The caller receives the result only after Account's issuance row and active identity fence - // committed together. Opening requires a fresh source and exact active-fence readback. - return openCommittedResult(currentCaller, requestedLease, receipt, committed); - } - - /** Full protected RPC result, with the original lease and ACK carrier left unchanged. */ - public net.firedevops.firemud.account.v1.AccountGameplayAdmissionLeaseResponse issue( - AccountGameplayAdmissionLeaseGrpcCodec.OriginalNewCredentialRequest request) { - Objects.requireNonNull(request, "Parsed ORIGINAL-NEW credential request is required"); - AccountGameplayAdmissionLeaseEvidence lease = request.originalLeaseEvidence(); - SourceRead source = readCurrentOriginalSourceAfterAuthentication(request, lease); - if (source.operation().state() != State.COMMITTED - || source.operation().bindingDecisionId() == null) throw unavailable(); - AccountGameplayAdmissionOriginalAckReceipt receipt = - receiptExecutor.read(lease, source.operation().bindingDecisionId()); - requireExactReceipt(receipt, source.operation(), lease); - OriginalNewCredential credential = issue(request.presentedInitialGsACompactJwt(), lease); - try { - var ack = - AccountGameplayAdmissionLeaseGrpcCodec.OriginalAckReceiptEvidence.fromFields( - receipt.schemaVersion(), - receipt.requestId(), - receipt.accountId(), - receipt.leaseId(), - receipt.leaseFence(), - receipt.evidenceSha256(), - receipt.bindingDecisionId(), - receipt.expiresAtMs(), - receipt.finalizationXid(), - receipt.committedBeforeMs(), - receipt.receiptXid()); - return AccountGameplayAdmissionLeaseGrpcCodec.toIssueOriginalNewCredentialResponse( - request, - lease, - AccountGameplayAdmissionLeaseGrpcCodec.State.COMMITTED, - source.operation().bindingDecisionId(), - ack, - credential); - } finally { - credential.close(); - } - } - - private SourceRead readCurrentOriginalSourceAfterAuthentication( - AccountGameplayAdmissionLeaseGrpcCodec.OriginalNewCredentialRequest request, - AccountGameplayAdmissionLeaseEvidence lease) { - GrpcPeerIdentity peer = requireGameSessionCaller(); - VerifiedCaller caller = verifyCaller(request.presentedInitialGsACompactJwt(), peer); - requireCallerMatchesLease(caller, peer, lease); - return readCurrentOriginalSource(caller, lease); - } - - /** - * Confirms only an actual Game Session final-admission readback fetched by Account's protected - * client. The caller supplies neither timestamps nor a proof object. No credential is reminted. - */ - public OriginalAdmissionConfirmation confirmOriginalFinalAdmission( - String presentedInitialGsACompactJwt, AccountGameplayAdmissionLeaseEvidence requestedLease) { - if (finalAdmissionReadClient == null) throw unavailable(); - GrpcPeerIdentity peer = requireGameSessionCaller(); - requireNoAmbientSql(); - VerifiedCaller caller = verifyCaller(presentedInitialGsACompactJwt, peer); - requireCallerMatchesLease(caller, peer, requestedLease); - SourceRead beforeRead = readCurrentOriginalSource(caller, requestedLease); - if (beforeRead.operation().state() != State.COMMITTED - || beforeRead.operation().bindingDecisionId() == null) throw unavailable(); - AccountGameplayAdmissionOriginalAckReceipt receipt = - receiptExecutor.read(requestedLease, beforeRead.operation().bindingDecisionId()); - requireExactReceipt(receipt, beforeRead.operation(), requestedLease); - Genesis beforeGenesis = - inWritableSerializableTransaction( - dsl -> { - SourceRead current = readCurrentOriginalSource(dsl, caller, requestedLease); - requireSameOriginalOperation(beforeRead.operation(), current.operation()); - Genesis stored = - new AccountOriginalNewBoundGameplayIssuanceRepository(dsl) - .readByLease(leaseId(requestedLease)); - if (stored == null - || stored.status() - != AccountOriginalNewBoundGameplayIssuanceRepository.Status.COMMITTED) { - throw unavailable(); - } - return stored; - }); - OriginalNewCredential storedCredential = - beforeGenesis.confirmedAdmissionAtMillis() == null - ? openFrozenCredentialForFinalAdmissionVerification( - caller, requestedLease, receipt, beforeGenesis) - : openCommittedResult(caller, requestedLease, receipt, beforeGenesis); - String storedCompactJwt = storedCredential.signedBoundGsACompactJwt(); - String boundTenantId = tenantId(requestedLease).toString(); - try { - Map boundTuple = - stringObjectMap(beforeGenesis.authorityTupleCanonicalBytes()); - Map boundMembership = - stringStringMap(beforeGenesis.membershipVersionCanonicalBytes()); - signer.verifyOriginalNewBoundCredential( - storedCompactJwt, - beforeGenesis, - beforeRead.accountAuthority(), - boundTenantId, - boundTuple, - boundMembership); - } finally { - storedCredential.close(); - } - ExpectedOriginalAdmission expected = expectedAdmission(requestedLease, beforeGenesis); - - if (beforeGenesis.confirmedAdmissionAtMillis() != null) { - long nowMillis = clock.millis(); - if (nowMillis <= 0L || nowMillis >= beforeGenesis.confirmedContinuityExpiresAtMillis()) - throw unavailable(); - VerifiedCaller currentCaller = verifyCaller(presentedInitialGsACompactJwt, peer); - if (!AccountGameplayDelegationIssuanceRepository.CommittedCandidateVerificationData - .hasSameOwnerEvidence(caller.currentCandidate(), currentCaller.currentCandidate())) { - throw unavailable(); - } - Genesis recovered = - inWritableSerializableTransaction( - dsl -> { - SourceRead current = readCurrentOriginalSource(dsl, currentCaller, requestedLease); - requireSameOriginalOperation(beforeRead.operation(), current.operation()); - AccountGameplayAdmissionOriginalAckReceipt durableReceipt = - new AccountGameplayAdmissionOriginalAckReceiptRepository( - dsl, new AccountGameplayAdmissionLeaseRepository(dsl)) - .readExact(requestedLease, current.operation().bindingDecisionId()); - // The receipt owner already proved independent durability outside this - // transaction. Re-read the immutable row here under current source locks. - requireExactReceipt(durableReceipt, current.operation(), requestedLease); - if (!receipt.equals(durableReceipt)) throw unavailable(); - var issuance = new AccountOriginalNewBoundGameplayIssuanceRepository(dsl); - Genesis exact = issuance.readByLease(leaseId(requestedLease)); - requireSameGenesisIdentity(beforeGenesis, exact); - if (exact.confirmedAdmissionAtMillis() == null - || !Objects.equals( - exact.confirmedAdmissionAtMillis(), - beforeGenesis.confirmedAdmissionAtMillis()) - || !Objects.equals( - exact.confirmedContinuityExpiresAtMillis(), - beforeGenesis.confirmedContinuityExpiresAtMillis()) - || !exact - .confirmationReadbackSha256() - .equals(beforeGenesis.confirmationReadbackSha256())) throw unavailable(); - new AccountGameplayTokenIdentityFenceRepository(dsl) - .requireActiveReadback(originalNewIdentity(exact)); - return exact; - }); - tokenRegistry.requireExactOriginalNewActiveRecord(recovered); - if (clock.millis() >= recovered.confirmedContinuityExpiresAtMillis()) throw unavailable(); - return new OriginalAdmissionConfirmation( - recovered.lineageId(), - recovered.leaseId(), - recovered.confirmedAdmissionAtMillis(), - recovered.confirmedContinuityExpiresAtMillis(), - recovered.confirmationReadbackSha256()); - } - - final AuthenticatedFinalAdmissionReadback finalReadback; - try { - finalReadback = - Objects.requireNonNull( - finalAdmissionReadClient.readActualOriginalFinalAdmission(expected)); - } catch (RuntimeException unavailable) { - throw unavailable(); - } - if (!expected.equals(finalReadback.anchors())) throw unavailable(); - long nowMillis = clock.millis(); - if (nowMillis <= 0L - || finalReadback.admissionAtMillis() > nowMillis - || nowMillis >= finalReadback.continuityExpiresAtMillis()) throw unavailable(); - - // Activation is Account-owned and happens only after the authenticated GS readback exists. - // If its reply is lost, the Redis CAS accepts only the same immutable active projection. - AccountGameplayDelegationRedisClient.OriginalNewActivationReadback activation = - tokenRegistry.activateOriginalNewCommittedPending(beforeGenesis); - requireActivationMatches(beforeGenesis, activation); - - VerifiedCaller currentCaller = verifyCaller(presentedInitialGsACompactJwt, peer); - if (!AccountGameplayDelegationIssuanceRepository.CommittedCandidateVerificationData - .hasSameOwnerEvidence(caller.currentCandidate(), currentCaller.currentCandidate())) { - throw unavailable(); - } - signer.verifyOriginalNewBoundCredential( - storedCompactJwt, - beforeGenesis, - beforeRead.accountAuthority(), - boundTenantId, - stringObjectMap(beforeGenesis.authorityTupleCanonicalBytes()), - stringStringMap(beforeGenesis.membershipVersionCanonicalBytes())); - String confirmationDigest = confirmationDigest(finalReadback, activation); - Genesis confirmed = - inWritableSerializableTransaction( - dsl -> { - SourceRead current = readCurrentOriginalSource(dsl, currentCaller, requestedLease); - requireSameOriginalOperation(beforeRead.operation(), current.operation()); - AccountGameplayAdmissionOriginalAckReceipt durableReceipt = - new AccountGameplayAdmissionOriginalAckReceiptRepository( - dsl, new AccountGameplayAdmissionLeaseRepository(dsl)) - .readExact(requestedLease, current.operation().bindingDecisionId()); - // Keep the independently proved receipt exact; this transaction supplies - // current source exclusion, not another historical durability attempt. - requireExactReceipt(durableReceipt, current.operation(), requestedLease); - if (!receipt.equals(durableReceipt)) throw unavailable(); - var issuance = new AccountOriginalNewBoundGameplayIssuanceRepository(dsl); - Genesis exact = issuance.readByLease(leaseId(requestedLease)); - requireSameGenesisIdentity(beforeGenesis, exact); - TokenIdentity tokenIdentity = originalNewIdentity(exact); - new AccountGameplayTokenIdentityFenceRepository(dsl) - .requireActiveReadback(tokenIdentity); - return issuance.confirmFinalAdmission( - exact, - finalReadback.admissionAtMillis(), - finalReadback.continuityExpiresAtMillis(), - confirmationDigest); - }); - tokenRegistry.requireExactOriginalNewActiveRecord(confirmed); - if (!confirmationDigest.equals(confirmed.confirmationReadbackSha256())) throw unavailable(); - return new OriginalAdmissionConfirmation( - confirmed.lineageId(), - confirmed.leaseId(), - confirmed.confirmedAdmissionAtMillis(), - confirmed.confirmedContinuityExpiresAtMillis(), - confirmed.confirmationReadbackSha256()); - } - - private static ExpectedOriginalAdmission expectedAdmission( - AccountGameplayAdmissionLeaseEvidence lease, Genesis genesis) { - Map scope = object(lease.carrier().get("bindingScope")); - UUID sessionId = uuid(scope.get("sessionId")); - UUID tenantId = uuid(scope.get("tenantId")); - return new ExpectedOriginalAdmission( - genesis.requestId(), - genesis.accountId(), - tenantId, - sessionId, - genesis.bindingDecisionId(), - genesis.leaseId(), - genesis.leaseFence(), - genesis.originalLeaseEvidenceSha256(), - genesis.lineageId(), - genesis.tokenJti(), - genesis.tokenHash(), - genesis.tokenGeneration(), - genesis.issuanceFence(), - genesis.bindingScopeSha256(), - sha256(genesis.membershipBaselineCanonicalBytes()), - sha256(genesis.outboxCheckpointsCanonicalBytes()), - genesis.rebindHandleSha256()); - } - - private static void requireActivationMatches( - Genesis genesis, - AccountGameplayDelegationRedisClient.OriginalNewActivationReadback activation) { - if (activation == null - || !genesis.tokenHash().equals(activation.tokenHash()) - || !genesis.accountId().toString().equals(activation.accountId()) - || !genesis.lineageId().toString().equals(activation.lineageId()) - || !genesis.tokenJti().toString().equals(activation.tokenJti()) - || activation.localAofCount() < 1L - || activation.replicaAofCount() < 1L) throw unavailable(); - } - - private static String confirmationDigest( - AuthenticatedFinalAdmissionReadback finalReadback, - AccountGameplayDelegationRedisClient.OriginalNewActivationReadback activation) { - Map fields = new LinkedHashMap<>(); - fields.put("domain", "account-original-new-final-admission-confirmation/v1"); - fields.put("finalReadbackSha256", finalReadback.canonicalReadbackSha256()); - fields.put("admissionAtMs", Long.toString(finalReadback.admissionAtMillis())); - fields.put("continuityExpiresAtMs", Long.toString(finalReadback.continuityExpiresAtMillis())); - fields.put("sessionDurationMs", Long.toString(finalReadback.canonicalSessionDurationMillis())); - fields.put("activeRecordSha256", activation.activeRecordSha256()); - fields.put("redisAbsoluteExpiryMs", Long.toString(activation.absoluteExpiryMillis())); - return sha256(canonicalJson(fields)); - } - - private Genesis signAndPersistCandidate( - VerifiedCaller caller, - AccountGameplayAdmissionLeaseEvidence lease, - AccountGameplayAdmissionOriginalAckReceipt receipt, - Genesis genesis) { - Map tuple = stringObjectMap(genesis.authorityTupleCanonicalBytes()); - Map membershipVersion = - stringStringMap(genesis.membershipVersionCanonicalBytes()); - Object tenantValue = objectMap(genesis.bindingScopeCanonicalBytes()).get("tenantId"); - if (!(tenantValue instanceof String tenantId)) throw unavailable(); - AccountAuthoritySnapshot accountAuthority = caller.currentCandidate().authoritySnapshot(); - EvidenceBundleReference evidenceReference = caller.currentCandidate().evidenceBundleReference(); - - byte[] handle = new byte[32]; - byte[] compactBytes = null; - byte[] envelopeBytes = null; - byte[] recordBytes = null; - byte[] payload = null; - try { - secureRandom.nextBytes(handle); - try (OriginalNewBoundSignedCandidate signed = - signer.signOriginalNewBoundCandidate( - genesis, accountAuthority, tenantId, tuple, membershipVersion)) { - compactBytes = signed.compactJwtBytes(); - String compactJwt = new String(compactBytes, StandardCharsets.US_ASCII); - GameSessionAccountDelegationRegistryRecord record = - GameSessionAccountDelegationRegistryRecord.fromAccountSignedBoundCompactJwt( - compactJwt, - signed.signerGeneration(), - new IssuanceBinding( - genesis.lineageId().toString(), - genesis.requestId().toString(), - genesis.requestDigest(), - genesis.accountId().toString()), - accountAuthority, - evidenceReference, - tenantId, - tuple, - membershipVersion, - genesis.issuedAtEpochSecond(), - GameSessionAccountDelegationProfile.MAX_REGISTRY_RECORD_BYTES); - recordBytes = - record.toCanonicalJsonBytes( - GameSessionAccountDelegationProfile.MAX_REGISTRY_RECORD_BYTES); - if (!signed.tokenHash().equals(record.tokenHash())) throw unavailable(); - payload = encodeProtectedResult(compactBytes, handle); - EncryptedResponseEnvelope envelope = - responseCryptography.encrypt( - responseBinding(genesis, lease, receipt), - payload, - Instant.ofEpochSecond(genesis.expiresAtEpochSecond())); - envelopeBytes = envelope.bytes(); - String handleHash = sha256(handle); - String tokenHash = signed.tokenHash(); - String signerKid = signed.signerKid(); - String signerGeneration = signed.signerGeneration(); - byte[] exactRecord = recordBytes.clone(); - byte[] exactEnvelope = envelopeBytes.clone(); - try { - return inWritableSerializableTransaction( - dsl -> { - SourceRead current = readCurrentOriginalSource(dsl, caller, lease); - if (current.operation().state() != State.COMMITTED - || !current - .operation() - .bindingDecisionId() - .equals(receipt.bindingDecisionId())) { - throw unavailable(); - } - requireExactReceipt(receipt, current.operation(), lease); - Genesis currentGenesis = - new AccountOriginalNewBoundGameplayIssuanceRepository(dsl) - .readByLease(leaseId(lease)); - requireSameGenesisIdentity(genesis, currentGenesis); - return new AccountOriginalNewBoundGameplayIssuanceRepository(dsl) - .bindSignedResult( - currentGenesis, - tokenHash, - signerKid, - signerGeneration, - exactRecord, - handleHash, - exactEnvelope); - }); - } finally { - wipe(exactRecord); - wipe(exactEnvelope); - } - } - } finally { - wipe(handle); - wipe(compactBytes); - wipe(envelopeBytes); - wipe(recordBytes); - wipe(payload); - } - } - - private OriginalNewCredential openCommittedResult( - VerifiedCaller caller, - AccountGameplayAdmissionLeaseEvidence lease, - AccountGameplayAdmissionOriginalAckReceipt receipt, - Genesis expectedGenesis) { - SourceRead source = readCurrentOriginalSource(caller, lease); - requireExactReceipt(receipt, source.operation(), lease); - Genesis committed = - inWritableSerializableTransaction( - dsl -> { - SourceRead current = readCurrentOriginalSource(dsl, caller, lease); - requireSameOriginalOperation(source.operation(), current.operation()); - var issuance = new AccountOriginalNewBoundGameplayIssuanceRepository(dsl); - Genesis exact = issuance.readByLease(leaseId(lease)); - requireSameGenesisIdentity(expectedGenesis, exact); - if (exact.status() - != AccountOriginalNewBoundGameplayIssuanceRepository.Status.COMMITTED) { - throw unavailable(); - } - var tokenIdentity = - new TokenIdentity( - exact.accountId(), - exact.lineageId(), - exact.requestId(), - exact.tokenHash(), - exact.tokenJti(), - exact.notBeforeEpochSecond(), - exact.tokenGeneration(), - exact.issuanceFence(), - SourceKind.ORIGINAL_NEW); - new AccountGameplayTokenIdentityFenceRepository(dsl) - .requireActiveReadback(tokenIdentity); - return exact; - }); - - if (committed.confirmedAdmissionAtMillis() != null) { - tokenRegistry.requireExactOriginalNewActiveRecord(committed); - } else { - tokenRegistry.registerOriginalNewPending(committed); - } - - return openFrozenCredentialResult(lease, receipt, source, committed); - } - - /** - * Opens only the already-frozen signed credential needed to verify Account's actual Game Session - * final-admission read. This path deliberately does not require or mutate a Redis registry state; - * the later positive result still requires the authenticated Game Session read and the exact - * Account-owned pending-to-active CAS. - */ - private OriginalNewCredential openFrozenCredentialForFinalAdmissionVerification( - VerifiedCaller caller, - AccountGameplayAdmissionLeaseEvidence lease, - AccountGameplayAdmissionOriginalAckReceipt receipt, - Genesis expectedGenesis) { - SourceRead source = readCurrentOriginalSource(caller, lease); - requireExactReceipt(receipt, source.operation(), lease); - Genesis committed = - inWritableSerializableTransaction( - dsl -> { - SourceRead current = readCurrentOriginalSource(dsl, caller, lease); - requireSameOriginalOperation(source.operation(), current.operation()); - var issuance = new AccountOriginalNewBoundGameplayIssuanceRepository(dsl); - Genesis exact = issuance.readByLease(leaseId(lease)); - requireSameGenesisIdentity(expectedGenesis, exact); - if (exact.status() - != AccountOriginalNewBoundGameplayIssuanceRepository.Status.COMMITTED) { - throw unavailable(); - } - new AccountGameplayTokenIdentityFenceRepository(dsl) - .requireActiveReadback(originalNewIdentity(exact)); - return exact; - }); - - return openFrozenCredentialResult(lease, receipt, source, committed); - } - - private OriginalNewCredential openFrozenCredentialResult( - AccountGameplayAdmissionLeaseEvidence lease, - AccountGameplayAdmissionOriginalAckReceipt receipt, - SourceRead source, - Genesis committed) { - - byte[] plaintext = null; - try { - plaintext = - responseCryptography.decrypt( - new EncryptedResponseEnvelope(committed.encryptedResultEnvelopeBytes()), - responseBinding(committed, lease, receipt), - Instant.ofEpochSecond(committed.expiresAtEpochSecond())); - OpenedProtectedResult stored = decodeProtectedResult(plaintext); - byte[] jwtBytes = stored.compactJwtBytes(); - byte[] handle = stored.handleBytes(); - try { - if (handle.length != 32 - || !sha256(handle).equals(committed.rebindHandleSha256()) - || !sha256(jwtBytes).equals(committed.tokenHash())) { - throw unavailable(); - } - String compactJwt = new String(jwtBytes, StandardCharsets.US_ASCII); - signer.verifyOriginalNewBoundCredential( - compactJwt, - committed, - source.accountAuthority(), - tenantId(lease).toString(), - stringObjectMap(committed.authorityTupleCanonicalBytes()), - stringStringMap(committed.membershipVersionCanonicalBytes())); - return AccountGameplayAdmissionLeaseGrpcCodec.originalNewCredential( - compactJwt, - handle, - committed.lineageId(), - committed.tokenJti(), - committed.tokenHash(), - committed.issuanceFence(), - committed.leaseId(), - committed.leaseFence(), - receipt.receiptXid(), - sha256(committed.outboxCheckpointsCanonicalBytes())); - } finally { - wipe(handle); - wipe(jwtBytes); - } - } catch (RuntimeException failure) { - throw unavailable(); - } finally { - wipe(plaintext); - } - } - - private SourceRead readCurrentOriginalSource( - VerifiedCaller caller, AccountGameplayAdmissionLeaseEvidence lease) { - return inWritableSerializableTransaction(dsl -> readCurrentOriginalSource(dsl, caller, lease)); - } - - private SourceRead readCurrentOriginalSource( - DSLContext dsl, VerifiedCaller caller, AccountGameplayAdmissionLeaseEvidence lease) { - UUID tenantId = tenantId(lease); - AccountGameplayAdmissionCurrentSources sourceReader = - AccountGameplayAdmissionCurrentSources.bind(dsl, workloadNamespace); - var current = - sourceReader.readCurrentPublicProductionNew( - tenantId, caller.identity().tokenJti(), caller.currentCandidate()); - current.requireMatchesOriginalLease(lease); - AccountGameplayAdmissionLeaseOperation operation = - new AccountGameplayAdmissionLeaseRepository(dsl) - .readExact(lease) - .orElseThrow(AccountOriginalNewBoundGameplayCredentialOwner::unavailable); - return new SourceRead(operation, current.currentCommittedCandidate().authoritySnapshot()); - } - - private Binding responseBinding( - Genesis genesis, - AccountGameplayAdmissionLeaseEvidence lease, - AccountGameplayAdmissionOriginalAckReceipt receipt) { - Map evidence = new LinkedHashMap<>(); - evidence.put("bindingScopeSha256", genesis.bindingScopeSha256()); - evidence.put("leaseEvidenceSha256", genesis.originalLeaseEvidenceSha256()); - evidence.put("ackEvidenceSha256", genesis.originalAckEvidenceSha256()); - evidence.put("ackReceiptXid", genesis.originalAckReceiptXid()); - evidence.put("outboxCheckpoints", checkpointArray(genesis.outboxCheckpointsCanonicalBytes())); - evidence.put("receiptCommittedBeforeMs", Long.toString(receipt.committedBeforeMs())); - byte[] evidenceBytes = canonicalJson(evidence); - try { - return new Binding( - ENVELOPE_OPERATION, - genesis.requestId().toString(), - HexFormat.of().parseHex(genesis.requestDigest()), - genesis.callerWorkload(), - genesis.leaseId().toString(), - Optional.of(genesis.lineageId().toString()), - Optional.empty(), - Optional.of(genesis.leaseId().toString()), - genesis.issuanceFence(), - genesis.authorityTupleCanonicalBytes(), - genesis.membershipVersionCanonicalBytes(), - evidenceBytes); - } finally { - wipe(evidenceBytes); - } - } - - private static byte[] encodeProtectedResult(byte[] compactJwt, byte[] handle) { - if (compactJwt == null - || compactJwt.length == 0 - || compactJwt.length > GameSessionAccountDelegationProfile.MAX_COMPACT_JWT_BYTES - || handle == null - || handle.length != 32) throw unavailable(); - ByteBuffer framed = ByteBuffer.allocate(8 + compactJwt.length + handle.length); - framed.put(new byte[] {'F', 'O', 'N', '1'}); - framed.putInt(compactJwt.length); - framed.put(compactJwt); - framed.put(handle); - return framed.array(); - } - - private static OpenedProtectedResult decodeProtectedResult(byte[] exactBytes) { - if (exactBytes == null - || exactBytes.length < 8 + 1 + 32 - || exactBytes.length > GameSessionAccountDelegationProfile.MAX_COMPACT_JWT_BYTES + 40) { - throw unavailable(); - } - ByteBuffer input = ByteBuffer.wrap(exactBytes); - if (input.get() != 'F' || input.get() != 'O' || input.get() != 'N' || input.get() != '1') { - throw unavailable(); - } - int jwtLength = input.getInt(); - if (jwtLength <= 0 - || jwtLength > GameSessionAccountDelegationProfile.MAX_COMPACT_JWT_BYTES - || input.remaining() != jwtLength + 32) throw unavailable(); - byte[] jwt = new byte[jwtLength]; - byte[] handle = new byte[32]; - input.get(jwt); - input.get(handle); - for (byte value : jwt) { - if (Byte.toUnsignedInt(value) > 0x7f) { - wipe(jwt); - wipe(handle); - throw unavailable(); - } - } - return new OpenedProtectedResult(jwt, handle); - } - - private static byte[] canonicalJson(Object value) { - try { - return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); - } catch (Exception malformed) { - throw unavailable(); - } - } - - private static Map stringObjectMap(byte[] bytes) { - return parseJsonMap(bytes); - } - - private static Map stringStringMap(byte[] bytes) { - Map value = parseJsonMap(bytes); - Map copy = new LinkedHashMap<>(); - value.forEach( - (key, item) -> { - if (!(key instanceof String textKey) || !(item instanceof String textValue)) { - throw unavailable(); - } - copy.put(textKey, textValue); - }); - return Map.copyOf(copy); - } - - private static Map objectMap(byte[] bytes) { - return parseJsonMap(bytes); - } - - private static Map parseJsonMap(byte[] bytes) { - try { - return JSON.readValue(bytes, Map.class); - } catch (Exception malformed) { - throw unavailable(); - } - } - - private static List checkpointArray(byte[] bytes) { - try { - return JSON.readValue(bytes, List.class); - } catch (Exception malformed) { - throw unavailable(); - } - } - - private VerifiedCaller verifyCaller(String compactJwt, GrpcPeerIdentity peer) { - VerifiedCaller caller; - try { - caller = callerVerifier.verifyPresentedCompactToken(compactJwt); - } catch (RuntimeException failure) { - throw unavailable(); - } - if (!peer.uri().equals(caller.identity().callerWorkload())) throw unavailable(); - return caller; - } - - private void requireCallerMatchesLease( - VerifiedCaller caller, GrpcPeerIdentity peer, AccountGameplayAdmissionLeaseEvidence lease) { - Map carrier = lease.carrier(); - Map scope = object(carrier.get("bindingScope")); - Map token = object(carrier.get("tokenIdentityEvidence")); - if (lease.leaseKind() != AccountGameplayAdmissionLeaseEvidence.LeaseKind.NEW_BINDING - || !workloadNamespace.equals(carrier.get("targetNamespace")) - || !peer.uri().equals(carrier.get("callerWorkload")) - || !peer.uri().equals(caller.identity().callerWorkload()) - || !caller.identity().accountId().toString().equals(scope.get("accountId")) - || !caller.identity().tokenJti().toString().equals(token.get("tokenJti")) - || !caller.currentCandidate().tokenSha256().equals(token.get("tokenSHA256"))) { - throw unavailable(); - } - } - - private GrpcPeerIdentity requireGameSessionCaller() { - GrpcPeerIdentity peer = GrpcPeerIdentity.current(); - if (peer == null - || SessionContext.hasAuthenticatedCallerContext() - || SessionContext.isInternalService() - || SessionContext.getServiceName() != null - || SessionContext.getServiceInstanceId() != null - || !GAME_SESSION_SERVICE.equals(peer.service()) - || !workloadNamespace.equals(peer.namespace()) - || !("spiffe://firemud/ns/" + workloadNamespace + "/sa/game-session-service") - .equals(peer.uri())) { - throw Status.PERMISSION_DENIED - .withDescription("Exact same-namespace Game Session workload required") - .asRuntimeException(); - } - return peer; - } - - private void requireNoAmbientSql() { - Object managed = - Objects.requireNonNull(new DataSourceTransactionManager(dataSource).getDataSource()); - if (TransactionSynchronizationManager.isActualTransactionActive() - || TransactionSynchronizationManager.isSynchronizationActive() - || TransactionSynchronizationManager.hasResource(dataSource) - || TransactionSynchronizationManager.hasResource(managed)) { - throw Status.FAILED_PRECONDITION - .withDescription("Original-new credential owner requires no ambient Account transaction") - .asRuntimeException(); - } - } - - private T inWritableSerializableTransaction( - java.util.function.Function operation) { - DataSourceTransactionManager manager = new DataSourceTransactionManager(dataSource); - TransactionTemplate transaction = new TransactionTemplate(manager); - transaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); - transaction.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE); - transaction.setReadOnly(false); - T result = - transaction.execute( - status -> { - if (!status.isNewTransaction()) throw unavailable(); - Object resource = - TransactionSynchronizationManager.getResource( - Objects.requireNonNull(manager.getDataSource())); - if (!(resource instanceof ConnectionHolder holder)) throw unavailable(); - var connection = holder.getConnection(); - try { - if (connection.getAutoCommit() - || connection.isReadOnly() - || connection.getTransactionIsolation() - != java.sql.Connection.TRANSACTION_SERIALIZABLE) throw unavailable(); - } catch (java.sql.SQLException failure) { - throw unavailable(); - } - return operation.apply(DSL.using(connection, SQLDialect.POSTGRES)); - }); - return Objects.requireNonNull(result); - } - - private static byte[] pendingRegistryReceiptBytes(PendingRegistrationReceipt receipt) { - Map fields = new LinkedHashMap<>(); - fields.put("domain", "account-original-new-pending-registry-receipt/v1"); - fields.put("aclIdentity", receipt.aclIdentity()); - fields.put("operationId", receipt.operationId()); - fields.put("requestId", receipt.requestId()); - fields.put("requestDigest", receipt.requestDigest()); - fields.put("accountId", receipt.accountId()); - fields.put("tokenJti", receipt.tokenJti()); - fields.put("tokenHash", receipt.tokenHash()); - fields.put("recordSha256", receipt.canonicalRecordSha256()); - fields.put("absoluteExpiryMillis", Long.toString(receipt.absoluteExpiryMillis())); - fields.put("localAofCount", Long.toString(receipt.localAofCount())); - fields.put("replicaAofCount", Long.toString(receipt.replicaAofCount())); - fields.put("registryVersion", Long.toString(receipt.registryVersion())); - return canonicalJson(fields); - } - - private static String pendingRegistryReceiptDigest(PendingRegistrationReceipt receipt) { - byte[] proof = pendingRegistryReceiptBytes(Objects.requireNonNull(receipt)); - try { - return sha256(proof); - } finally { - wipe(proof); - } - } - - private static void requireExactReceipt( - AccountGameplayAdmissionOriginalAckReceipt receipt, - AccountGameplayAdmissionLeaseOperation operation, - AccountGameplayAdmissionLeaseEvidence lease) { - if (operation == null - || receipt == null - || operation.state() != State.COMMITTED - || !operation.evidence().hasSameIdentity(lease) - || !receipt.operation().evidence().hasSameIdentity(lease) - || !receipt.bindingDecisionId().equals(operation.bindingDecisionId()) - || !receipt.evidenceSha256().equals(lease.sha256())) throw unavailable(); - } - - private static void requireSameOriginalOperation( - AccountGameplayAdmissionLeaseOperation expected, - AccountGameplayAdmissionLeaseOperation actual) { - if (expected == null - || actual == null - || expected.state() != State.COMMITTED - || actual.state() != State.COMMITTED - || !expected.evidence().hasSameIdentity(actual.evidence()) - || !Objects.equals(expected.bindingDecisionId(), actual.bindingDecisionId())) - throw unavailable(); - } - - private static void requireSameGenesisIdentity(Genesis expected, Genesis actual) { - if (expected == null - || actual == null - || !expected.lineageId().equals(actual.lineageId()) - || !expected.tokenJti().equals(actual.tokenJti()) - || !expected.requestDigest().equals(actual.requestDigest()) - || !expected.leaseId().equals(actual.leaseId()) - || expected.issuanceFence() != actual.issuanceFence()) throw unavailable(); - } - - private static UUID tenantId(AccountGameplayAdmissionLeaseEvidence lease) { - Object value = object(lease.carrier().get("bindingScope")).get("tenantId"); - if (!(value instanceof String text)) throw unavailable(); - try { - UUID parsed = UUID.fromString(text); - if (!parsed.toString().equals(text) || parsed.version() != 4 || parsed.variant() != 2) - throw unavailable(); - return parsed; - } catch (IllegalArgumentException malformed) { - throw unavailable(); - } - } - - private static UUID leaseId(AccountGameplayAdmissionLeaseEvidence lease) { - Object value = lease.carrier().get("leaseId"); - if (!(value instanceof String text)) throw unavailable(); - try { - UUID parsed = UUID.fromString(text); - if (!parsed.toString().equals(text) || parsed.version() != 4 || parsed.variant() != 2) - throw unavailable(); - return parsed; - } catch (IllegalArgumentException malformed) { - throw unavailable(); - } - } - - private static Map object(Object value) { - if (!(value instanceof Map map)) throw unavailable(); - return map; - } - - private static UUID uuid(Object value) { - if (!(value instanceof String text)) throw unavailable(); - try { - UUID parsed = UUID.fromString(text); - if (!parsed.toString().equals(text) || parsed.version() != 4 || parsed.variant() != 2) { - throw unavailable(); - } - return parsed; - } catch (IllegalArgumentException malformed) { - throw unavailable(); - } - } - - private static TokenIdentity originalNewIdentity(Genesis genesis) { - return new TokenIdentity( - genesis.accountId(), - genesis.lineageId(), - genesis.requestId(), - genesis.tokenHash(), - genesis.tokenJti(), - genesis.notBeforeEpochSecond(), - genesis.tokenGeneration(), - genesis.issuanceFence(), - SourceKind.ORIGINAL_NEW); - } - - private static String sha256(byte[] value) { - try { - return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value)); - } catch (NoSuchAlgorithmException impossible) { - throw unavailable(); - } - } - - private static void wipe(byte[] bytes) { - if (bytes != null) Arrays.fill(bytes, (byte) 0); - } - - private static IllegalStateException unavailable() { - return new IllegalStateException("Original-new bound gameplay credential is unavailable"); - } - - private record SourceRead( - AccountGameplayAdmissionLeaseOperation operation, AccountAuthoritySnapshot accountAuthority) { - SourceRead { - Objects.requireNonNull(operation); - Objects.requireNonNull(accountAuthority); - } - } - - private record OpenedProtectedResult(byte[] compactJwtBytes, byte[] handleBytes) {} - - /** Actual original-admission anchors returned only by the Account-side confirmation hook. */ - public static final class OriginalAdmissionConfirmation { - private final UUID lineageId; - private final UUID originalLeaseId; - private final long admissionAtMillis; - private final long continuityExpiresAtMillis; - private final String authenticatedConfirmationSha256; - - private OriginalAdmissionConfirmation( - UUID lineageId, - UUID originalLeaseId, - long admissionAtMillis, - long continuityExpiresAtMillis, - String authenticatedConfirmationSha256) { - this.lineageId = Objects.requireNonNull(lineageId); - this.originalLeaseId = Objects.requireNonNull(originalLeaseId); - if (admissionAtMillis <= 0L || continuityExpiresAtMillis <= admissionAtMillis) { - throw unavailable(); - } - this.admissionAtMillis = admissionAtMillis; - this.continuityExpiresAtMillis = continuityExpiresAtMillis; - this.authenticatedConfirmationSha256 = - Objects.requireNonNull(authenticatedConfirmationSha256); - if (!authenticatedConfirmationSha256.matches("[0-9a-f]{64}")) throw unavailable(); - } - - public UUID lineageId() { - return lineageId; - } - - public UUID originalLeaseId() { - return originalLeaseId; - } - - public long admissionAtMillis() { - return admissionAtMillis; - } - - public long continuityExpiresAtMillis() { - return continuityExpiresAtMillis; - } - - public String authenticatedConfirmationSha256() { - return authenticatedConfirmationSha256; - } - - @Override - public String toString() { - return "OriginalAdmissionConfirmation[redacted]"; - } - } -} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountOriginalNewBoundGameplayIssuanceRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountOriginalNewBoundGameplayIssuanceRepository.java deleted file mode 100644 index cb4221300d..0000000000 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountOriginalNewBoundGameplayIssuanceRepository.java +++ /dev/null @@ -1,935 +0,0 @@ -package net.firedevops.firemud.accountservice.repository; - -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.Objects; -import java.util.UUID; -import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionLeaseOperation.State; -import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionOriginalAckReceipt; -import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; -import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; -import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; -import org.jooq.DSLContext; -import org.jooq.Record; -import org.springframework.transaction.support.TransactionSynchronizationManager; -import tools.jackson.databind.json.JsonMapper; - -/** - * Durable Account owner for the single ORIGINAL-NEW bound-token lineage attached to one committed - * Account admission lease. LOGIN issuance remains in its existing table and has no changed shape. - * - *

This repository only records exact owner-produced identity and postcondition evidence. It does - * not sign credentials, establish the Game Session final-admission result, or make a handle - * consumable without the caller's independent current-source and authenticated-read checks. - */ -public final class AccountOriginalNewBoundGameplayIssuanceRepository { - private static final String TABLE = "account_original_new_bound_gameplay_issuances"; - private static final JsonMapper JSON = JsonMapper.builder().build(); - - private final DSLContext dsl; - - public AccountOriginalNewBoundGameplayIssuanceRepository(DSLContext dsl) { - this.dsl = Objects.requireNonNull(dsl, "Account DSLContext is required"); - } - - /** - * Creates one fresh generation-1 lineage or returns that exact lineage for a matching lease. - * Generated IDs and token times are inputs used only for a new row; a retry always returns the - * originally persisted IDs and times and never starts another lineage. - */ - public Genesis beginGenesis( - AccountGameplayAdmissionLeaseEvidence lease, - AccountGameplayAdmissionOriginalAckReceipt receipt, - UUID operationId, - UUID tokenJti, - long issuedAtEpochSecond, - long notBeforeEpochSecond, - long expiresAtEpochSecond) { - requireWritableSerializableTransaction(); - Objects.requireNonNull(lease, "Exact original Account lease is required"); - Objects.requireNonNull(receipt, "Durable original Account ACK receipt is required"); - requireUuidV4(operationId); - requireUuidV4(tokenJti); - if (operationId.equals(tokenJti) - || issuedAtEpochSecond <= 0L - || notBeforeEpochSecond <= 0L - || notBeforeEpochSecond > issuedAtEpochSecond - || expiresAtEpochSecond <= issuedAtEpochSecond - || expiresAtEpochSecond - issuedAtEpochSecond - > GameSessionAccountDelegationProfile.MAX_TOKEN_LIFETIME_SECONDS) { - throw unavailable(); - } - - Map carrier = lease.carrier(); - Map scope = object(carrier.get("bindingScope")); - UUID requestId = uuid(carrier.get("requestId")); - UUID leaseId = uuid(carrier.get("leaseId")); - UUID accountId = uuid(scope.get("accountId")); - UUID bindingDecisionId = receipt.bindingDecisionId(); - long leaseFence = lease.leaseFence().longValueExact(); - long issuanceFence = positiveLong(carrier.get("issuanceFence")); - requireOriginalAck(lease, receipt, requestId, accountId, leaseId, leaseFence); - - byte[] scopeBytes = canonicalBytes(scope); - String bindingScopeSha256 = sha256(scopeBytes); - byte[] tupleBytes = canonicalBytes(carrier.get("authorityTuple")); - Map baseline = object(carrier.get("membershipBaseline")); - byte[] membershipBaselineBytes = canonicalBytes(baseline); - byte[] membershipVersionBytes = canonicalBytes(baseline.get("membershipVersion")); - byte[] checkpointsBytes = canonicalBytes(carrier.get("outboxCheckpoints")); - String requestDigest = - requestDigest( - lease, - receipt, - scopeBytes, - tupleBytes, - membershipBaselineBytes, - membershipVersionBytes, - checkpointsBytes); - try { - // Account first, then the original lease/receipt rows, then this lineage row. The trigger - // independently checks the exact committed operation and separate ACK receipt on INSERT. - dsl.fetchOne( - "SELECT account_uuid FROM accounts WHERE account_uuid = ? FOR UPDATE", accountId); - Record retained = - dsl.fetchOne("SELECT * FROM " + TABLE + " WHERE lease_id = ? FOR UPDATE", leaseId); - if (retained != null) { - Genesis exact = decode(retained); - requireSameFrozenSource( - exact, - requestId, - accountId, - leaseId, - leaseFence, - bindingDecisionId, - lease, - receipt, - requestDigest, - bindingScopeSha256, - scopeBytes, - tupleBytes, - membershipBaselineBytes, - membershipVersionBytes, - checkpointsBytes, - issuanceFence); - return exact; - } - Record priorBinding = - dsl.fetchOne( - "SELECT * FROM " + TABLE + " WHERE binding_scope_sha256 = ? FOR UPDATE", - bindingScopeSha256); - if (priorBinding != null) throw unavailable(); - - int inserted = - dsl.execute( - "INSERT INTO " - + TABLE - + " (operation_id, request_id, account_uuid, caller_workload, request_digest, " - + "lease_id, lease_fence, binding_decision_id, binding_scope_sha256, " - + "original_lease_evidence_sha256, " - + "original_ack_receipt_xid, original_ack_evidence_sha256, " - + "binding_scope_canonical_bytes, authority_tuple_canonical_bytes, " - + "membership_baseline_canonical_bytes, membership_version_canonical_bytes, " - + "outbox_checkpoints_canonical_bytes, " - + "issuance_fence, token_jti, token_generation, issued_at_epoch_second, " - + "not_before_epoch_second, expires_at_epoch_second) " - + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, ?, ?, ?) " - + "ON CONFLICT DO NOTHING", - operationId, - requestId, - accountId, - carrier.get("callerWorkload"), - requestDigest, - leaseId, - leaseFence, - bindingDecisionId, - bindingScopeSha256, - lease.sha256(), - receipt.receiptXid(), - receipt.evidenceSha256(), - scopeBytes, - tupleBytes, - membershipBaselineBytes, - membershipVersionBytes, - checkpointsBytes, - issuanceFence, - tokenJti, - issuedAtEpochSecond, - notBeforeEpochSecond, - expiresAtEpochSecond); - if (inserted != 1) throw unavailable(); - Record readback = - dsl.fetchOne("SELECT * FROM " + TABLE + " WHERE lease_id = ? FOR UPDATE", leaseId); - if (readback == null) throw unavailable(); - Genesis created = decode(readback); - requireSameFrozenSource( - created, - requestId, - accountId, - leaseId, - leaseFence, - bindingDecisionId, - lease, - receipt, - requestDigest, - bindingScopeSha256, - scopeBytes, - tupleBytes, - membershipBaselineBytes, - membershipVersionBytes, - checkpointsBytes, - issuanceFence); - if (!created.lineageId().equals(operationId) - || !created.tokenJti().equals(tokenJti) - || created.issuedAtEpochSecond() != issuedAtEpochSecond - || created.notBeforeEpochSecond() != notBeforeEpochSecond - || created.expiresAtEpochSecond() != expiresAtEpochSecond) throw unavailable(); - return created; - } finally { - wipe(scopeBytes); - wipe(tupleBytes); - wipe(membershipBaselineBytes); - wipe(membershipVersionBytes); - wipe(checkpointsBytes); - } - } - - /** Binds the exact signed candidate, opaque-handle hash, and encrypted result once. */ - public Genesis bindSignedResult( - Genesis genesis, - String tokenHash, - String signerKid, - String signerGeneration, - byte[] canonicalPendingRegistryRecord, - String opaqueHandleHash, - byte[] encryptedResultEnvelope) { - requireWritableSerializableTransaction(); - Objects.requireNonNull(genesis); - requireSha256(tokenHash); - requireSha256(opaqueHandleHash); - if (signerKid == null || !signerKid.matches("[A-Za-z0-9_-]{1,64}")) throw unavailable(); - requirePositiveDecimal(signerGeneration); - requireBytes(canonicalPendingRegistryRecord, 16 * 1024); - requireBytes(encryptedResultEnvelope, 65_610); - String envelopeHash = sha256(encryptedResultEnvelope); - - Record prior = requireByLeaseForUpdate(genesis.leaseId()); - Genesis current = decode(prior); - requireSameGenesis(genesis, current); - if (current.tokenHash() != null) { - if (!tokenHash.equals(current.tokenHash()) - || !signerKid.equals(current.signerKid()) - || !signerGeneration.equals(current.signerGeneration()) - || !Arrays.equals(canonicalPendingRegistryRecord, current.pendingRegistryRecordBytes()) - || !opaqueHandleHash.equals(current.rebindHandleSha256()) - || !envelopeHash.equals(current.encryptedResultEnvelopeSha256()) - || !Arrays.equals(encryptedResultEnvelope, current.encryptedResultEnvelopeBytes())) { - throw unavailable(); - } - return current; - } - int changed = - dsl.execute( - "UPDATE " - + TABLE - + " SET token_hash = ?, signer_kid = ?, signer_generation = ?, " - + "pending_registry_record_bytes = ?, rebind_handle_sha256 = ?, " - + "encrypted_result_envelope_sha256 = ?, encrypted_result_envelope_bytes = ? " - + "WHERE operation_id = ? AND status = 'PENDING' AND token_hash IS NULL", - tokenHash, - signerKid, - signerGeneration, - canonicalPendingRegistryRecord, - opaqueHandleHash, - envelopeHash, - encryptedResultEnvelope, - genesis.lineageId()); - if (changed != 1) throw unavailable(); - Genesis readback = decode(requireByLeaseForUpdate(genesis.leaseId())); - requireSameGenesis(genesis, readback); - if (!tokenHash.equals(readback.tokenHash()) - || !opaqueHandleHash.equals(readback.rebindHandleSha256()) - || !envelopeHash.equals(readback.encryptedResultEnvelopeSha256()) - || !Arrays.equals(canonicalPendingRegistryRecord, readback.pendingRegistryRecordBytes()) - || !Arrays.equals(encryptedResultEnvelope, readback.encryptedResultEnvelopeBytes())) { - throw unavailable(); - } - return readback; - } - - /** Finalizes only the existing one-way issuance after exact pending-registry readback. */ - public Genesis commit(Genesis genesis, String pendingRegistryReceiptSha256) { - requireWritableSerializableTransaction(); - Objects.requireNonNull(genesis); - requireSha256(pendingRegistryReceiptSha256); - Genesis current = decode(requireByLeaseForUpdate(genesis.leaseId())); - requireSameGenesis(genesis, current); - if (current.status() == Status.COMMITTED) { - if (!pendingRegistryReceiptSha256.equals(current.committedRegistryReceiptSha256())) { - throw unavailable(); - } - return current; - } - if (current.tokenHash() == null) throw unavailable(); - int changed = - dsl.execute( - "UPDATE " - + TABLE - + " SET status = 'COMMITTED', committed_registry_receipt_sha256 = ?, " - + "committed_at = CURRENT_TIMESTAMP WHERE operation_id = ? AND status = 'PENDING' " - + "AND token_hash = ? AND rebind_handle_sha256 = ?", - pendingRegistryReceiptSha256, - genesis.lineageId(), - current.tokenHash(), - current.rebindHandleSha256()); - if (changed != 1) throw unavailable(); - Genesis committed = decode(requireByLeaseForUpdate(genesis.leaseId())); - if (committed.status() != Status.COMMITTED - || !pendingRegistryReceiptSha256.equals(committed.committedRegistryReceiptSha256())) { - throw unavailable(); - } - return committed; - } - - /** Readback by exact original lease; this does not authenticate the supplied lease or caller. */ - public Genesis readByLease(UUID leaseId) { - requireReadableTransaction(); - requireUuidV4(leaseId); - Record row = dsl.fetchOne("SELECT * FROM " + TABLE + " WHERE lease_id = ?", leaseId); - return row == null ? null : decode(row); - } - - /** Stores the actual Account-authenticated Game Session final-readback anchors once. */ - Genesis confirmFinalAdmission( - Genesis expected, - long actualAdmissionAtMillis, - long actualContinuityExpiresAtMillis, - String authenticatedReadbackSha256) { - requireWritableSerializableTransaction(); - Objects.requireNonNull(expected); - requireSha256(authenticatedReadbackSha256); - if (actualAdmissionAtMillis <= 0L || actualContinuityExpiresAtMillis <= actualAdmissionAtMillis) - throw unavailable(); - Genesis current = decode(requireByLeaseForUpdate(expected.leaseId())); - requireSameGenesis(expected, current); - if (current.status() != Status.COMMITTED) throw unavailable(); - if (current.confirmedAdmissionAtMillis() != null) { - if (current.confirmedAdmissionAtMillis() != actualAdmissionAtMillis - || current.confirmedContinuityExpiresAtMillis() != actualContinuityExpiresAtMillis - || !authenticatedReadbackSha256.equals(current.confirmationReadbackSha256())) { - throw unavailable(); - } - return current; - } - int changed = - dsl.execute( - "UPDATE " - + TABLE - + " SET confirmed_admission_at_ms = ?, confirmed_continuity_expires_at_ms = ?, " - + "confirmation_readback_sha256 = ? WHERE operation_id = ? AND status = 'COMMITTED' " - + "AND confirmed_admission_at_ms IS NULL AND handle_consumed_at_ms IS NULL", - actualAdmissionAtMillis, - actualContinuityExpiresAtMillis, - authenticatedReadbackSha256, - expected.lineageId()); - if (changed != 1) throw unavailable(); - Genesis stored = decode(requireByLeaseForUpdate(expected.leaseId())); - if (!Objects.equals(stored.confirmedAdmissionAtMillis(), actualAdmissionAtMillis) - || !Objects.equals( - stored.confirmedContinuityExpiresAtMillis(), actualContinuityExpiresAtMillis) - || !authenticatedReadbackSha256.equals(stored.confirmationReadbackSha256())) { - throw unavailable(); - } - return stored; - } - - /** Atomically consumes the Account-only handle once inside the already currentness-checked tx. */ - Genesis consumeOneUseHandle( - Genesis expected, - String presentedHandleSha256, - UUID consumptionRequestId, - long actualAdmissionAtMillis) { - requireWritableSerializableTransaction(); - Objects.requireNonNull(expected); - requireSha256(presentedHandleSha256); - requireUuidV4(consumptionRequestId); - if (actualAdmissionAtMillis <= 0L) throw unavailable(); - Genesis current = decode(requireByLeaseForUpdate(expected.leaseId())); - requireSameGenesis(expected, current); - if (current.status() != Status.COMMITTED - || current.confirmedAdmissionAtMillis() == null - || current.confirmedContinuityExpiresAtMillis() == null - || current.confirmationReadbackSha256() == null - || current.confirmedAdmissionAtMillis() != actualAdmissionAtMillis - || !presentedHandleSha256.equals(current.rebindHandleSha256())) throw unavailable(); - if (current.handleConsumedAtMillis() != null) { - if (!consumptionRequestId.equals(current.handleConsumptionRequestId()) - || current.handleConsumedAtMillis() >= current.confirmedContinuityExpiresAtMillis()) { - throw unavailable(); - } - return current; - } - int changed = - dsl.execute( - "UPDATE " - + TABLE - + " SET handle_consumed_at_ms = floor(extract(epoch FROM clock_timestamp()) * 1000)::bigint, " - + "handle_consumption_request_id = ? WHERE operation_id = ? AND status = 'COMMITTED' " - + "AND rebind_handle_sha256 = ? AND confirmed_admission_at_ms = ? " - + "AND confirmed_continuity_expires_at_ms > floor(extract(epoch FROM clock_timestamp()) * 1000) " - + "AND handle_consumed_at_ms IS NULL", - consumptionRequestId, - expected.lineageId(), - presentedHandleSha256, - actualAdmissionAtMillis); - if (changed != 1) throw unavailable(); - Genesis consumed = decode(requireByLeaseForUpdate(expected.leaseId())); - if (!consumptionRequestId.equals(consumed.handleConsumptionRequestId()) - || consumed.handleConsumedAtMillis() == null - || consumed.handleConsumedAtMillis() < actualAdmissionAtMillis - || consumed.handleConsumedAtMillis() >= consumed.confirmedContinuityExpiresAtMillis()) { - throw unavailable(); - } - return consumed; - } - - private Record requireByLeaseForUpdate(UUID leaseId) { - Record row = dsl.fetchOne("SELECT * FROM " + TABLE + " WHERE lease_id = ? FOR UPDATE", leaseId); - if (row == null) throw unavailable(); - return row; - } - - private static void requireOriginalAck( - AccountGameplayAdmissionLeaseEvidence lease, - AccountGameplayAdmissionOriginalAckReceipt receipt, - UUID requestId, - UUID accountId, - UUID leaseId, - long leaseFence) { - if (lease.leaseKind() != AccountGameplayAdmissionLeaseEvidence.LeaseKind.NEW_BINDING - || receipt.operation().state() != State.COMMITTED - || !requestId.equals(receipt.requestId()) - || !accountId.equals(receipt.accountId()) - || !leaseId.equals(receipt.leaseId()) - || leaseFence != receipt.leaseFence() - || !lease.sha256().equals(receipt.evidenceSha256()) - || !receipt.bindingDecisionId().equals(receipt.operation().bindingDecisionId()) - || !receipt.operation().evidence().hasSameIdentity(lease)) throw unavailable(); - } - - private static void requireSameFrozenSource( - Genesis genesis, - UUID requestId, - UUID accountId, - UUID leaseId, - long leaseFence, - UUID decisionId, - AccountGameplayAdmissionLeaseEvidence lease, - AccountGameplayAdmissionOriginalAckReceipt receipt, - String requestDigest, - String bindingScopeSha256, - byte[] scope, - byte[] tuple, - byte[] membershipBaseline, - byte[] membershipVersion, - byte[] checkpoints, - long issuanceFence) { - if (!genesis.requestId().equals(requestId) - || !genesis.accountId().equals(accountId) - || !genesis.leaseId().equals(leaseId) - || genesis.leaseFence() != leaseFence - || !genesis.bindingDecisionId().equals(decisionId) - || !genesis.bindingScopeSha256().equals(bindingScopeSha256) - || !genesis.originalLeaseEvidenceSha256().equals(lease.sha256()) - || !genesis.originalAckReceiptXid().equals(receipt.receiptXid()) - || !genesis.originalAckEvidenceSha256().equals(receipt.evidenceSha256()) - || !genesis.requestDigest().equals(requestDigest) - || !Arrays.equals(scope, genesis.bindingScopeCanonicalBytes()) - || !Arrays.equals(tuple, genesis.authorityTupleCanonicalBytes()) - || !Arrays.equals(membershipBaseline, genesis.membershipBaselineCanonicalBytes()) - || !Arrays.equals(membershipVersion, genesis.membershipVersionCanonicalBytes()) - || !Arrays.equals(checkpoints, genesis.outboxCheckpointsCanonicalBytes()) - || genesis.issuanceFence() != issuanceFence) throw unavailable(); - } - - private static void requireSameGenesis(Genesis expected, Genesis actual) { - if (!expected.lineageId().equals(actual.lineageId()) - || !expected.requestId().equals(actual.requestId()) - || !expected.accountId().equals(actual.accountId()) - || !expected.leaseId().equals(actual.leaseId()) - || expected.leaseFence() != actual.leaseFence() - || !expected.bindingDecisionId().equals(actual.bindingDecisionId()) - || !expected.requestDigest().equals(actual.requestDigest()) - || !expected.tokenJti().equals(actual.tokenJti()) - || expected.issuanceFence() != actual.issuanceFence()) throw unavailable(); - } - - private static Genesis decode(Record row) { - try { - return new Genesis( - row.get("operation_id", UUID.class), - row.get("request_id", UUID.class), - row.get("account_uuid", UUID.class), - row.get("caller_workload", String.class), - row.get("request_digest", String.class), - row.get("lease_id", UUID.class), - row.get("lease_fence", Long.class), - row.get("binding_decision_id", UUID.class), - row.get("binding_scope_sha256", String.class), - row.get("original_lease_evidence_sha256", String.class), - row.get("original_ack_receipt_xid", String.class), - row.get("original_ack_evidence_sha256", String.class), - row.get("binding_scope_canonical_bytes", byte[].class), - row.get("authority_tuple_canonical_bytes", byte[].class), - row.get("membership_baseline_canonical_bytes", byte[].class), - row.get("membership_version_canonical_bytes", byte[].class), - row.get("outbox_checkpoints_canonical_bytes", byte[].class), - row.get("issuance_fence", Long.class), - row.get("token_jti", UUID.class), - row.get("token_generation", Long.class), - row.get("issued_at_epoch_second", Long.class), - row.get("not_before_epoch_second", Long.class), - row.get("expires_at_epoch_second", Long.class), - Status.valueOf(row.get("status", String.class)), - row.get("token_hash", String.class), - row.get("signer_kid", String.class), - row.get("signer_generation", String.class), - row.get("pending_registry_record_bytes", byte[].class), - row.get("rebind_handle_sha256", String.class), - row.get("encrypted_result_envelope_sha256", String.class), - row.get("encrypted_result_envelope_bytes", byte[].class), - row.get("committed_registry_receipt_sha256", String.class), - row.get("confirmed_admission_at_ms", Long.class), - row.get("confirmed_continuity_expires_at_ms", Long.class), - row.get("confirmation_readback_sha256", String.class), - row.get("handle_consumed_at_ms", Long.class), - row.get("handle_consumption_request_id", UUID.class)); - } catch (RuntimeException malformed) { - throw unavailable(); - } - } - - private static byte[] canonicalBytes(Object value) { - try { - return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); - } catch (Exception malformed) { - throw unavailable(); - } - } - - private static String requestDigest( - AccountGameplayAdmissionLeaseEvidence lease, - AccountGameplayAdmissionOriginalAckReceipt receipt, - byte[] scope, - byte[] tuple, - byte[] membershipBaseline, - byte[] membershipVersion, - byte[] checkpoints) { - Map fields = new LinkedHashMap<>(); - fields.put("domain", "account-original-new-bound-gameplay/v1"); - fields.put("requestId", receipt.requestId().toString()); - fields.put("leaseId", receipt.leaseId().toString()); - fields.put("leaseFence", Long.toString(receipt.leaseFence())); - fields.put("bindingDecisionId", receipt.bindingDecisionId().toString()); - fields.put("leaseEvidenceSha256", lease.sha256()); - fields.put("ackReceiptXid", receipt.receiptXid()); - fields.put("ackEvidenceSha256", receipt.evidenceSha256()); - fields.put("bindingScope", decodeUtf8(scope)); - fields.put("authorityTuple", decodeUtf8(tuple)); - fields.put("membershipBaseline", decodeUtf8(membershipBaseline)); - fields.put("membershipVersion", decodeUtf8(membershipVersion)); - fields.put("outboxCheckpoints", decodeUtf8(checkpoints)); - try { - return sha256(Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(fields))); - } catch (Exception malformed) { - throw unavailable(); - } - } - - private static String decodeUtf8(byte[] value) { - return new String(value, StandardCharsets.UTF_8); - } - - private static String sha256(byte[] value) { - try { - return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value)); - } catch (NoSuchAlgorithmException impossible) { - throw unavailable(); - } - } - - private static void requireSha256(String value) { - if (value == null || !value.matches("[0-9a-f]{64}")) throw unavailable(); - } - - private static void requirePositiveDecimal(String value) { - if (value == null || !value.matches("[1-9][0-9]{0,18}")) throw unavailable(); - } - - private static void requireBytes(byte[] value, int maximum) { - if (value == null || value.length == 0 || value.length > maximum) throw unavailable(); - } - - private static void requireUuidV4(UUID value) { - if (value == null || value.version() != 4 || value.variant() != 2) throw unavailable(); - } - - private static UUID uuid(Object value) { - if (!(value instanceof String text)) throw unavailable(); - try { - UUID parsed = UUID.fromString(text); - if (!parsed.toString().equals(text) || parsed.version() != 4 || parsed.variant() != 2) { - throw unavailable(); - } - return parsed; - } catch (IllegalArgumentException malformed) { - throw unavailable(); - } - } - - private static long positiveLong(Object value) { - if (!(value instanceof String text) || !text.matches("[1-9][0-9]{0,18}")) throw unavailable(); - try { - return Long.parseLong(text); - } catch (NumberFormatException malformed) { - throw unavailable(); - } - } - - private static Map object(Object value) { - if (!(value instanceof Map map)) throw unavailable(); - return map; - } - - private static void wipe(byte[] bytes) { - if (bytes != null) Arrays.fill(bytes, (byte) 0); - } - - private static void requireWritableSerializableTransaction() { - if (!TransactionSynchronizationManager.isActualTransactionActive() - || TransactionSynchronizationManager.isCurrentTransactionReadOnly() - || !Integer.valueOf(java.sql.Connection.TRANSACTION_SERIALIZABLE) - .equals(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel())) { - throw unavailable(); - } - } - - private static void requireReadableTransaction() { - if (!TransactionSynchronizationManager.isActualTransactionActive()) throw unavailable(); - } - - private static IllegalStateException unavailable() { - return new IllegalStateException("Original-new bound gameplay issuance is unavailable"); - } - - public enum Status { - PENDING, - COMMITTED - } - - /** - * Frozen non-secret token identity and protected result source; arrays are defensively copied. - */ - public static final class Genesis { - private final UUID lineageId; - private final UUID requestId; - private final UUID accountId; - private final String callerWorkload; - private final String requestDigest; - private final UUID leaseId; - private final long leaseFence; - private final UUID bindingDecisionId; - private final String bindingScopeSha256; - private final String originalLeaseEvidenceSha256; - private final String originalAckReceiptXid; - private final String originalAckEvidenceSha256; - private final byte[] bindingScopeCanonicalBytes; - private final byte[] authorityTupleCanonicalBytes; - private final byte[] membershipBaselineCanonicalBytes; - private final byte[] membershipVersionCanonicalBytes; - private final byte[] outboxCheckpointsCanonicalBytes; - private final long issuanceFence; - private final UUID tokenJti; - private final long tokenGeneration; - private final long issuedAtEpochSecond; - private final long notBeforeEpochSecond; - private final long expiresAtEpochSecond; - private final Status status; - private final String tokenHash; - private final String signerKid; - private final String signerGeneration; - private final byte[] pendingRegistryRecordBytes; - private final String rebindHandleSha256; - private final String encryptedResultEnvelopeSha256; - private final byte[] encryptedResultEnvelopeBytes; - private final String committedRegistryReceiptSha256; - private final Long confirmedAdmissionAtMillis; - private final Long confirmedContinuityExpiresAtMillis; - private final String confirmationReadbackSha256; - private final Long handleConsumedAtMillis; - private final UUID handleConsumptionRequestId; - - private Genesis( - UUID lineageId, - UUID requestId, - UUID accountId, - String callerWorkload, - String requestDigest, - UUID leaseId, - long leaseFence, - UUID bindingDecisionId, - String bindingScopeSha256, - String originalLeaseEvidenceSha256, - String originalAckReceiptXid, - String originalAckEvidenceSha256, - byte[] bindingScopeCanonicalBytes, - byte[] authorityTupleCanonicalBytes, - byte[] membershipBaselineCanonicalBytes, - byte[] membershipVersionCanonicalBytes, - byte[] outboxCheckpointsCanonicalBytes, - long issuanceFence, - UUID tokenJti, - long tokenGeneration, - long issuedAtEpochSecond, - long notBeforeEpochSecond, - long expiresAtEpochSecond, - Status status, - String tokenHash, - String signerKid, - String signerGeneration, - byte[] pendingRegistryRecordBytes, - String rebindHandleSha256, - String encryptedResultEnvelopeSha256, - byte[] encryptedResultEnvelopeBytes, - String committedRegistryReceiptSha256, - Long confirmedAdmissionAtMillis, - Long confirmedContinuityExpiresAtMillis, - String confirmationReadbackSha256, - Long handleConsumedAtMillis, - UUID handleConsumptionRequestId) { - this.lineageId = Objects.requireNonNull(lineageId); - this.requestId = Objects.requireNonNull(requestId); - this.accountId = Objects.requireNonNull(accountId); - this.callerWorkload = Objects.requireNonNull(callerWorkload); - this.requestDigest = Objects.requireNonNull(requestDigest); - this.leaseId = Objects.requireNonNull(leaseId); - this.leaseFence = leaseFence; - this.bindingDecisionId = Objects.requireNonNull(bindingDecisionId); - this.bindingScopeSha256 = Objects.requireNonNull(bindingScopeSha256); - this.originalLeaseEvidenceSha256 = Objects.requireNonNull(originalLeaseEvidenceSha256); - this.originalAckReceiptXid = Objects.requireNonNull(originalAckReceiptXid); - this.originalAckEvidenceSha256 = Objects.requireNonNull(originalAckEvidenceSha256); - this.bindingScopeCanonicalBytes = copy(bindingScopeCanonicalBytes); - this.authorityTupleCanonicalBytes = copy(authorityTupleCanonicalBytes); - this.membershipBaselineCanonicalBytes = copy(membershipBaselineCanonicalBytes); - this.membershipVersionCanonicalBytes = copy(membershipVersionCanonicalBytes); - this.outboxCheckpointsCanonicalBytes = copy(outboxCheckpointsCanonicalBytes); - this.issuanceFence = issuanceFence; - this.tokenJti = Objects.requireNonNull(tokenJti); - this.tokenGeneration = tokenGeneration; - this.issuedAtEpochSecond = issuedAtEpochSecond; - this.notBeforeEpochSecond = notBeforeEpochSecond; - this.expiresAtEpochSecond = expiresAtEpochSecond; - this.status = Objects.requireNonNull(status); - this.tokenHash = tokenHash; - this.signerKid = signerKid; - this.signerGeneration = signerGeneration; - this.pendingRegistryRecordBytes = copy(pendingRegistryRecordBytes); - this.rebindHandleSha256 = rebindHandleSha256; - this.encryptedResultEnvelopeSha256 = encryptedResultEnvelopeSha256; - this.encryptedResultEnvelopeBytes = copy(encryptedResultEnvelopeBytes); - this.committedRegistryReceiptSha256 = committedRegistryReceiptSha256; - this.confirmedAdmissionAtMillis = confirmedAdmissionAtMillis; - this.confirmedContinuityExpiresAtMillis = confirmedContinuityExpiresAtMillis; - this.confirmationReadbackSha256 = confirmationReadbackSha256; - this.handleConsumedAtMillis = handleConsumedAtMillis; - this.handleConsumptionRequestId = handleConsumptionRequestId; - if ((confirmedAdmissionAtMillis == null) != (confirmedContinuityExpiresAtMillis == null) - || (confirmedAdmissionAtMillis == null) != (confirmationReadbackSha256 == null) - || (handleConsumedAtMillis == null) != (handleConsumptionRequestId == null) - || (confirmedAdmissionAtMillis != null - && (confirmedAdmissionAtMillis <= 0L - || confirmedContinuityExpiresAtMillis <= confirmedAdmissionAtMillis - || !confirmationReadbackSha256.matches("[0-9a-f]{64}") - || status != Status.COMMITTED)) - || (handleConsumedAtMillis != null - && (handleConsumedAtMillis <= 0L - || confirmedContinuityExpiresAtMillis == null - || handleConsumedAtMillis >= confirmedContinuityExpiresAtMillis - || status != Status.COMMITTED))) { - throw unavailable(); - } - if (leaseFence <= 0L - || issuanceFence <= 0L - || tokenGeneration != 1L - || issuedAtEpochSecond <= 0L - || notBeforeEpochSecond <= 0L - || notBeforeEpochSecond > issuedAtEpochSecond - || expiresAtEpochSecond <= issuedAtEpochSecond) { - throw unavailable(); - } - } - - private static byte[] copy(byte[] value) { - return value == null ? null : value.clone(); - } - - public UUID lineageId() { - return lineageId; - } - - public UUID requestId() { - return requestId; - } - - public UUID accountId() { - return accountId; - } - - public String callerWorkload() { - return callerWorkload; - } - - public String requestDigest() { - return requestDigest; - } - - public UUID leaseId() { - return leaseId; - } - - public long leaseFence() { - return leaseFence; - } - - public UUID bindingDecisionId() { - return bindingDecisionId; - } - - public String bindingScopeSha256() { - return bindingScopeSha256; - } - - public String originalLeaseEvidenceSha256() { - return originalLeaseEvidenceSha256; - } - - public String originalAckReceiptXid() { - return originalAckReceiptXid; - } - - public String originalAckEvidenceSha256() { - return originalAckEvidenceSha256; - } - - public byte[] bindingScopeCanonicalBytes() { - return bindingScopeCanonicalBytes.clone(); - } - - public byte[] authorityTupleCanonicalBytes() { - return authorityTupleCanonicalBytes.clone(); - } - - public byte[] membershipBaselineCanonicalBytes() { - return membershipBaselineCanonicalBytes.clone(); - } - - public byte[] membershipVersionCanonicalBytes() { - return membershipVersionCanonicalBytes.clone(); - } - - public byte[] outboxCheckpointsCanonicalBytes() { - return outboxCheckpointsCanonicalBytes.clone(); - } - - public long issuanceFence() { - return issuanceFence; - } - - public UUID tokenJti() { - return tokenJti; - } - - public long tokenGeneration() { - return tokenGeneration; - } - - public long issuedAtEpochSecond() { - return issuedAtEpochSecond; - } - - public long notBeforeEpochSecond() { - return notBeforeEpochSecond; - } - - public long expiresAtEpochSecond() { - return expiresAtEpochSecond; - } - - public Status status() { - return status; - } - - public String tokenHash() { - return tokenHash; - } - - public String signerKid() { - return signerKid; - } - - public String signerGeneration() { - return signerGeneration; - } - - public byte[] pendingRegistryRecordBytes() { - return copy(pendingRegistryRecordBytes); - } - - public String rebindHandleSha256() { - return rebindHandleSha256; - } - - public String encryptedResultEnvelopeSha256() { - return encryptedResultEnvelopeSha256; - } - - public byte[] encryptedResultEnvelopeBytes() { - return copy(encryptedResultEnvelopeBytes); - } - - public String committedRegistryReceiptSha256() { - return committedRegistryReceiptSha256; - } - - public Long confirmedAdmissionAtMillis() { - return confirmedAdmissionAtMillis; - } - - public Long confirmedContinuityExpiresAtMillis() { - return confirmedContinuityExpiresAtMillis; - } - - public String confirmationReadbackSha256() { - return confirmationReadbackSha256; - } - - public Long handleConsumedAtMillis() { - return handleConsumedAtMillis; - } - - public UUID handleConsumptionRequestId() { - return handleConsumptionRequestId; - } - - @Override - public String toString() { - return "OriginalNewBoundGameplayGenesis[status=" + status + ",credential=redacted]"; - } - } -} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayAdmissionLeaseGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayAdmissionLeaseGrpcService.java index 2b9222cb02..7ea03fe510 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayAdmissionLeaseGrpcService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayAdmissionLeaseGrpcService.java @@ -11,41 +11,28 @@ import net.firedevops.firemud.account.v1.AccountGameplayAdmissionLeaseResponse; import net.firedevops.firemud.account.v1.AccountGameplayAdmissionLeaseServiceGrpc; import net.firedevops.firemud.account.v1.AcquireGameplayAdmissionLeaseRequest; -import net.firedevops.firemud.account.v1.ConfirmOriginalNewGameplayAdmissionRequest; import net.firedevops.firemud.account.v1.FinalizeGameplayAdmissionLeaseRequest; -import net.firedevops.firemud.account.v1.IssueOriginalNewGameplayCredentialRequest; -import net.firedevops.firemud.account.v1.OriginalNewAdmissionConfirmationResponse; import net.firedevops.firemud.account.v1.ReadGameplayAdmissionLeaseRequest; import net.firedevops.firemud.accountservice.repository.AccountGameplayAdmissionLeaseOwner; -import net.firedevops.firemud.accountservice.repository.AccountOriginalNewBoundGameplayCredentialOwner; import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseGrpcCodec; import org.jooq.exception.DataAccessException; import org.springframework.dao.DataAccessResourceFailureException; import org.springframework.transaction.CannotCreateTransactionException; import org.springframework.transaction.support.TransactionSynchronizationManager; -/** Standalone, unregistered receiver for Account's NEW lease and ORIGINAL-NEW credential calls. */ +/** Standalone, unregistered receiver for Account's four NEW lease operations. */ public final class AccountGameplayAdmissionLeaseGrpcService extends AccountGameplayAdmissionLeaseServiceGrpc.AccountGameplayAdmissionLeaseServiceImplBase { private static final String FAILURE_DESCRIPTION = "Account gameplay admission lease operation denied or unavailable"; private final AccountGameplayAdmissionLeaseOwner owner; - private final AccountOriginalNewBoundGameplayCredentialOwner originalNewCredentialOwner; private final AccountGameplayAdmissionLeaseWorkloadGuard workloadGuard; AccountGameplayAdmissionLeaseGrpcService( AccountGameplayAdmissionLeaseOwner owner, AccountGameplayAdmissionLeaseWorkloadGuard workloadGuard) { - this(owner, null, workloadGuard); - } - - AccountGameplayAdmissionLeaseGrpcService( - AccountGameplayAdmissionLeaseOwner owner, - AccountOriginalNewBoundGameplayCredentialOwner originalNewCredentialOwner, - AccountGameplayAdmissionLeaseWorkloadGuard workloadGuard) { this.owner = Objects.requireNonNull(owner, "Account gameplay admission lease owner required"); - this.originalNewCredentialOwner = originalNewCredentialOwner; this.workloadGuard = Objects.requireNonNull(workloadGuard, "Account gameplay admission lease guard required"); } @@ -110,103 +97,6 @@ public void abortGameplayAdmissionLease( }); } - @Override - public void issueOriginalNewGameplayCredential( - IssueOriginalNewGameplayCredentialRequest request, - StreamObserver observer) { - receive( - request, - observer, - AccountGameplayAdmissionLeaseGrpcCodec.MAX_ORIGINAL_LEASE_REQUEST_WIRE_BYTES, - () -> { - var parsed = - AccountGameplayAdmissionLeaseGrpcCodec.parseIssueOriginalNewCredentialRequest( - request); - workloadGuard.requireOriginalNewCredentialNamespace(parsed); - if (originalNewCredentialOwner == null) { - throw Status.UNAVAILABLE - .withDescription("Account original-new credential owner is unavailable") - .asRuntimeException(); - } - return () -> originalNewCredentialOwner.issue(parsed); - }); - } - - @Override - public void confirmOriginalNewGameplayAdmission( - ConfirmOriginalNewGameplayAdmissionRequest request, - StreamObserver observer) { - Objects.requireNonNull(observer, "response observer is required"); - try { - workloadGuard.requireGameSessionCaller(); - } catch (StatusRuntimeException denied) { - fail(observer, denied.getStatus()); - return; - } - if (TransactionSynchronizationManager.isActualTransactionActive() - || TransactionSynchronizationManager.isSynchronizationActive()) { - fail(observer, Status.FAILED_PRECONDITION); - return; - } - if (request == null - || request.getSerializedSize() - > AccountGameplayAdmissionLeaseGrpcCodec.MAX_ORIGINAL_LEASE_REQUEST_WIRE_BYTES) { - fail(observer, Status.INVALID_ARGUMENT); - return; - } - final AccountGameplayAdmissionLeaseGrpcCodec.OriginalFinalAdmissionConfirmationRequest parsed; - try { - parsed = - AccountGameplayAdmissionLeaseGrpcCodec.parseConfirmOriginalNewGameplayAdmissionRequest( - request); - workloadGuard.requireOriginalFinalAdmissionConfirmationNamespace(parsed); - if (originalNewCredentialOwner == null) throw new IllegalStateException(); - } catch (StatusRuntimeException rejected) { - fail(observer, rejected.getStatus()); - return; - } catch (IllegalArgumentException malformed) { - fail(observer, Status.INVALID_ARGUMENT); - return; - } catch (RuntimeException unavailable) { - fail(observer, Status.UNAVAILABLE); - return; - } - - final AccountOriginalNewBoundGameplayCredentialOwner.OriginalAdmissionConfirmation confirmed; - try { - confirmed = - originalNewCredentialOwner.confirmOriginalFinalAdmission( - parsed.presentedInitialGsACompactJwt(), parsed.originalLeaseEvidence()); - } catch (StatusRuntimeException failure) { - fail(observer, failure.getStatus()); - return; - } catch (IllegalArgumentException malformed) { - fail(observer, Status.FAILED_PRECONDITION); - return; - } catch (RuntimeException unavailable) { - fail(observer, Status.UNAVAILABLE); - return; - } - - final OriginalNewAdmissionConfirmationResponse response; - try { - response = - AccountGameplayAdmissionLeaseGrpcCodec.toConfirmOriginalNewGameplayAdmissionResponse( - parsed, - confirmed.lineageId(), - confirmed.originalLeaseId(), - parsed.originalLeaseEvidence().leaseFence().longValueExact(), - confirmed.admissionAtMillis(), - confirmed.continuityExpiresAtMillis(), - confirmed.authenticatedConfirmationSha256()); - } catch (RuntimeException invalidOwnerResult) { - fail(observer, Status.INTERNAL); - return; - } - observer.onNext(response); - observer.onCompleted(); - } - private void receive( T request, StreamObserver observer, diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayAdmissionLeaseManualFactory.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayAdmissionLeaseManualFactory.java index 569e529bc6..8eb97c6693 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayAdmissionLeaseManualFactory.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayAdmissionLeaseManualFactory.java @@ -8,7 +8,6 @@ import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.TrustManagerFactory; import net.firedevops.firemud.accountservice.repository.AccountGameplayAdmissionLeaseOwner; -import net.firedevops.firemud.accountservice.repository.AccountOriginalNewBoundGameplayCredentialOwner; import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseGrpcCodec; import net.firedevops.firemud.common.grpc.BoundedGrpcServerFactory; import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; @@ -25,18 +24,6 @@ public static AccountGameplayAdmissionLeaseGrpcService createUnregisteredReceive new AccountGameplayAdmissionLeaseWorkloadGuard(workloadNamespace)); } - /** Explicit receiver composition that enables only the exact post-COMMITTED credential method. */ - public static AccountGameplayAdmissionLeaseGrpcService createUnregisteredReceiver( - AccountGameplayAdmissionLeaseOwner owner, - AccountOriginalNewBoundGameplayCredentialOwner originalNewCredentialOwner, - String workloadNamespace) { - return new AccountGameplayAdmissionLeaseGrpcService( - Objects.requireNonNull(owner, "Account gameplay admission lease owner required"), - Objects.requireNonNull( - originalNewCredentialOwner, "Account original-new credential owner required"), - new AccountGameplayAdmissionLeaseWorkloadGuard(workloadNamespace)); - } - /** Creates an unstarted TLS server with a finite ceiling and no production registration. */ public static Server createUnregisteredServer( String address, @@ -67,36 +54,4 @@ public static Server createUnregisteredServer( new AccountGameplayAdmissionLeaseWorkloadGuard(workloadNamespace))); return factory.createServer(); } - - /** Creates an unstarted, method-guarded receiver with the ORIGINAL-NEW credential owner wired. */ - public static Server createUnregisteredServer( - String address, - KeyManagerFactory keys, - TrustManagerFactory trust, - AccountGameplayAdmissionLeaseOwner owner, - AccountOriginalNewBoundGameplayCredentialOwner originalNewCredentialOwner, - String workloadNamespace) { - Objects.requireNonNull(address, "gRPC server address required"); - Objects.requireNonNull(keys, "gRPC server key manager required"); - Objects.requireNonNull(trust, "gRPC server trust manager required"); - int transportMaximum = - Math.max( - AccountGameplayAdmissionLeaseGrpcCodec.MAX_ACQUIRE_REQUEST_WIRE_BYTES, - AccountGameplayAdmissionLeaseGrpcCodec.MAX_ORIGINAL_LEASE_REQUEST_WIRE_BYTES); - var factory = - new BoundedGrpcServerFactory( - address, - List.of(), - keys, - trust, - TlsServerCredentials.ClientAuth.REQUIRE, - GrpcRequestBytePolicy.ordinary(), - transportMaximum); - factory.addService( - ServerInterceptors.interceptForward( - createUnregisteredReceiver(owner, originalNewCredentialOwner, workloadNamespace), - new GrpcPeerIdentityInterceptor(), - new AccountGameplayAdmissionLeaseWorkloadGuard(workloadNamespace))); - return factory.createServer(); - } } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayAdmissionLeaseWorkloadGuard.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayAdmissionLeaseWorkloadGuard.java index cd2d84a114..76aae99c5f 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayAdmissionLeaseWorkloadGuard.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayAdmissionLeaseWorkloadGuard.java @@ -78,12 +78,6 @@ private static boolean isLeaseMethod(MethodDescriptor method) { .getFullMethodName() .equals(fullMethodName) || AccountGameplayAdmissionLeaseServiceGrpc.getAbortGameplayAdmissionLeaseMethod() - .getFullMethodName() - .equals(fullMethodName) - || AccountGameplayAdmissionLeaseServiceGrpc.getIssueOriginalNewGameplayCredentialMethod() - .getFullMethodName() - .equals(fullMethodName) - || AccountGameplayAdmissionLeaseServiceGrpc.getConfirmOriginalNewGameplayAdmissionMethod() .getFullMethodName() .equals(fullMethodName); } @@ -117,36 +111,6 @@ public void requireOriginalLeaseNamespace( } } - public void requireOriginalNewCredentialNamespace( - AccountGameplayAdmissionLeaseGrpcCodec.OriginalNewCredentialRequest request) { - if (request == null) { - throw Status.INVALID_ARGUMENT - .withDescription("Malformed Account original-new credential request") - .asRuntimeException(); - } - Object targetNamespace = request.originalLeaseEvidence().carrier().get("targetNamespace"); - if (!namespace.equals(targetNamespace)) { - throw Status.PERMISSION_DENIED - .withDescription("Original-new credential lease target namespace is not authorized") - .asRuntimeException(); - } - } - - public void requireOriginalFinalAdmissionConfirmationNamespace( - AccountGameplayAdmissionLeaseGrpcCodec.OriginalFinalAdmissionConfirmationRequest request) { - if (request == null) { - throw Status.INVALID_ARGUMENT - .withDescription("Malformed Account original-new confirmation request") - .asRuntimeException(); - } - Object targetNamespace = request.originalLeaseEvidence().carrier().get("targetNamespace"); - if (!namespace.equals(targetNamespace)) { - throw Status.PERMISSION_DENIED - .withDescription("Original-new confirmation lease target namespace is not authorized") - .asRuntimeException(); - } - } - private static boolean hasSessionContext() { return SessionContext.hasAuthenticatedCallerContext() || SessionContext.isInternalService() diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisClient.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisClient.java index af2412f947..108371f5e9 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisClient.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisClient.java @@ -28,7 +28,6 @@ import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository.CommittedCandidateVerificationData; import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository.PendingIntent; import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationPendingIdentity; -import net.firedevops.firemud.accountservice.repository.AccountOriginalNewBoundGameplayIssuanceRepository.Genesis; import net.firedevops.firemud.accountservice.service.AccountGenerationProjection; import net.firedevops.firemud.accountservice.service.AccountGenerationProjectionRedisContract; import net.firedevops.firemud.accountservice.service.session.AccountCoordinationPinnedConnectionProvider.AcknowledgementRequirements; @@ -1109,161 +1108,6 @@ private RedisScriptDescriptor requirePendingDescriptor() { return descriptor; } - /** - * Applies the original-new pending-to-active CAS after Account obtains an authenticated ORIGINAL - * final-admission readback. Exact retries retain the same record and expiry. - */ - public OriginalNewActivationReadback activateOriginalNewCommittedPending( - Genesis committedOriginalNew, long absoluteExpiryMillis) { - Objects.requireNonNull(committedOriginalNew, "Committed ORIGINAL-NEW Account row required"); - if (TransactionSynchronizationManager.isActualTransactionActive() - || committedOriginalNew.status() - != net.firedevops.firemud.accountservice.repository - .AccountOriginalNewBoundGameplayIssuanceRepository.Status.COMMITTED - || committedOriginalNew.committedRegistryReceiptSha256() == null - || absoluteExpiryMillis <= 0L) throw unavailable(); - byte[] exactPendingBytes = null; - byte[] activeBytes = null; - byte[] scriptSource = null; - byte[] key = null; - byte[] deadline = null; - byte[] currentBytes = null; - byte[] activeReadback = null; - StatefulRedisConnection connection = null; - - try { - exactPendingBytes = committedOriginalNew.pendingRegistryRecordBytes(); - GameSessionAccountDelegationRegistryRecord pendingRecord = - GameSessionAccountDelegationRegistryRecord.decode(exactPendingBytes, maxRecordBytes); - requireOriginalNewPendingMatches(committedOriginalNew, pendingRecord, exactPendingBytes); - activeBytes = activeRecordBytes(pendingRecord); - String tokenHash = committedOriginalNew.tokenHash(); - if (tokenHash == null) throw unavailable(); - RedisScriptDescriptor descriptor = requireActiveTransitionDescriptor(); - scriptSource = readScriptSource(descriptor); - if (!descriptor.sha256().equals(sha256(scriptSource))) throw unavailable(); - key = ascii(TOKEN_KEY_PREFIX + tokenHash); - deadline = Long.toString(absoluteExpiryMillis).getBytes(StandardCharsets.US_ASCII); - connection = connectionProvider.openPinnedConnection(); - if (connection == null) throw unavailable(); - RedisCommands commands = requirePinnedCommands(connection); - requireAccountAclIdentity(commands); - String loadedSha = commands.scriptLoad(scriptSource); - if (loadedSha == null - || !SHA1.matcher(loadedSha).matches() - || !sha1(scriptSource).equals(loadedSha)) throw unavailable(); - currentBytes = commands.get(key); - Long currentExpiry = commands.pexpiretime(key); - if (currentBytes == null || currentExpiry == null || currentExpiry != absoluteExpiryMillis) { - throw unavailable(); - } - GameSessionAccountDelegationRegistryRecord currentRecord = - GameSessionAccountDelegationRegistryRecord.decode(currentBytes, maxRecordBytes); - byte[] expectedCurrent; - if ("pending".equals(currentRecord.state()) && currentRecord.registryVersion() == 1L) { - expectedCurrent = exactPendingBytes; - } else if ("active".equals(currentRecord.state()) && currentRecord.registryVersion() == 2L) { - expectedCurrent = activeBytes; - } else { - throw unavailable(); - } - if (!Arrays.equals(expectedCurrent, currentBytes)) throw unavailable(); - Long transition = - commands.evalsha( - loadedSha, - ScriptOutputType.INTEGER, - new byte[][] {key}, - exactPendingBytes, - activeBytes, - deadline); - if (transition == null || (transition != 0L && transition != 1L)) throw unavailable(); - Acknowledgement acknowledgement = requireDurabilityAcknowledgement(commands); - activeReadback = commands.get(key); - Long activeExpiry = commands.pexpiretime(key); - if (!Arrays.equals(activeBytes, activeReadback) - || activeExpiry == null - || activeExpiry != absoluteExpiryMillis) throw unavailable(); - GameSessionAccountDelegationRegistryRecord active = - GameSessionAccountDelegationRegistryRecord.decode(activeReadback, maxRecordBytes); - if (!"active".equals(active.state()) - || active.registryVersion() != 2L - || !active.tokenHash().equals(tokenHash)) throw unavailable(); - return new OriginalNewActivationReadback( - tokenHash, - committedOriginalNew.accountId().toString(), - committedOriginalNew.lineageId().toString(), - committedOriginalNew.tokenJti().toString(), - sha256(activeReadback), - absoluteExpiryMillis, - acknowledgement.localAofCount(), - acknowledgement.replicaAofCount()); - } catch (RuntimeException failure) { - if (failure instanceof AccountCoordinationRedisException) throw failure; - throw unavailable(); - } finally { - wipe(exactPendingBytes); - wipe(activeBytes); - wipe(currentBytes); - wipe(activeReadback); - wipe(scriptSource); - wipe(key); - wipe(deadline); - if (connection != null) { - try { - connection.close(); - } catch (RuntimeException failure) { - throw unavailable(); - } - } - } - } - - /** Exact read-only ACTIVE check for a retained original-new lineage after confirmation. */ - public ActiveRegistryReadback requireExactOriginalNewActiveRecord( - Genesis committedOriginalNew, long absoluteExpiryMillis) { - Objects.requireNonNull(committedOriginalNew); - if (TransactionSynchronizationManager.isActualTransactionActive() - || committedOriginalNew.status() - != net.firedevops.firemud.accountservice.repository - .AccountOriginalNewBoundGameplayIssuanceRepository.Status.COMMITTED - || absoluteExpiryMillis <= 0L) throw unavailable(); - ActiveRegistryReadback active = readActiveRecord(committedOriginalNew.tokenHash()); - byte[] pendingRecordBytes = committedOriginalNew.pendingRegistryRecordBytes(); - try { - if (!active.tokenHash().equals(committedOriginalNew.tokenHash()) - || !active.accountId().equals(committedOriginalNew.accountId().toString()) - || !active.jti().equals(committedOriginalNew.tokenJti().toString()) - || active.tokenExpiryEpochSecond() != committedOriginalNew.expiresAtEpochSecond() - || active.absoluteExpiryMillis() != absoluteExpiryMillis - || !active.canonicalPendingRecordSha256().equals(sha256(pendingRecordBytes))) { - throw unavailable(); - } - return active; - } finally { - wipe(pendingRecordBytes); - } - } - - private void requireOriginalNewPendingMatches( - Genesis genesis, GameSessionAccountDelegationRegistryRecord record, byte[] recordBytes) { - if (!"pending".equals(record.state()) - || record.registryVersion() != 1L - || !record.tokenHash().equals(genesis.tokenHash()) - || !record.kid().equals(genesis.signerKid()) - || !record.signerGeneration().equals(genesis.signerGeneration()) - || !record.operationId().equals(genesis.lineageId().toString()) - || !record.requestId().equals(genesis.requestId().toString()) - || !record.requestDigest().equals(genesis.requestDigest()) - || !record.accountId().equals(genesis.accountId().toString()) - || !record.jti().equals(genesis.tokenJti().toString()) - || record.issuedAtEpochSecond() != genesis.issuedAtEpochSecond() - || record.notBeforeEpochSecond() != genesis.notBeforeEpochSecond() - || record.expiresAtEpochSecond() != genesis.expiresAtEpochSecond() - || !Long.toString(genesis.tokenGeneration()).equals(record.fields().get("tokenGeneration")) - || record.issuanceFence() != genesis.issuanceFence() - || !Arrays.equals(recordBytes, genesis.pendingRegistryRecordBytes())) throw unavailable(); - } - private RedisScriptDescriptor requireActiveTransitionDescriptor() { RedisScriptDescriptor descriptor = scriptCatalog.require(ACTIVE_TRANSITION_SCRIPT_ID); if (!ACTIVE_TRANSITION_SCRIPT_ID.equals(descriptor.scriptId()) @@ -1427,10 +1271,6 @@ private static boolean canonicalMapEquals(Object value, Map expe } } - private static void wipe(byte[] value) { - if (value != null) Arrays.fill(value, (byte) 0); - } - private static byte[] canonicalJson(Object value) { try { return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); @@ -1829,86 +1669,6 @@ public enum ActiveRegistrationOutcome { EXACT_RETRY } - /** Redacted pinned-Redis/AOF result for one original-new active transition or exact retry. */ - public static final class OriginalNewActivationReadback { - private final String tokenHash; - private final String accountId; - private final String lineageId; - private final String tokenJti; - private final String activeRecordSha256; - private final long absoluteExpiryMillis; - private final long localAofCount; - private final long replicaAofCount; - - private OriginalNewActivationReadback( - String tokenHash, - String accountId, - String lineageId, - String tokenJti, - String activeRecordSha256, - long absoluteExpiryMillis, - long localAofCount, - long replicaAofCount) { - if (tokenHash == null - || !SHA256.matcher(tokenHash).matches() - || accountId == null - || lineageId == null - || tokenJti == null - || activeRecordSha256 == null - || !SHA256.matcher(activeRecordSha256).matches() - || absoluteExpiryMillis <= 0L - || localAofCount < 1L - || replicaAofCount < 1L) { - throw unavailable(); - } - this.tokenHash = tokenHash; - this.accountId = accountId; - this.lineageId = lineageId; - this.tokenJti = tokenJti; - this.activeRecordSha256 = activeRecordSha256; - this.absoluteExpiryMillis = absoluteExpiryMillis; - this.localAofCount = localAofCount; - this.replicaAofCount = replicaAofCount; - } - - public String tokenHash() { - return tokenHash; - } - - public String accountId() { - return accountId; - } - - public String lineageId() { - return lineageId; - } - - public String tokenJti() { - return tokenJti; - } - - public String activeRecordSha256() { - return activeRecordSha256; - } - - public long absoluteExpiryMillis() { - return absoluteExpiryMillis; - } - - public long localAofCount() { - return localAofCount; - } - - public long replicaAofCount() { - return replicaAofCount; - } - - @Override - public String toString() { - return "OriginalNewActivationReadback[redacted]"; - } - } - /** * Private-constructor metadata for an exact ACTIVE registry readback. This value is not a token * credential and is not proof of player admission, response recovery, or current signer state diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationSigner.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationSigner.java index fd57932553..9cb048ccf9 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationSigner.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationSigner.java @@ -26,7 +26,6 @@ import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.CommittedSignerEvidence; import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.CustodyMode; import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.TrustFence; -import net.firedevops.firemud.accountservice.repository.AccountOriginalNewBoundGameplayIssuanceRepository.Genesis; import net.firedevops.firemud.common.security.AccountAsymmetricJwtVerifier; import net.firedevops.firemud.common.security.AccountAsymmetricJwtVerifier.ExplicitRouteProfilePolicy; import net.firedevops.firemud.common.security.AccountAsymmetricJwtVerifier.VerifiedClaims; @@ -316,234 +315,6 @@ CandidateOutcome signPendingCandidate(UUID requestId) { } } - /** - * Signs and locally verifies the distinct tenant-bound ORIGINAL-NEW credential for one frozen - * Account lineage. It reuses the current Account signer/trust/JWKS sources, but does not enter or - * alter the unscoped LOGIN issuance row or its token-identity invariant. - */ - public OriginalNewBoundSignedCandidate signOriginalNewBoundCandidate( - Genesis genesis, - AccountAuthoritySnapshot accountAuthority, - String tenantId, - Map exactAuthorityTuple, - Map exactMembershipVersion) { - Objects.requireNonNull(genesis); - Objects.requireNonNull(accountAuthority); - if (TransactionSynchronizationManager.isActualTransactionActive() - || TransactionSynchronizationManager.isSynchronizationActive()) throw unavailable(); - byte[] firstJwksBytes = null; - byte[] finalJwksBytes = null; - AtomicReference compactTokenCapture = new AtomicReference<>(); - byte[] transientCompactJwt = null; - try { - CurrentSigner initial = accountTransaction.execute(status -> currentCommittedSigner()); - if (initial == null || !accountAuthority.accountId().equals(genesis.accountId())) { - throw unavailable(); - } - SourceIdentity sourcePin = trustedJwksSource.sourceIdentity(); - firstJwksBytes = requireExactTrustedSnapshot(initial, sourcePin, trustedJwksSource.load()); - byte[] pinnedJwks = firstJwksBytes; - AccountPublicJwksCache keyCache = - new AccountPublicJwksCache( - () -> { - PublicJwksSnapshot observed = trustedJwksSource.load(); - byte[] observedBytes = requireExactTrustedSnapshot(initial, sourcePin, observed); - try { - if (!Arrays.equals(pinnedJwks, observedBytes)) { - throw new AccountPublicJwksCache.InvalidJwksException(); - } - return observed; - } finally { - wipe(observedBytes); - } - }, - sourcePin, - clock, - PUBLIC_KEY_CACHE_AGE); - keyCache.keyFor(initial.expectedIdentity().kid()); - - var bound = - new AccountMountedJwtSignerBundle.BoundDelegationClaims( - tenantId, exactAuthorityTuple, exactMembershipVersion); - var signingSpec = - new AccountMountedJwtSignerBundle.OriginalNewBoundDelegationSigningSpec( - genesis.lineageId(), - genesis.requestId(), - genesis.accountId(), - genesis.tokenJti(), - genesis.issuedAtEpochSecond(), - genesis.notBeforeEpochSecond(), - genesis.expiresAtEpochSecond(), - genesis.issuanceFence(), - accountAuthority, - bound); - AccountMountedJwtSignerBundle.SignedDelegationDigest digest = - AccountMountedJwtSignerBundle.signOriginalNewBoundGameplayDelegationDigest( - privateMountRoot, - privateBundlePath, - publicMountRoot, - publicJwksPath, - initial.expectedIdentity(), - signingSpec, - (signed, exactCompactJwt) -> { - if (!genesis.lineageId().equals(signed.issuanceOperationId()) - || !genesis.requestId().equals(signed.requestId()) - || !genesis.tokenJti().equals(signed.jti()) - || !initial.expectedIdentity().operationId().equals(signed.signerOperationId()) - || !initial.expectedIdentity().generation().equals(signed.signerGeneration()) - || !initial.expectedIdentity().kid().equals(signed.kid()) - || !initial - .expectedIdentity() - .publicKeyFingerprint() - .equals(signed.publicKeyFingerprint()) - || signed.issuedAtEpochSecond() != genesis.issuedAtEpochSecond() - || signed.notBeforeEpochSecond() != genesis.notBeforeEpochSecond() - || signed.expiresAtEpochSecond() != genesis.expiresAtEpochSecond() - || !genesis.requestDigest().matches("[0-9a-f]{64}")) { - throw unavailable(); - } - byte[] copy = exactCompactJwt.clone(); - if (!compactTokenCapture.compareAndSet(null, copy)) { - wipe(copy); - throw unavailable(); - } - }); - transientCompactJwt = compactTokenCapture.getAndSet(null); - if (transientCompactJwt == null - || !sha256(transientCompactJwt).equals(digest.compactTokenSha256())) throw unavailable(); - String compact = exactAscii(transientCompactJwt); - VerifiedClaims verified = - new AccountAsymmetricJwtVerifier(keyCache, clock).verify(compact, GSA_SIGNING_POLICY); - Map claims = verified.claims(); - if (!GameSessionAccountDelegationProfile.PROFILE.equals(verified.profile()) - || !GameSessionAccountDelegationProfile.TYPE.equals(verified.tokenType()) - || !initial.expectedIdentity().kid().equals(verified.keyId()) - || !genesis.accountId().toString().equals(claims.get("sub")) - || !genesis.accountId().toString().equals(claims.get("accountId")) - || !genesis.tokenJti().toString().equals(claims.get("jti")) - || !tenantId.equals(claims.get("tenantId")) - || decimalCounterClaim(claims, "tokenGeneration") != 1L - || numberClaim(claims, "iat") != genesis.issuedAtEpochSecond() - || numberClaim(claims, "nbf") != genesis.notBeforeEpochSecond() - || numberClaim(claims, "exp") != genesis.expiresAtEpochSecond() - || decimalCounterClaim(claims, "issuanceFence") != genesis.issuanceFence() - || !exactAuthorityTuple.equals(claims.get("authorityTuple")) - || !exactMembershipVersion.equals(claims.get("membershipVersion")) - || claims.containsKey("globalRoles") - || claims.containsKey("scopedRoles") - || !sha256(transientCompactJwt).equals(digest.compactTokenSha256())) { - throw unavailable(); - } - finalJwksBytes = requireExactTrustedSnapshot(initial, sourcePin, trustedJwksSource.load()); - if (!Arrays.equals(firstJwksBytes, finalJwksBytes)) throw unavailable(); - CurrentSigner observed = accountTransaction.execute(status -> currentCommittedSigner()); - if (observed == null) throw unavailable(); - requireSameCommittedSigner(initial, observed); - return new OriginalNewBoundSignedCandidate( - transientCompactJwt, - digest.compactTokenSha256(), - digest.kid(), - digest.signerGeneration(), - digest.publicKeyFingerprint()); - } catch (RuntimeException failure) { - throw unavailable(); - } finally { - wipe(firstJwksBytes); - wipe(finalJwksBytes); - wipe(compactTokenCapture.getAndSet(null)); - wipe(transientCompactJwt); - } - } - - /** Verifies one exact Account-owned ORIGINAL-NEW JWT under the current mounted signer/JWKS. */ - public VerifiedOriginalNewBoundCredential verifyOriginalNewBoundCredential( - String compactJwt, - Genesis genesis, - AccountAuthoritySnapshot accountAuthority, - String tenantId, - Map exactAuthorityTuple, - Map exactMembershipVersion) { - Objects.requireNonNull(compactJwt); - Objects.requireNonNull(genesis); - Objects.requireNonNull(accountAuthority); - Objects.requireNonNull(exactAuthorityTuple); - Objects.requireNonNull(exactMembershipVersion); - if (TransactionSynchronizationManager.isActualTransactionActive() - || TransactionSynchronizationManager.isSynchronizationActive()) throw unavailable(); - byte[] jwtBytes = null; - byte[] initialJwks = null; - byte[] finalJwks = null; - try { - CurrentSigner initial = accountTransaction.execute(status -> currentCommittedSigner()); - if (initial == null || !genesis.accountId().equals(accountAuthority.accountId())) - throw unavailable(); - // Recovery verifies the frozen JWT's original key against today's trusted JWKS. - // A completed rotation can retain that key without making it the active signer. - SourceIdentity pin = trustedJwksSource.sourceIdentity(); - initialJwks = requireExactTrustedSnapshot(initial, pin, trustedJwksSource.load()); - byte[] pinned = initialJwks; - AccountPublicJwksCache keyCache = - new AccountPublicJwksCache( - () -> { - PublicJwksSnapshot observed = trustedJwksSource.load(); - byte[] observedBytes = requireExactTrustedSnapshot(initial, pin, observed); - try { - if (!Arrays.equals(pinned, observedBytes)) { - throw new AccountPublicJwksCache.InvalidJwksException(); - } - return observed; - } finally { - wipe(observedBytes); - } - }, - pin, - clock, - PUBLIC_KEY_CACHE_AGE); - keyCache.keyFor(genesis.signerKid()); - VerifiedClaims verified = - new AccountAsymmetricJwtVerifier(keyCache, clock).verify(compactJwt, GSA_SIGNING_POLICY); - Map claims = verified.claims(); - jwtBytes = compactJwt.getBytes(StandardCharsets.US_ASCII); - if (!exactAscii(jwtBytes).equals(compactJwt) - || jwtBytes.length > GameSessionAccountDelegationProfile.MAX_COMPACT_JWT_BYTES - || !sha256(jwtBytes).equals(genesis.tokenHash()) - || !GameSessionAccountDelegationProfile.PROFILE.equals(verified.profile()) - || !GameSessionAccountDelegationProfile.TYPE.equals(verified.tokenType()) - || !genesis.signerKid().equals(verified.keyId()) - || !genesis.accountId().toString().equals(claims.get("sub")) - || !genesis.accountId().toString().equals(claims.get("accountId")) - || !genesis.tokenJti().toString().equals(claims.get("jti")) - || !tenantId.equals(claims.get("tenantId")) - || decimalCounterClaim(claims, "tokenGeneration") != 1L - || numberClaim(claims, "iat") != genesis.issuedAtEpochSecond() - || numberClaim(claims, "nbf") != genesis.notBeforeEpochSecond() - || numberClaim(claims, "exp") != genesis.expiresAtEpochSecond() - || decimalCounterClaim(claims, "issuanceFence") != genesis.issuanceFence() - || !exactAuthorityTuple.equals(claims.get("authorityTuple")) - || !exactMembershipVersion.equals(claims.get("membershipVersion")) - || claims.containsKey("globalRoles") - || claims.containsKey("scopedRoles")) throw unavailable(); - finalJwks = requireExactTrustedSnapshot(initial, pin, trustedJwksSource.load()); - if (!Arrays.equals(initialJwks, finalJwks)) throw unavailable(); - CurrentSigner observed = accountTransaction.execute(status -> currentCommittedSigner()); - if (observed == null) throw unavailable(); - requireSameCommittedSigner(initial, observed); - return new VerifiedOriginalNewBoundCredential( - genesis.lineageId(), - genesis.accountId(), - genesis.tokenJti(), - genesis.tokenHash(), - genesis.issuanceFence(), - genesis.expiresAtEpochSecond()); - } catch (RuntimeException failure) { - throw unavailable(); - } finally { - wipe(jwtBytes); - wipe(initialJwks); - wipe(finalJwks); - } - } - /** * Revalidates signer-owned candidate evidence inside the caller's writable Account transaction. * This method performs no signing, external JWKS/API request, mutation, or authorization effect. @@ -1782,82 +1553,4 @@ private SigningUnavailableException() { super("Account gameplay delegation candidate is unavailable or ambiguous"); } } - - /** Signature/profile verification result with no compact JWT or handle bytes. */ - public record VerifiedOriginalNewBoundCredential( - UUID lineageId, - UUID accountId, - UUID tokenJti, - String tokenSha256, - long issuanceFence, - long expiresAtEpochSecond) { - public VerifiedOriginalNewBoundCredential { - Objects.requireNonNull(lineageId); - Objects.requireNonNull(accountId); - Objects.requireNonNull(tokenJti); - if (tokenSha256 == null - || !tokenSha256.matches("[0-9a-f]{64}") - || issuanceFence <= 0L - || expiresAtEpochSecond <= 0L) throw unavailable(); - } - - @Override - public String toString() { - return "VerifiedOriginalNewBoundCredential[redacted]"; - } - } - - /** Transient signed bytes owned by this Account signer invocation; diagnostics redact them. */ - public static final class OriginalNewBoundSignedCandidate implements AutoCloseable { - private byte[] compactJwtBytes; - private final String tokenHash; - private final String signerKid; - private final String signerGeneration; - private final String publicKeyFingerprint; - - private OriginalNewBoundSignedCandidate( - byte[] compactJwtBytes, - String tokenHash, - String signerKid, - String signerGeneration, - String publicKeyFingerprint) { - this.compactJwtBytes = compactJwtBytes.clone(); - this.tokenHash = Objects.requireNonNull(tokenHash); - this.signerKid = Objects.requireNonNull(signerKid); - this.signerGeneration = Objects.requireNonNull(signerGeneration); - this.publicKeyFingerprint = Objects.requireNonNull(publicKeyFingerprint); - } - - public byte[] compactJwtBytes() { - if (compactJwtBytes == null) throw unavailable(); - return compactJwtBytes.clone(); - } - - public String tokenHash() { - return tokenHash; - } - - public String signerKid() { - return signerKid; - } - - public String signerGeneration() { - return signerGeneration; - } - - public String publicKeyFingerprint() { - return publicKeyFingerprint; - } - - @Override - public void close() { - wipe(compactJwtBytes); - compactJwtBytes = null; - } - - @Override - public String toString() { - return "OriginalNewBoundSignedCandidate[credential=redacted]"; - } - } } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationTokenRegistry.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationTokenRegistry.java index d5bd93a51d..29e1c6acc7 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationTokenRegistry.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationTokenRegistry.java @@ -1,14 +1,12 @@ package net.firedevops.firemud.accountservice.service.session; import java.time.Clock; -import java.util.Arrays; import java.util.Map; import java.util.Objects; import java.util.UUID; import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository; import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository.CommittedCandidateVerificationData; import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository.PendingRegistryCandidate; -import net.firedevops.firemud.accountservice.repository.AccountOriginalNewBoundGameplayIssuanceRepository.Genesis; import net.firedevops.firemud.common.security.AccountJwtExactValues; import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; import net.firedevops.firemud.common.security.GameSessionAccountDelegationRegistryRecord; @@ -135,123 +133,6 @@ public AccountGameplayDelegationRedisClient.PendingRegistrationReceipt registerP return receipt; } - /** - * Registers the exact immutable Account-owned ORIGINAL-NEW pending projection. Its lineage row - * was already committed with the signed token hash and record bytes; this method only repeats - * that record under the same fixed expiry and requires the real pinned-Redis WAITAOF receipt. - */ - public AccountGameplayDelegationRedisClient.PendingRegistrationReceipt registerOriginalNewPending( - Genesis genesis) { - Objects.requireNonNull(genesis, "Account-owned ORIGINAL-NEW genesis is required"); - requireNoAccountTransaction( - "ORIGINAL-NEW pending registry work must not join an Account transaction"); - byte[] recordBytes = genesis.pendingRegistryRecordBytes(); - if (recordBytes == null || recordBytes.length == 0 || recordBytes.length > maxEncodedBytes) { - throw new IllegalStateException("Durable ORIGINAL-NEW registry record is unavailable"); - } - try { - GameSessionAccountDelegationRegistryRecord record = - GameSessionAccountDelegationRegistryRecord.decode(recordBytes, maxEncodedBytes); - if (!"pending".equals(record.state()) - || record.registryVersion() != 1L - || !genesis.tokenHash().equals(record.tokenHash()) - || !genesis.signerKid().equals(record.kid()) - || !genesis.signerGeneration().equals(record.signerGeneration()) - || !genesis.lineageId().toString().equals(record.operationId()) - || !genesis.requestId().toString().equals(record.requestId()) - || !genesis.requestDigest().equals(record.requestDigest()) - || !genesis.accountId().toString().equals(record.accountId()) - || !genesis.tokenJti().toString().equals(record.jti()) - || genesis.issuedAtEpochSecond() != record.issuedAtEpochSecond() - || genesis.notBeforeEpochSecond() != record.notBeforeEpochSecond() - || genesis.expiresAtEpochSecond() != record.expiresAtEpochSecond() - || !Long.toString(genesis.tokenGeneration()) - .equals(record.fields().get("tokenGeneration")) - || genesis.issuanceFence() != record.issuanceFence()) { - throw new IllegalStateException( - "Persisted ORIGINAL-NEW registry record differs from the frozen lineage"); - } - - long nowMillis = clock.millis(); - if (nowMillis <= 0L) throw new IllegalStateException("Clock returned an invalid instant"); - long absoluteExpiryMillis; - try { - absoluteExpiryMillis = Math.multiplyExact(genesis.expiresAtEpochSecond(), 1_000L); - absoluteExpiryMillis = Math.addExact(absoluteExpiryMillis, cleanupMarginMillis); - if (absoluteExpiryMillis <= nowMillis) { - throw new IllegalStateException("Original-new registry deadline has elapsed"); - } - } catch (ArithmeticException malformed) { - throw new IllegalStateException("Original-new registry deadline is unavailable"); - } - - AccountGameplayDelegationRedisClient.PendingRegistrationReceipt receipt = - coordinationRedis.registerPending(genesis.tokenHash(), recordBytes, absoluteExpiryMillis); - if (receipt == null - || !receipt - .tokenKey() - .equals(AccountGameplayDelegationRedisClient.TOKEN_KEY_PREFIX + genesis.tokenHash()) - || !AccountGameplayDelegationRedisClient.REQUIRED_ACL_IDENTITY.equals( - receipt.aclIdentity()) - || !receipt.canonicalRecordSha256().equals(sha256(recordBytes)) - || !receipt.operationId().equals(genesis.lineageId().toString()) - || !receipt.requestId().equals(genesis.requestId().toString()) - || !receipt.requestDigest().equals(genesis.requestDigest()) - || !receipt.accountId().equals(genesis.accountId().toString()) - || !receipt.tokenJti().equals(genesis.tokenJti().toString()) - || !receipt.tokenHash().equals(genesis.tokenHash()) - || !receipt.kid().equals(genesis.signerKid()) - || !receipt.signerGeneration().equals(genesis.signerGeneration()) - || receipt.issuedAtEpochSecond() != genesis.issuedAtEpochSecond() - || receipt.notBeforeEpochSecond() != genesis.notBeforeEpochSecond() - || receipt.expiresAtEpochSecond() != genesis.expiresAtEpochSecond() - || receipt.issuanceFence() != genesis.issuanceFence() - || receipt.registryVersion() != 1L - || receipt.absoluteExpiryMillis() != absoluteExpiryMillis - || receipt.localAofCount() < 1L - || receipt.replicaAofCount() < 1L) { - throw new IllegalStateException("ORIGINAL-NEW pending registry receipt is inconsistent"); - } - return receipt; - } finally { - Arrays.fill(recordBytes, (byte) 0); - } - } - - /** - * Activates one exact committed ORIGINAL-NEW projection after Account's authenticated GS read. - */ - public AccountGameplayDelegationRedisClient.OriginalNewActivationReadback - activateOriginalNewCommittedPending(Genesis genesis) { - Objects.requireNonNull(genesis, "Committed Account ORIGINAL-NEW source required"); - requireNoAccountTransaction("ORIGINAL-NEW activation must not hold Account SQL locks"); - long absoluteExpiryMillis = originalNewAbsoluteExpiry(genesis); - long nowMillis = clock.millis(); - if (nowMillis <= 0L || absoluteExpiryMillis <= nowMillis) throw unavailable(); - return coordinationRedis.activateOriginalNewCommittedPending(genesis, absoluteExpiryMillis); - } - - /** Requires the exact already-active ORIGINAL-NEW projection and its original absolute expiry. */ - public AccountGameplayDelegationRedisClient.ActiveRegistryReadback - requireExactOriginalNewActiveRecord(Genesis genesis) { - Objects.requireNonNull(genesis, "Committed Account ORIGINAL-NEW source required"); - requireNoAccountTransaction("ORIGINAL-NEW registry reads must not hold Account SQL locks"); - if (clock.millis() <= 0L) throw unavailable(); - return coordinationRedis.requireExactOriginalNewActiveRecord( - genesis, originalNewAbsoluteExpiry(genesis)); - } - - private long originalNewAbsoluteExpiry(Genesis genesis) { - try { - long tokenExpiryMillis = Math.multiplyExact(genesis.expiresAtEpochSecond(), 1_000L); - long absoluteExpiryMillis = Math.addExact(tokenExpiryMillis, cleanupMarginMillis); - if (absoluteExpiryMillis <= 0L) throw unavailable(); - return absoluteExpiryMillis; - } catch (ArithmeticException malformed) { - throw unavailable(); - } - } - /** * Requires the exact ACTIVE Redis projection for an already-current COMMITTED Account owner read. * This read grants no authority by itself and performs no registry activation. @@ -382,8 +263,4 @@ private static String sha256(byte[] value) { throw new IllegalStateException("SHA-256 is unavailable"); } } - - private static IllegalStateException unavailable() { - return new IllegalStateException("Original-new Account token registry is unavailable"); - } } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountMountedJwtSignerBundle.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountMountedJwtSignerBundle.java index 8eeb666209..a46894c1a8 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountMountedJwtSignerBundle.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountMountedJwtSignerBundle.java @@ -348,121 +348,6 @@ static SignedDelegationDigest signCommittedGameplayDelegationDigest( } } - /** - * Signs the purpose-bound tenant credential for one Account-owned ORIGINAL-NEW lineage. The - * supplied operation identity is the lineage identity; the new row has generation 1 and a - * distinct JTI. It is separate from the immutable unscoped LOGIN claim shape. - */ - static SignedDelegationDigest signOriginalNewBoundGameplayDelegationDigest( - Path privateMountRoot, - Path privateBundlePath, - Path publicMountRoot, - Path publicJwksPath, - ExpectedIdentity expectedIdentity, - OriginalNewBoundDelegationSigningSpec spec, - DelegationCandidateConsumer candidateConsumer) { - Objects.requireNonNull(spec, "Original-new bound signing specification is required"); - Objects.requireNonNull(candidateConsumer, "Gameplay delegation owner callback is required"); - VerifiedMountedSigner mounted = - readAndVerifyMounted( - privateMountRoot, privateBundlePath, publicMountRoot, publicJwksPath, expectedIdentity); - if (!mounted.observation().expectedIdentity().equals(expectedIdentity) - || !spec.accountAuthority().accountId().equals(spec.accountId()) - || spec.accountAuthority().issuanceFence() != spec.issuanceFence() - || spec.operationId().equals(spec.tokenJti())) { - throw invalid(); - } - - byte[] header = null; - byte[] claims = null; - byte[] encodedHeader = null; - byte[] encodedClaims = null; - byte[] signingInput = null; - byte[] signatureBytes = null; - byte[] encodedSignature = null; - byte[] compactBytes = null; - byte[] tokenDigest = null; - byte[] callbackBytes = null; - try { - Map headerFields = new LinkedHashMap<>(); - headerFields.put("alg", ALGORITHM); - headerFields.put("kid", expectedIdentity.kid()); - headerFields.put("typ", "JWT"); - header = canonicalJsonBytes(headerFields); - Map delegation = new LinkedHashMap<>(); - delegation.put("iss", GameSessionAccountDelegationProfile.ISSUER); - delegation.put("sub", spec.accountId().toString()); - delegation.put("jti", spec.tokenJti().toString()); - delegation.put("accountId", spec.accountId().toString()); - delegation.put("aud", GameSessionAccountDelegationProfile.AUDIENCE); - delegation.put("iat", spec.issuedAtEpochSecond()); - delegation.put("nbf", spec.notBeforeEpochSecond()); - delegation.put("exp", spec.expiresAtEpochSecond()); - delegation.put("tokenGeneration", "1"); - delegation.put( - "authorityTuple", mergeBoundAuthorityTuple(spec.accountAuthority(), spec.bound())); - delegation.put("membershipVersion", spec.bound().membershipVersion()); - delegation.put("issuanceFence", Long.toString(spec.issuanceFence())); - delegation.put("tenantId", spec.bound().tenantId()); - net.firedevops.firemud.common.security.GameSessionAccountDelegationJwtProfileValidator - .validateClaims(delegation); - claims = canonicalJsonBytes(delegation); - encodedHeader = Base64.getUrlEncoder().withoutPadding().encode(header); - encodedClaims = Base64.getUrlEncoder().withoutPadding().encode(claims); - signingInput = joinCompactParts(encodedHeader, encodedClaims, null); - - Signature signer = Signature.getInstance("SHA256withRSA"); - signer.initSign(mounted.privateKey()); - signer.update(signingInput); - signatureBytes = signer.sign(); - - Signature verifier = Signature.getInstance("SHA256withRSA"); - verifier.initVerify(mounted.publicKey()); - verifier.update(signingInput); - if (!verifier.verify(signatureBytes)) throw invalid(); - encodedSignature = Base64.getUrlEncoder().withoutPadding().encode(signatureBytes); - compactBytes = joinCompactParts(encodedHeader, encodedClaims, encodedSignature); - if (compactBytes.length > MAX_DELEGATION_COMPACT_JWT_BYTES) throw invalid(); - tokenDigest = MessageDigest.getInstance("SHA-256").digest(compactBytes); - SignedDelegationDigest digest = - new SignedDelegationDigest( - spec.operationId(), - spec.requestId(), - spec.tokenJti(), - expectedIdentity.operationId(), - expectedIdentity.generation(), - expectedIdentity.kid(), - expectedIdentity.publicKeyFingerprint(), - spec.issuedAtEpochSecond(), - spec.notBeforeEpochSecond(), - spec.expiresAtEpochSecond(), - java.util.HexFormat.of().formatHex(tokenDigest)); - callbackBytes = compactBytes.clone(); - try { - candidateConsumer.bindExactCandidate(digest, callbackBytes); - } catch (RuntimeException failure) { - throw invalid(); - } - if (!sha256(callbackBytes).equals(digest.compactTokenSha256())) throw invalid(); - return digest; - } catch (InvalidMountedSignerBundleException ex) { - throw ex; - } catch (Exception ex) { - throw invalid(); - } finally { - wipe(header); - wipe(claims); - wipe(encodedHeader); - wipe(encodedClaims); - wipe(signingInput); - wipe(signatureBytes); - wipe(encodedSignature); - wipe(compactBytes); - wipe(tokenDigest); - wipe(callbackBytes); - } - } - /** * Distinct control-ui entry, available only to the Account owner. The owner must have retained * genuine primary authentication and exact committed signer evidence before calling outside SQL @@ -1257,45 +1142,6 @@ record BoundDelegationClaims( } } - record OriginalNewBoundDelegationSigningSpec( - UUID operationId, - UUID requestId, - UUID accountId, - UUID tokenJti, - long issuedAtEpochSecond, - long notBeforeEpochSecond, - long expiresAtEpochSecond, - long issuanceFence, - AccountAuthoritySnapshot accountAuthority, - BoundDelegationClaims bound) { - OriginalNewBoundDelegationSigningSpec { - Objects.requireNonNull(operationId); - Objects.requireNonNull(requestId); - Objects.requireNonNull(accountId); - Objects.requireNonNull(tokenJti); - Objects.requireNonNull(accountAuthority); - Objects.requireNonNull(bound); - if (operationId.version() != 4 - || requestId.version() != 4 - || tokenJti.version() != 4 - || operationId.variant() != 2 - || requestId.variant() != 2 - || tokenJti.variant() != 2 - || operationId.equals(tokenJti) - || !accountAuthority.accountId().equals(accountId) - || issuedAtEpochSecond <= 0L - || notBeforeEpochSecond <= 0L - || notBeforeEpochSecond > issuedAtEpochSecond - || expiresAtEpochSecond <= issuedAtEpochSecond - || expiresAtEpochSecond - issuedAtEpochSecond - > GameSessionAccountDelegationProfile.MAX_TOKEN_LIFETIME_SECONDS - || issuanceFence <= 0L - || accountAuthority.issuanceFence() != issuanceFence) { - throw invalid(); - } - } - } - @FunctionalInterface interface DelegationCandidateConsumer { /** The caller persists the exact candidate before any internal transient handoff. */ diff --git a/services/account-service/src/main/resources/db/migration/V1012__account_original_new_bound_gameplay_credentials.sql b/services/account-service/src/main/resources/db/migration/V1012__account_original_new_bound_gameplay_credentials.sql deleted file mode 100644 index 92acbbd693..0000000000 --- a/services/account-service/src/main/resources/db/migration/V1012__account_original_new_bound_gameplay_credentials.sql +++ /dev/null @@ -1,370 +0,0 @@ --- Purpose-bound ORIGINAL-NEW Account delegation lineage and protected rebind handle. --- The existing LOGIN issuance rows, their unscoped claim invariant, and their retained bytes are --- not rewritten. This row family has one fresh generation-1 lineage per exact original NEW lease. -CREATE TABLE account_original_new_bound_gameplay_issuances ( - operation_id UUID PRIMARY KEY, - request_id UUID NOT NULL UNIQUE, - account_uuid UUID NOT NULL REFERENCES accounts (account_uuid) ON DELETE RESTRICT, - caller_workload VARCHAR(256) NOT NULL, - request_digest VARCHAR(64) NOT NULL, - lease_id UUID NOT NULL UNIQUE, - lease_fence BIGINT NOT NULL, - binding_decision_id UUID NOT NULL UNIQUE, - binding_scope_sha256 VARCHAR(64) NOT NULL UNIQUE, - original_lease_evidence_sha256 VARCHAR(64) NOT NULL, - original_ack_receipt_xid VARCHAR(32) NOT NULL, - original_ack_evidence_sha256 VARCHAR(64) NOT NULL, - binding_scope_canonical_bytes BYTEA NOT NULL, - authority_tuple_canonical_bytes BYTEA NOT NULL, - membership_baseline_canonical_bytes BYTEA NOT NULL, - membership_version_canonical_bytes BYTEA NOT NULL, - outbox_checkpoints_canonical_bytes BYTEA NOT NULL, - issuance_fence BIGINT NOT NULL, - token_jti UUID NOT NULL UNIQUE, - token_generation BIGINT NOT NULL DEFAULT 1, - issued_at_epoch_second BIGINT NOT NULL, - not_before_epoch_second BIGINT NOT NULL, - expires_at_epoch_second BIGINT NOT NULL, - status VARCHAR(16) NOT NULL DEFAULT 'PENDING', - token_hash VARCHAR(64), - signer_kid VARCHAR(64), - signer_generation VARCHAR(19), - pending_registry_record_bytes BYTEA, - rebind_handle_sha256 VARCHAR(64) UNIQUE, - encrypted_result_envelope_sha256 VARCHAR(64), - encrypted_result_envelope_bytes BYTEA, - committed_registry_receipt_sha256 VARCHAR(64), - confirmed_admission_at_ms BIGINT, - confirmed_continuity_expires_at_ms BIGINT, - confirmation_readback_sha256 VARCHAR(64), - handle_consumed_at_ms BIGINT, - handle_consumption_request_id UUID, - created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, - committed_at TIMESTAMPTZ, - CONSTRAINT account_original_new_bound_identity_check CHECK ( - operation_id <> '00000000-0000-0000-0000-000000000000'::UUID - 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 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 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 lease_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 binding_decision_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}$' - AND operation_id <> token_jti), - CONSTRAINT account_original_new_bound_caller_check CHECK ( - caller_workload ~ '^spiffe://firemud/ns/[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?/sa/game-session-service$' - AND request_digest ~ '^[0-9a-f]{64}$'), - CONSTRAINT account_original_new_bound_fence_check CHECK ( - lease_fence > 0 AND issuance_fence > 0 AND token_generation = 1), - CONSTRAINT account_original_new_bound_source_check CHECK ( - binding_scope_sha256 ~ '^[0-9a-f]{64}$' - AND binding_scope_sha256 = encode(sha256(binding_scope_canonical_bytes), 'hex') - AND - original_lease_evidence_sha256 ~ '^[0-9a-f]{64}$' - AND original_ack_evidence_sha256 ~ '^[0-9a-f]{64}$' - AND original_ack_receipt_xid ~ '^[1-9][0-9]{0,19}$' - AND octet_length(binding_scope_canonical_bytes) BETWEEN 1 AND 4096 - AND jsonb_typeof(convert_from(binding_scope_canonical_bytes, 'UTF8')::jsonb) = 'object' - AND octet_length(authority_tuple_canonical_bytes) BETWEEN 1 AND 4096 - AND jsonb_typeof(convert_from(authority_tuple_canonical_bytes, 'UTF8')::jsonb) = 'object' - AND octet_length(membership_baseline_canonical_bytes) BETWEEN 1 AND 4096 - AND jsonb_typeof(convert_from(membership_baseline_canonical_bytes, 'UTF8')::jsonb) = 'object' - AND octet_length(membership_version_canonical_bytes) BETWEEN 1 AND 4096 - AND jsonb_typeof(convert_from(membership_version_canonical_bytes, 'UTF8')::jsonb) = 'object' - AND convert_from(membership_version_canonical_bytes, 'UTF8') <> '{}' - AND octet_length(outbox_checkpoints_canonical_bytes) BETWEEN 1 AND 8192 - AND jsonb_typeof(convert_from(outbox_checkpoints_canonical_bytes, 'UTF8')::jsonb) = 'array'), - CONSTRAINT account_original_new_bound_time_check CHECK ( - issued_at_epoch_second > 0 AND not_before_epoch_second > 0 - AND not_before_epoch_second <= issued_at_epoch_second - AND expires_at_epoch_second > issued_at_epoch_second - AND expires_at_epoch_second - issued_at_epoch_second <= 300), - CONSTRAINT account_original_new_bound_state_check CHECK (status IN ('PENDING', 'COMMITTED')), - CONSTRAINT account_original_new_bound_candidate_check CHECK ( - (token_hash IS NULL AND signer_kid IS NULL AND signer_generation IS NULL - AND pending_registry_record_bytes IS NULL AND rebind_handle_sha256 IS NULL - AND encrypted_result_envelope_sha256 IS NULL AND encrypted_result_envelope_bytes IS NULL - AND committed_registry_receipt_sha256 IS NULL AND committed_at IS NULL) - OR (token_hash IS NOT NULL AND token_hash ~ '^[0-9a-f]{64}$' - AND signer_kid IS NOT NULL AND signer_kid ~ '^[A-Za-z0-9_-]{1,64}$' - AND signer_generation IS NOT NULL AND signer_generation ~ '^[1-9][0-9]{0,18}$' - AND pending_registry_record_bytes IS NOT NULL - AND octet_length(pending_registry_record_bytes) BETWEEN 1 AND 16384 - AND rebind_handle_sha256 IS NOT NULL AND rebind_handle_sha256 ~ '^[0-9a-f]{64}$' - AND encrypted_result_envelope_sha256 IS NOT NULL - AND encrypted_result_envelope_sha256 ~ '^[0-9a-f]{64}$' - AND encrypted_result_envelope_bytes IS NOT NULL - AND octet_length(encrypted_result_envelope_bytes) BETWEEN 1 AND 65610 - AND ((status = 'PENDING' AND committed_registry_receipt_sha256 IS NULL AND committed_at IS NULL) - OR (status = 'COMMITTED' AND committed_registry_receipt_sha256 IS NOT NULL - AND committed_registry_receipt_sha256 ~ '^[0-9a-f]{64}$' - AND committed_at IS NOT NULL)))), - CONSTRAINT account_original_new_bound_confirmation_check CHECK ( - (confirmed_admission_at_ms IS NULL AND confirmed_continuity_expires_at_ms IS NULL - AND confirmation_readback_sha256 IS NULL) - OR (confirmed_admission_at_ms IS NOT NULL AND confirmed_admission_at_ms > 0 - AND status = 'COMMITTED' AND token_hash IS NOT NULL - AND confirmed_continuity_expires_at_ms IS NOT NULL - AND confirmed_continuity_expires_at_ms > confirmed_admission_at_ms - AND confirmation_readback_sha256 IS NOT NULL - AND confirmation_readback_sha256 ~ '^[0-9a-f]{64}$')), - CONSTRAINT account_original_new_bound_consumption_check CHECK ( - (handle_consumed_at_ms IS NULL AND handle_consumption_request_id IS NULL) - OR (handle_consumed_at_ms IS NOT NULL AND handle_consumed_at_ms > 0 - AND status = 'COMMITTED' AND confirmed_admission_at_ms IS NOT NULL - AND handle_consumed_at_ms >= confirmed_admission_at_ms - AND confirmed_continuity_expires_at_ms IS NOT NULL - AND handle_consumed_at_ms < confirmed_continuity_expires_at_ms - AND handle_consumption_request_id IS NOT NULL - AND handle_consumption_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}$')) -); - --- A row is admitted only when the exact original lease and its independently committed ACK receipt --- already exist. Their source bytes remain untouched and are compared by digest here and in Java. --- [jooq ignore start] -CREATE FUNCTION account_original_new_bound_gameplay_issuance_guard() -RETURNS TRIGGER LANGUAGE plpgsql AS $$ -DECLARE - original RECORD; - receipt RECORD; -BEGIN - IF TG_OP = 'DELETE' THEN - RAISE EXCEPTION 'Original-new gameplay issuance evidence cannot be deleted' USING ERRCODE = '23514'; - END IF; - PERFORM account_uuid FROM accounts WHERE account_uuid = NEW.account_uuid FOR UPDATE; - IF NOT FOUND THEN - RAISE EXCEPTION 'Original-new Account source is absent' USING ERRCODE = '23514'; - END IF; - SELECT request_id, account_uuid, lease_id, lease_fence, binding_decision_id, - evidence_sha256, evidence_json, expires_at_ms, status - INTO original FROM account_gameplay_admission_lease_operations - WHERE request_id = NEW.request_id AND lease_id = NEW.lease_id FOR SHARE; - SELECT request_id, account_uuid, lease_id, lease_fence, binding_decision_id, - evidence_sha256, receipt_xid - INTO receipt FROM account_gameplay_admission_original_commit_ack_receipts - WHERE request_id = NEW.request_id FOR SHARE; - IF original.request_id IS NULL OR original.status <> 'COMMITTED' - OR original.account_uuid <> NEW.account_uuid OR original.lease_id <> NEW.lease_id - OR original.lease_fence <> NEW.lease_fence - OR original.binding_decision_id <> NEW.binding_decision_id - OR original.evidence_sha256 <> NEW.original_lease_evidence_sha256 - OR original.evidence_json::jsonb -> 'bindingScope' - IS DISTINCT FROM convert_from(NEW.binding_scope_canonical_bytes, 'UTF8')::jsonb - OR original.evidence_json::jsonb -> 'authorityTuple' - IS DISTINCT FROM convert_from(NEW.authority_tuple_canonical_bytes, 'UTF8')::jsonb - OR original.evidence_json::jsonb -> 'membershipBaseline' - IS DISTINCT FROM convert_from(NEW.membership_baseline_canonical_bytes, 'UTF8')::jsonb - OR original.evidence_json::jsonb -> 'membershipBaseline' -> 'membershipVersion' - IS DISTINCT FROM convert_from(NEW.membership_version_canonical_bytes, 'UTF8')::jsonb - OR original.evidence_json::jsonb -> 'outboxCheckpoints' - IS DISTINCT FROM convert_from(NEW.outbox_checkpoints_canonical_bytes, 'UTF8')::jsonb - OR original.evidence_json::jsonb ->> 'issuanceFence' IS DISTINCT FROM NEW.issuance_fence::text - OR receipt.request_id IS NULL OR receipt.account_uuid <> NEW.account_uuid - OR receipt.lease_id <> NEW.lease_id OR receipt.lease_fence <> NEW.lease_fence - OR receipt.binding_decision_id <> NEW.binding_decision_id - OR receipt.evidence_sha256 <> NEW.original_ack_evidence_sha256 - OR receipt.receipt_xid <> NEW.original_ack_receipt_xid THEN - RAISE EXCEPTION 'Original-new credential requires the exact committed lease and ACK' - USING ERRCODE = '23514', CONSTRAINT = 'account_original_new_bound_original_commit_required'; - END IF; - IF TG_OP = 'INSERT' THEN - IF NEW.status <> 'PENDING' OR NEW.token_hash IS NOT NULL - OR NEW.signer_kid IS NOT NULL OR NEW.signer_generation IS NOT NULL - OR NEW.pending_registry_record_bytes IS NOT NULL OR NEW.rebind_handle_sha256 IS NOT NULL - OR NEW.encrypted_result_envelope_sha256 IS NOT NULL - OR NEW.encrypted_result_envelope_bytes IS NOT NULL - OR NEW.committed_registry_receipt_sha256 IS NOT NULL OR NEW.committed_at IS NOT NULL - OR NEW.confirmed_admission_at_ms IS NOT NULL - OR NEW.confirmed_continuity_expires_at_ms IS NOT NULL - OR NEW.confirmation_readback_sha256 IS NOT NULL - OR NEW.handle_consumed_at_ms IS NOT NULL - OR NEW.handle_consumption_request_id IS NOT NULL THEN - RAISE EXCEPTION 'Original-new lineage must start as unbound PENDING' - USING ERRCODE = '23514', CONSTRAINT = 'account_original_new_bound_initial_pending_only'; - END IF; - RETURN NEW; - END IF; - IF ROW(NEW.operation_id, NEW.request_id, NEW.account_uuid, NEW.caller_workload, - NEW.request_digest, NEW.lease_id, NEW.lease_fence, NEW.binding_decision_id, - NEW.binding_scope_sha256, - NEW.original_lease_evidence_sha256, NEW.original_ack_receipt_xid, - NEW.original_ack_evidence_sha256, NEW.binding_scope_canonical_bytes, - NEW.authority_tuple_canonical_bytes, NEW.membership_baseline_canonical_bytes, - NEW.membership_version_canonical_bytes, - NEW.outbox_checkpoints_canonical_bytes, NEW.issuance_fence, NEW.token_jti, - NEW.token_generation, NEW.issued_at_epoch_second, NEW.not_before_epoch_second, - NEW.expires_at_epoch_second, NEW.created_at) - IS DISTINCT FROM ROW(OLD.operation_id, OLD.request_id, OLD.account_uuid, OLD.caller_workload, - OLD.request_digest, OLD.lease_id, OLD.lease_fence, OLD.binding_decision_id, - OLD.binding_scope_sha256, - OLD.original_lease_evidence_sha256, OLD.original_ack_receipt_xid, - OLD.original_ack_evidence_sha256, OLD.binding_scope_canonical_bytes, - OLD.authority_tuple_canonical_bytes, OLD.membership_baseline_canonical_bytes, - OLD.membership_version_canonical_bytes, - OLD.outbox_checkpoints_canonical_bytes, OLD.issuance_fence, OLD.token_jti, - OLD.token_generation, OLD.issued_at_epoch_second, OLD.not_before_epoch_second, - OLD.expires_at_epoch_second, OLD.created_at) THEN - RAISE EXCEPTION 'Original-new lineage identity and frozen claims are immutable' - USING ERRCODE = '23514', CONSTRAINT = 'account_original_new_bound_identity_immutable'; - END IF; - IF OLD.token_hash IS NULL THEN - IF NEW.token_hash IS NULL OR NEW.signer_kid IS NULL OR NEW.signer_generation IS NULL - OR NEW.pending_registry_record_bytes IS NULL OR NEW.rebind_handle_sha256 IS NULL - OR NEW.encrypted_result_envelope_sha256 IS NULL - OR NEW.encrypted_result_envelope_bytes IS NULL - OR NEW.status <> 'PENDING' OR NEW.committed_registry_receipt_sha256 IS NOT NULL - OR NEW.committed_at IS NOT NULL THEN - RAISE EXCEPTION 'Original-new signed identity must bind once before commit' - USING ERRCODE = '23514', CONSTRAINT = 'account_original_new_bound_candidate_one_way'; - END IF; - ELSIF ROW(NEW.token_hash, NEW.signer_kid, NEW.signer_generation, - NEW.pending_registry_record_bytes, NEW.rebind_handle_sha256, - NEW.encrypted_result_envelope_sha256, NEW.encrypted_result_envelope_bytes) - IS DISTINCT FROM ROW(OLD.token_hash, OLD.signer_kid, OLD.signer_generation, - OLD.pending_registry_record_bytes, OLD.rebind_handle_sha256, - OLD.encrypted_result_envelope_sha256, OLD.encrypted_result_envelope_bytes) THEN - RAISE EXCEPTION 'Original-new signed identity and encrypted result are immutable' - USING ERRCODE = '23514', CONSTRAINT = 'account_original_new_bound_candidate_immutable'; - END IF; - IF OLD.status = 'PENDING' AND NEW.status = 'COMMITTED' - AND OLD.token_hash IS NOT NULL AND NEW.committed_registry_receipt_sha256 ~ '^[0-9a-f]{64}$' - AND NEW.committed_at IS NOT NULL - AND ROW(NEW.confirmed_admission_at_ms, NEW.confirmed_continuity_expires_at_ms, - NEW.confirmation_readback_sha256, NEW.handle_consumed_at_ms, - NEW.handle_consumption_request_id) - IS NOT DISTINCT FROM ROW(OLD.confirmed_admission_at_ms, OLD.confirmed_continuity_expires_at_ms, - OLD.confirmation_readback_sha256, OLD.handle_consumed_at_ms, - OLD.handle_consumption_request_id) THEN - RETURN NEW; - END IF; - IF NEW.status IS DISTINCT FROM OLD.status - OR NEW.committed_registry_receipt_sha256 IS DISTINCT FROM OLD.committed_registry_receipt_sha256 - OR NEW.committed_at IS DISTINCT FROM OLD.committed_at THEN - RAISE EXCEPTION 'Original-new issuance lifecycle transition conflicts' - USING ERRCODE = '23514', CONSTRAINT = 'account_original_new_bound_commit_once'; - END IF; - IF OLD.confirmed_admission_at_ms IS NOT NULL - AND ROW(NEW.confirmed_admission_at_ms, NEW.confirmed_continuity_expires_at_ms, - NEW.confirmation_readback_sha256) - IS DISTINCT FROM ROW(OLD.confirmed_admission_at_ms, OLD.confirmed_continuity_expires_at_ms, - OLD.confirmation_readback_sha256) THEN - RAISE EXCEPTION 'Original-new final-admission confirmation is immutable' - USING ERRCODE = '23514', CONSTRAINT = 'account_original_new_bound_confirmation_immutable'; - END IF; - IF OLD.confirmed_admission_at_ms IS NULL AND NEW.confirmed_admission_at_ms IS NOT NULL - AND (OLD.status <> 'COMMITTED' OR NEW.status <> 'COMMITTED' - OR OLD.token_hash IS NULL OR OLD.rebind_handle_sha256 IS NULL - OR OLD.encrypted_result_envelope_bytes IS NULL) THEN - RAISE EXCEPTION 'Original-new confirmation requires the committed protected result' - USING ERRCODE = '23514', CONSTRAINT = 'account_original_new_bound_confirmation_after_commit'; - END IF; - IF OLD.handle_consumed_at_ms IS NOT NULL - AND ROW(NEW.handle_consumed_at_ms, NEW.handle_consumption_request_id) - IS DISTINCT FROM ROW(OLD.handle_consumed_at_ms, OLD.handle_consumption_request_id) THEN - RAISE EXCEPTION 'Original-new rebind handle consumption is immutable' - USING ERRCODE = '23514', CONSTRAINT = 'account_original_new_bound_consumption_immutable'; - END IF; - IF OLD.handle_consumed_at_ms IS NULL AND NEW.handle_consumed_at_ms IS NOT NULL - AND (OLD.status <> 'COMMITTED' OR NEW.status <> 'COMMITTED' - OR OLD.confirmed_admission_at_ms IS NULL - OR OLD.confirmed_continuity_expires_at_ms IS NULL - OR NEW.handle_consumed_at_ms < OLD.confirmed_admission_at_ms - OR NEW.handle_consumed_at_ms >= OLD.confirmed_continuity_expires_at_ms) THEN - RAISE EXCEPTION 'Original-new handle consumption requires prior current admission confirmation' - USING ERRCODE = '23514', CONSTRAINT = 'account_original_new_bound_consumption_after_confirmation'; - END IF; - RETURN NEW; -END; -$$; -CREATE TRIGGER account_original_new_bound_gameplay_issuance_guard -BEFORE INSERT OR UPDATE OR DELETE ON account_original_new_bound_gameplay_issuances -FOR EACH ROW EXECUTE FUNCTION account_original_new_bound_gameplay_issuance_guard(); - -CREATE FUNCTION account_original_new_bound_gameplay_issuance_no_truncate() -RETURNS TRIGGER LANGUAGE plpgsql AS $$ -BEGIN - IF EXISTS (SELECT 1 FROM account_original_new_bound_gameplay_issuances) THEN - RAISE EXCEPTION 'Original-new gameplay issuance evidence cannot be truncated' USING ERRCODE = '23514'; - END IF; - RETURN NULL; -END; -$$; -CREATE TRIGGER account_original_new_bound_gameplay_issuance_no_truncate -BEFORE TRUNCATE ON account_original_new_bound_gameplay_issuances -FOR EACH STATEMENT EXECUTE FUNCTION account_original_new_bound_gameplay_issuance_no_truncate(); --- [jooq ignore stop] - --- Extend the existing token-identity fence with an explicit purpose arm. Existing rows are LOGIN --- and retain their old source predicate; ORIGINAL_NEW fences require the separate immutable --- Account-owned ORIGINAL-NEW issuance row above to be COMMITTED. --- PostgreSQL supplies this name for the original inline foreign key; the jOOQ H2 --- interpreter assigns a different generated name. The real migration must remove it. --- [jooq ignore start] -ALTER TABLE account_gameplay_token_identity_fences - DROP CONSTRAINT account_gameplay_token_identity_fences_operation_id_fkey; --- [jooq ignore stop] -ALTER TABLE account_gameplay_token_identity_fences - ADD COLUMN source_kind VARCHAR(16) NOT NULL DEFAULT 'LOGIN'; -ALTER TABLE account_gameplay_token_identity_fences - ADD CONSTRAINT account_gameplay_token_identity_source_kind_check - CHECK (source_kind IN ('LOGIN', 'ORIGINAL_NEW')); - --- [jooq ignore start] -CREATE OR REPLACE 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; - IF NEW.source_kind = 'LOGIN' THEN - 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; - ELSIF NEW.source_kind = 'ORIGINAL_NEW' THEN - PERFORM operation_id FROM account_original_new_bound_gameplay_issuances - 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; - ELSE - RAISE EXCEPTION 'Account token fence purpose is unsupported' USING ERRCODE = '23514'; - END IF; - IF NOT FOUND THEN - RAISE EXCEPTION 'Account token fence requires exact COMMITTED purpose-bound 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.source_kind, 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.source_kind, 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; -$$; --- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V1013__account_original_ack_pg18_historical_recovery.sql b/services/account-service/src/main/resources/db/migration/V1013__account_original_ack_pg18_historical_recovery.sql deleted file mode 100644 index 67c22cbe7b..0000000000 --- a/services/account-service/src/main/resources/db/migration/V1013__account_original_ack_pg18_historical_recovery.sql +++ /dev/null @@ -1,142 +0,0 @@ --- Qualify PostgreSQL 18 historical original-ACK recovery through the existing canonical reader. --- Preserve V144/V146 and every original receipt/operation byte. PostgreSQL 16 remains supported; --- other majors remain denied. This read observes durability and never reconstructs the original --- physical-COMMIT acknowledgement, restamps its clock bound, writes a marker or forces WAL flush. --- The private owner ends capture before observing coverage, without lowering or recapturing --- the fence. The legacy direct SQL reader remains strict while holding its capture locks. --- PostgreSQL 18 retains the required read-only WAL insert/flush observations, top-level XID --- semantics and SERIALIZABLE snapshot isolation: --- https://www.postgresql.org/docs/18/functions-admin.html#FUNCTIONS-ADMIN-BACKUP --- https://www.postgresql.org/docs/18/functions-info.html#FUNCTIONS-TXID-SNAPSHOT --- https://www.postgresql.org/docs/18/transaction-iso.html#XACT-SERIALIZABLE --- [jooq ignore start] -CREATE FUNCTION account_gameplay_admission_capture_original_ack_receipt( - requested_request_id UUID, expected_sha TEXT, expected_decision UUID) -RETURNS TABLE ( - captured_receipt account_gameplay_admission_original_commit_ack_receipts, - wal_upper_fence pg_lsn, - capture_snapshot pg_snapshot, - capture_own_xid TEXT, - capture_initial_flush pg_lsn) -LANGUAGE plpgsql AS $$ -DECLARE - operation account_gameplay_admission_lease_operations%ROWTYPE; - receipt account_gameplay_admission_original_commit_ack_receipts%ROWTYPE; - locked_operation account_gameplay_admission_lease_operations%ROWTYPE; - locked_receipt account_gameplay_admission_original_commit_ack_receipts%ROWTYPE; - own_xid TEXT; - fixed_snapshot pg_snapshot; - insert_fence pg_lsn; - initial_flush_fence pg_lsn; -BEGIN - IF current_setting('transaction_isolation') IS DISTINCT FROM 'serializable' - OR current_setting('transaction_read_only') IS DISTINCT FROM 'off' THEN - RAISE EXCEPTION 'Writable SERIALIZABLE Account acknowledgement receipt read required' - USING ERRCODE = '23514', CONSTRAINT = 'account_admission_original_ack_receipt_transaction_required'; - END IF; - IF NOT ((current_setting('server_version_num')::integer >= 160000 - AND current_setting('server_version_num')::integer < 170000) - OR (current_setting('server_version_num')::integer >= 180000 - AND current_setting('server_version_num')::integer < 190000)) - OR pg_is_in_recovery() OR current_setting('fsync') IS DISTINCT FROM 'on' THEN - RAISE EXCEPTION 'Supported durable PostgreSQL 16 or 18 primary required for Account acknowledgement receipt read' - USING ERRCODE = '23514', CONSTRAINT = 'account_admission_original_ack_receipt_durable_primary'; - END IF; - -- Establish one fixed snapshot and its WAL upper fence before any heap read or row lock. - -- A receipt visible in this snapshot committed independently before this fence. - fixed_snapshot := pg_current_snapshot(); - own_xid := pg_current_xact_id_if_assigned()::text; - insert_fence := pg_current_wal_insert_lsn(); - initial_flush_fence := pg_current_wal_flush_lsn(); - IF insert_fence IS NULL OR insert_fence <= '0/0'::pg_lsn THEN - RAISE EXCEPTION 'Original Account acknowledgement receipt WAL coverage unavailable' - USING ERRCODE = '23514', CONSTRAINT = 'account_admission_original_ack_receipt_wal_coverage'; - END IF; - - SELECT * INTO operation FROM account_gameplay_admission_lease_operations - WHERE request_id = requested_request_id; - IF NOT FOUND THEN - RAISE EXCEPTION 'Original Account acknowledgement operation missing' - USING ERRCODE = '23514', CONSTRAINT = 'account_admission_original_ack_receipt_operation_required'; - END IF; - SELECT * INTO receipt FROM account_gameplay_admission_original_commit_ack_receipts - WHERE request_id = requested_request_id; - IF NOT FOUND OR operation.status IS DISTINCT FROM 'COMMITTED' - OR operation.finalization_xid IS NULL - OR expected_sha IS DISTINCT FROM operation.evidence_sha256 - OR expected_decision IS DISTINCT FROM operation.binding_decision_id - OR receipt.schema_version IS DISTINCT FROM 1 - OR receipt.account_uuid IS DISTINCT FROM operation.account_uuid - OR receipt.lease_id IS DISTINCT FROM operation.lease_id - OR receipt.lease_fence IS DISTINCT FROM operation.lease_fence - OR receipt.evidence_sha256 IS DISTINCT FROM operation.evidence_sha256 - OR receipt.binding_decision_id IS DISTINCT FROM operation.binding_decision_id - OR receipt.expires_at_ms IS DISTINCT FROM operation.expires_at_ms - OR receipt.finalization_xid IS DISTINCT FROM operation.finalization_xid - OR receipt.committed_before_ms <= 0 - OR receipt.committed_before_ms >= operation.expires_at_ms THEN - RAISE EXCEPTION 'Exact durable original Account acknowledgement receipt required' - USING ERRCODE = '23514', CONSTRAINT = 'account_admission_original_ack_receipt_required'; - END IF; - -- receipt_xid is the database-stamped top-level XID, so this excludes the current transaction - -- and any released subtransaction while retaining an independently committed historical row. - IF receipt.receipt_xid = own_xid THEN - RAISE EXCEPTION 'Original Account acknowledgement receipt requires independent commit' - USING ERRCODE = '23514', CONSTRAINT = 'account_admission_original_ack_receipt_independent'; - END IF; - - PERFORM 1 FROM accounts WHERE account_uuid = operation.account_uuid FOR UPDATE; - IF NOT FOUND THEN - RAISE EXCEPTION 'Original Account acknowledgement owner missing' - USING ERRCODE = '23514', CONSTRAINT = 'account_admission_original_ack_receipt_owner_required'; - END IF; - SELECT * INTO locked_operation FROM account_gameplay_admission_lease_operations - WHERE request_id = requested_request_id FOR UPDATE; - IF NOT FOUND OR locked_operation IS DISTINCT FROM operation THEN - RAISE EXCEPTION 'Exact durable original Account acknowledgement receipt required' - USING ERRCODE = '23514', CONSTRAINT = 'account_admission_original_ack_receipt_required'; - END IF; - SELECT * INTO locked_receipt FROM account_gameplay_admission_original_commit_ack_receipts - WHERE request_id = requested_request_id FOR UPDATE; - IF NOT FOUND OR locked_receipt IS DISTINCT FROM receipt THEN - RAISE EXCEPTION 'Exact durable original Account acknowledgement receipt required' - USING ERRCODE = '23514', CONSTRAINT = 'account_admission_original_ack_receipt_required'; - END IF; - - -- This is pending evidence only. The private owner must independently observe durable - -- coverage of this exact frozen fence after the capture transaction successfully completes. - RETURN QUERY SELECT receipt, insert_fence, fixed_snapshot, own_xid, initial_flush_fence; -END; -$$; - -CREATE OR REPLACE FUNCTION account_gameplay_admission_read_original_ack_receipt_durably( - requested_request_id UUID, expected_sha TEXT, expected_decision UUID) -RETURNS SETOF account_gameplay_admission_original_commit_ack_receipts LANGUAGE plpgsql AS $$ -DECLARE - captured RECORD; - receipt account_gameplay_admission_original_commit_ack_receipts%ROWTYPE; - flush_fence pg_lsn; - observation INTEGER; -BEGIN - SELECT * INTO STRICT captured FROM account_gameplay_admission_capture_original_ack_receipt( - requested_request_id, expected_sha, expected_decision); - receipt := captured.captured_receipt; - -- Direct SQL callers retain the strict in-transaction proof. A capture by itself is never a - -- durable result; private owner continuation observes this same fence outside its SQL locks. - FOR observation IN 1..50 LOOP - flush_fence := pg_current_wal_flush_lsn(); - EXIT WHEN flush_fence IS NOT NULL AND flush_fence >= captured.wal_upper_fence; - IF observation = 50 THEN - RAISE EXCEPTION 'Original Account acknowledgement receipt WAL coverage unavailable' - USING ERRCODE = '23514', CONSTRAINT = 'account_admission_original_ack_receipt_wal_coverage', - DETAIL = format('snapshot=%s own_xid_if_assigned=%s finalization_xid=%s receipt_xid=%s insert_fence=%s initial_flush=%s final_flush=%s unchanged_expiry_ms=%s', - captured.capture_snapshot, captured.capture_own_xid, - receipt.finalization_xid, receipt.receipt_xid, captured.wal_upper_fence, - captured.capture_initial_flush, flush_fence, receipt.expires_at_ms); - END IF; - PERFORM pg_sleep(0.01); - END LOOP; - RETURN NEXT receipt; -END; -$$; --- [jooq ignore stop] diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionDefinitiveAbortCompositionIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionDefinitiveAbortCompositionIntegrationTest.java index 620f5d6eab..496d9e3fc8 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionDefinitiveAbortCompositionIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionDefinitiveAbortCompositionIntegrationTest.java @@ -640,7 +640,7 @@ void actualCompletedMemberAckSurvivesAccountAbortAndRetainsUnresolvedPhysicalCle @Test void actualAcknowledgedAbortCleanupSurvivesLaterAccountIntentAndRetiresExactIssuerMember() throws Exception { - try (var session = open(MigrationVersion.fromVersion("1038"))) { + try (var session = open(true)) { var acknowledgement = session.gs.repairAccountMember(); assertThat(acknowledgement.transitionId()).isEqualTo(session.gs.transitionId()); assertThat(session.gs.hasExactAccountMember()).isTrue(); @@ -681,40 +681,10 @@ void actualAcknowledgedAbortCleanupSurvivesLaterAccountIntentAndRetiresExactIssu assertThat(session.gs.hasExactOtherControllerMember(newerMemberSeed)).isTrue(); assertThat(session.gs.hasExactAccountMember()).isTrue(); - var retainedRowsBeforeUpgrade = session.gs.retainedFirstNewAbortRowsImage(); - var migrationHistoryBeforeUpgrade = session.gs.migrationHistoryImage(); - assertThat(migrationHistoryBeforeUpgrade) - .anyMatch(row -> row.contains("V1000__create_saga_schema.sql")) - .anyMatch(row -> row.contains("V1001__saga_instance_table.sql")) - .anyMatch(row -> row.contains("V1002__saga_step_table.sql")); - var issuerFieldsBeforeUpgrade = session.gs.issuerPartitionFieldSetBytes(); - assertThat( - session - .gs - .dsl() - .fetchSingle( - "SELECT state FROM game_session_canonical_account_coverage_control" - + " WHERE account_id = ?", - session.gs.candidate().accountId()) - .get(0, String.class)) - .isEqualTo("ACQUISITION_INTENT"); - assertThat( - session.gs.upgradeWithDefaultGameSessionMigrations( - MigrationVersion.fromVersion("1038.1"))) - .isEqualTo(1); - var migrationHistoryAfterUpgrade = session.gs.migrationHistoryImage(); - assertThat(migrationHistoryAfterUpgrade).hasSize(migrationHistoryBeforeUpgrade.size() + 1); - for (int index = 0; index < migrationHistoryBeforeUpgrade.size(); index++) { - assertThat(migrationHistoryAfterUpgrade.get(index)) - .isEqualTo(migrationHistoryBeforeUpgrade.get(index)); - } - assertThat(migrationHistoryAfterUpgrade.get(migrationHistoryAfterUpgrade.size() - 1)) - .contains("1038.1", "V1038.1__retained_first_new_abort_cleanup_account_control.sql"); - assertThat(session.gs.retainedFirstNewAbortRowsImage()).isEqualTo(retainedRowsBeforeUpgrade); + var retainedRowsBeforeRetry = session.gs.retainedFirstNewAbortRowsImage(); + var issuerFieldsBeforeRetry = session.gs.issuerPartitionFieldSetBytes(); assertThat(session.gs.memberAcknowledgementImage()).isEqualTo(originalAck); assertThat(session.gs.accountObligationPhaseImage()).isEqualTo(originalPhase); - assertThat(session.gs.issuerPartitionFieldSetBytes()) - .containsExactly(issuerFieldsBeforeUpgrade); assertThat(session.gs.hasExactAccountMember()).isTrue(); assertThat(session.gs.hasExactOtherControllerMember(newerMemberSeed)).isTrue(); @@ -729,11 +699,11 @@ void actualAcknowledgedAbortCleanupSurvivesLaterAccountIntentAndRetiresExactIssu assertThat(abortRetry.accountOperation().originalLeaseEvidence().canonicalJson()) .isEqualTo(session.lease.canonicalJson()); assertThat(session.image()).isEqualTo(imageBeforeAbortRetry); - assertThat(session.gs.retainedFirstNewAbortRowsImage()).isEqualTo(retainedRowsBeforeUpgrade); + assertThat(session.gs.retainedFirstNewAbortRowsImage()).isEqualTo(retainedRowsBeforeRetry); assertThat(session.gs.memberAcknowledgementImage()).isEqualTo(originalAck); assertThat(session.gs.accountObligationPhaseImage()).isEqualTo(originalPhase); assertThat(session.gs.issuerPartitionFieldSetBytes()) - .containsExactly(issuerFieldsBeforeUpgrade); + .containsExactly(issuerFieldsBeforeRetry); var pendingRelease = session.gs.prepareIssuerRelease(); var releaseReadback = session.gs.projectIssuerRelease(pendingRelease); @@ -840,11 +810,6 @@ private Session open(boolean prepareMemberRepair) throws Exception { return new Session(prepareMemberRepair); } - private Session open(MigrationVersion migrationTarget) throws Exception { - accountFixtures.temporaryDirectory = temporaryDirectory; - return new Session(true, migrationTarget); - } - private final class Session implements AutoCloseable { private final PhysicalRedisFixture redis = PhysicalRedisFixture.start(); private final AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.Fixture diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java index e3f51576fb..537621aa6b 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java @@ -5,13 +5,9 @@ import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import integration.net.firedevops.firemud.accountservice.repository.AccountPostgresIntegrationFixture; -import java.nio.charset.StandardCharsets; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; import java.sql.Connection; import java.sql.SQLException; import java.time.Instant; -import java.util.HexFormat; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @@ -19,9 +15,6 @@ import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; -import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionOriginalAckReceipt; -import net.firedevops.firemud.accountservice.dto.AccountGameplayTokenIdentityFence.SourceKind; -import net.firedevops.firemud.accountservice.dto.AccountGameplayTokenIdentityFence.TokenIdentity; import net.firedevops.firemud.accountservice.entity.Account; import net.firedevops.firemud.accountservice.repository.AccountGameplayAdmissionOriginalCommitExecutor.OriginalCommitAcknowledgement; import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; @@ -41,14 +34,13 @@ import org.springframework.transaction.support.TransactionTemplate; /** - * PostgreSQL 18 proof for fresh and historical original-ACK and bounded ORIGINAL-NEW storage. + * PostgreSQL 18 proof for fresh original-ACK storage only. * *

Tests exercise the original operation's physical COMMIT, its opaque pre-expiry - * acknowledgement, and a separate physical receipt COMMIT. The lineage test uses controlled token, - * registry and encrypted-envelope artifacts to prove immutable generation and one-use storage; it - * does not claim production signing, Redis acknowledgement, current caller authority, final - * admission, production privilege adoption, or gameplay. Historical recovery observes WAL coverage - * without reconstructing the original acknowledgement or changing its clock bound. + * acknowledgement, and a separate physical receipt COMMIT. PostgreSQL 18 does not enable the + * retained historical durability reader or lost-acknowledgement recovery. SQL and JVM storage proof + * establish no authentication, current ownership, admission, production privilege adoption, or + * gameplay. */ @Execution(ExecutionMode.SAME_THREAD) class AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest { @@ -321,7 +313,7 @@ void ownFinalizationAndReleasedSubtransactionCannotSupplyIndependentOriginal() { } @Test - void ownReceiptAndReleasedSubtransactionCannotSupplyHistoricalDurability() { + void historicalDurableReadRemainsDeniedOnPostgres18AfterReceiptInsert() { for (boolean subtransaction : List.of(false, true)) { var context = context(); var ack = finalized(context, 15000); @@ -337,172 +329,11 @@ void ownReceiptAndReleasedSubtransactionCannotSupplyHistoricalDurability() { context.dsl().execute("RELEASE SAVEPOINT receipt_creation"); repository(context).readDurably(ack.evidence(), ack.decisionId()); })) - .hasMessageContaining("requires independent commit"); + .hasMessageContaining("Supported durable PostgreSQL 16 primary required"); assertThat(context.dsl().fetchCount(DSL.table(RECEIPTS))).isZero(); } } - @Test - void historicalCaptureFreezesItsFenceBeforeLocksAndObservesCoverageAfterCompletion() { - var context = context(); - var ack = finalized(context, 15000); - var expected = - new AccountGameplayAdmissionOriginalAckReceiptCommitExecutor(context.admin()).confirm(ack); - var storageBefore = ackStorageSnapshot(context); - var sourcesBefore = sourceSnapshot(context); - var pending = - java.util.Objects.requireNonNull( - context - .transaction() - .execute( - status -> { - var captured = - repository(context).captureHistorical(ack.evidence(), ack.decisionId()); - assertThat(captured.receipt()).isEqualTo(expected); - // Actual capture locks append WAL after the original frozen upper fence. - // That later insert position must never replace the SQL-issued proof fence. - assertThat( - context - .dsl() - .fetchSingle( - "SELECT pg_current_wal_insert_lsn() > ?::pg_lsn", - captured.walUpperFence()) - .get(0, Boolean.class)) - .isTrue(); - return captured; - })); - String exactFrozenFence = pending.walUpperFence(); - // No SQL transaction/row lock remains open. Completion itself is not accepted as proof; - // positively observe durable WAL coverage of precisely the captured fence. - assertThat( - context - .dsl() - .fetchSingle("SELECT pg_current_wal_flush_lsn() >= ?::pg_lsn", exactFrozenFence) - .get(0, Boolean.class)) - .isTrue(); - assertThat(pending.walUpperFence()).isEqualTo(exactFrozenFence); - AccountGameplayAdmissionOriginalAckReceipt independentReadback = - context - .transaction() - .execute(status -> repository(context).readExact(ack.evidence(), ack.decisionId())); - assertThat(independentReadback).isEqualTo(pending.receipt()); - assertThat( - new AccountGameplayAdmissionOriginalAckReceiptCommitExecutor(context.admin()) - .read(ack.evidence(), ack.decisionId())) - .isEqualTo(expected); - assertThat(ackStorageSnapshot(context)).isEqualTo(storageBefore); - assertThat(sourceSnapshot(context)).isEqualTo(sourcesBefore); - } - - @Test - void historicalRecoveryRefusesChangedDigestDecisionAndMissingOperationWithoutChangingRows() { - var context = context(); - var ack = finalized(context, 15000); - var expected = - new AccountGameplayAdmissionOriginalAckReceiptCommitExecutor(context.admin()).confirm(ack); - var storageBefore = ackStorageSnapshot(context); - var sourcesBefore = sourceSnapshot(context); - for (boolean changedDigest : List.of(false, true)) { - assertThatThrownBy( - () -> - context - .transaction() - .executeWithoutResult( - status -> - context - .dsl() - .fetch( - "SELECT * FROM account_gameplay_admission_read_original_ack_receipt_durably(?, ?, ?)", - request(ack.evidence()), - changedDigest ? "0".repeat(64) : ack.evidence().sha256(), - changedDigest ? ack.decisionId() : UUID.randomUUID()))) - .hasMessageContaining("Exact durable original Account acknowledgement receipt required"); - } - assertThatThrownBy( - () -> - context - .transaction() - .executeWithoutResult( - status -> - context - .dsl() - .fetch( - "SELECT * FROM account_gameplay_admission_read_original_ack_receipt_durably(?, ?, ?)", - UUID.randomUUID(), - ack.evidence().sha256(), - ack.decisionId()))) - .hasMessageContaining("Original Account acknowledgement operation missing"); - assertThat( - new AccountGameplayAdmissionOriginalAckReceiptCommitExecutor(context.admin()) - .read(ack.evidence(), ack.decisionId())) - .isEqualTo(expected); - assertThat(ackStorageSnapshot(context)).isEqualTo(storageBefore); - assertThat(sourceSnapshot(context)).isEqualTo(sourcesBefore); - } - - @Test - void historicalRecoveryCannotSeeReceiptCommittedAfterItsFixedSnapshot() throws Exception { - var context = context(); - var ack = finalized(context, 15000); - try (var stale = context.admin().getConnection()) { - stale.setAutoCommit(false); - stale.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE); - DSL.using(stale).fetchSingle("SELECT pg_current_snapshot()"); - var expected = - new AccountGameplayAdmissionOriginalAckReceiptCommitExecutor(context.admin()) - .confirm(ack); - var storageBefore = ackStorageSnapshot(context); - assertThatThrownBy( - () -> - DSL.using(stale) - .fetch( - "SELECT * FROM account_gameplay_admission_read_original_ack_receipt_durably(?, ?, ?)", - request(ack.evidence()), - ack.evidence().sha256(), - ack.decisionId())) - .hasMessageContaining("Exact durable original Account acknowledgement receipt required"); - stale.rollback(); - assertThat( - new AccountGameplayAdmissionOriginalAckReceiptCommitExecutor(context.admin()) - .read(ack.evidence(), ack.decisionId())) - .isEqualTo(expected); - assertThat(ackStorageSnapshot(context)).isEqualTo(storageBefore); - } - } - - @Test - void v1013QualifiesRetainedPg18ReceiptWithoutChangingHistoricalStorage() { - var context = context("1012"); - var ack = finalized(context, 15000); - var expected = - new AccountGameplayAdmissionOriginalAckReceiptCommitExecutor(context.admin()).confirm(ack); - var storageBefore = ackStorageSnapshot(context); - var sourcesBefore = sourceSnapshot(context); - assertThatThrownBy( - () -> - context - .transaction() - .execute( - status -> - repository(context).readDurably(ack.evidence(), ack.decisionId()))) - .hasMessageContaining("Supported durable PostgreSQL 16 primary required"); - Flyway.configure() - .dataSource(context.admin()) - .schemas(context.schema()) - .defaultSchema(context.schema()) - .placeholders(Map.of("serviceSchema", context.schema())) - .locations("classpath:db/migration") - .target("1013") - .load() - .migrate(); - assertThat( - new AccountGameplayAdmissionOriginalAckReceiptCommitExecutor(context.admin()) - .read(ack.evidence(), ack.decisionId())) - .isEqualTo(expected); - assertThat(ackStorageSnapshot(context)).isEqualTo(storageBefore); - assertThat(sourceSnapshot(context)).isEqualTo(sourcesBefore); - } - @Test void staleSnapshotBeforeOriginalCommitCannotCreateAcknowledgementReceipt() throws Exception { var context = context(); @@ -823,7 +654,7 @@ void acknowledgementFromAnotherPostgresDataSourceCannotCreateReceipt() { } @Test - void lostReceiptCommitAcknowledgementRecoversHistoricallyWithoutReconstructingOriginal() { + void lostReceiptCommitAcknowledgementDoesNotReconstructFreshReceiptDurability() { var context = context(); var evidence = pending(context, 15000); UUID decision = UUID.randomUUID(); @@ -859,17 +690,10 @@ void lostReceiptCommitAcknowledgementRecoversHistoricallyWithoutReconstructingOr assertThat(retained.get("receipt_xid")).isNotEqualTo(ack.finalizationXid()); assertThat(operation(context, evidence)).isEqualTo(operationBefore); - var storageBefore = ackStorageSnapshot(context); - // A replacement executor proves the retained receipt through the canonical historical reader; - // it never reruns the original finalizer or substitutes its later COMMIT for original timing. - var replacement = new AccountGameplayAdmissionOriginalAckReceiptCommitExecutor(context.admin()); - var recovered = replacement.read(evidence, decision); - assertThat(recovered.receiptXid()).isEqualTo(retained.get("receipt_xid")); - assertThat(recovered.committedBeforeMs()).isEqualTo(ack.committedBeforeMs()); - assertThat(recovered.finalizationXid()).isEqualTo(ack.finalizationXid()); - assertThat(new AccountGameplayAdmissionOriginalAckReceiptCommitExecutor(source).confirm(ack)) - .isEqualTo(recovered); - assertThat(ackStorageSnapshot(context)).isEqualTo(storageBefore); + // PostgreSQL 18 deliberately cannot recover a retained receipt from its retry COMMIT. + assertThatThrownBy( + () -> new AccountGameplayAdmissionOriginalAckReceiptCommitExecutor(source).confirm(ack)) + .hasMessageContaining("Supported durable PostgreSQL 16 primary required"); assertThat(receipt(context)).isEqualTo(retained); assertThat(operation(context, evidence)).isEqualTo(operationBefore); assertThat(sourceSnapshot(context)).isEqualTo(sourcesBefore); @@ -888,7 +712,7 @@ void returnedCommitFaultConnectionClosesItsPhysicalConnection() throws SQLExcept } @Test - void retainedCommittedRetryCannotMintFreshAckAndHistoricalReceiptRecoveryPreservesOriginal() { + void retainedCommittedRetryCannotMintFreshAckAndHistoricalReceiptRecoveryStaysDenied() { var context = context(); var ack = finalized(context, 15000); var receiptExecutor = @@ -896,8 +720,6 @@ void retainedCommittedRetryCannotMintFreshAckAndHistoricalReceiptRecoveryPreserv var receipt = receiptExecutor.confirm(ack); var operationBefore = operation(context, ack.evidence()); var receiptBefore = receipt(context); - var storageBefore = ackStorageSnapshot(context); - var sourcesBefore = sourceSnapshot(context); assertThat(receipt.finalizationXid()).isEqualTo(ack.finalizationXid()); assertThat(receipt.receiptXid()).isNotEqualTo(ack.finalizationXid()); @@ -906,17 +728,12 @@ void retainedCommittedRetryCannotMintFreshAckAndHistoricalReceiptRecoveryPreserv new AccountGameplayAdmissionOriginalCommitExecutor(context.admin()) .execute(ack.evidence(), ack.decisionId())) .hasMessageContaining("Fresh owned Account original COMMIT required"); - assertThat(receiptExecutor.read(ack.evidence(), ack.decisionId())).isEqualTo(receipt); - assertThat(receiptExecutor.confirm(ack)).isEqualTo(receipt); - // A new executor, after the original lease expires, observes the same historical evidence. - // This supplies neither renewed admission authority nor a fresh original acknowledgement. - waitPastExpiry(context, ack); - assertThat( - new AccountGameplayAdmissionOriginalAckReceiptCommitExecutor(context.admin()) - .read(ack.evidence(), ack.decisionId())) - .isEqualTo(receipt); - assertThat(ackStorageSnapshot(context)).isEqualTo(storageBefore); - assertThat(sourceSnapshot(context)).isEqualTo(sourcesBefore); + assertThatThrownBy(() -> receiptExecutor.read(ack.evidence(), ack.decisionId())) + .hasMessageContaining("Supported durable PostgreSQL 16 primary required"); + // A retained receipt's retry COMMIT is not historical durability proof on PostgreSQL 18. + assertThatThrownBy(() -> receiptExecutor.confirm(ack)) + .hasMessageContaining("Supported durable PostgreSQL 16 primary required"); + assertThat(operation(context, ack.evidence())).isEqualTo(operationBefore); assertThat(receipt(context)).isEqualTo(receiptBefore); assertThat(context.dsl().fetchCount(DSL.table(RECEIPTS))).isOne(); @@ -1029,241 +846,7 @@ void genuineAckSqlEntryRequiresWritableSerializableTransactionAndKeepsFinalizerS assertThat(context.dsl().fetchCount(DSL.table(RECEIPTS))).isZero(); } - @Test - void originalNewLineageFreezesGenerationAndHandleUntilAuthenticatedAdmissionConfirmation() { - var context = context(); - var ack = finalized(context, 15000, 1L); - var receipt = - new AccountGameplayAdmissionOriginalAckReceiptCommitExecutor(context.admin()).confirm(ack); - var repository = new AccountOriginalNewBoundGameplayIssuanceRepository(context.dsl()); - long nowSeconds = Instant.now().getEpochSecond(); - UUID lineageId = UUID.randomUUID(); - UUID tokenJti = UUID.randomUUID(); - - var created = - context - .transaction() - .execute( - status -> - repository.beginGenesis( - ack.evidence(), - receipt, - lineageId, - tokenJti, - nowSeconds, - nowSeconds, - nowSeconds + 300L)); - assertThat(created.tokenGeneration()).isEqualTo(1L); - assertThat(created.status()) - .isEqualTo(AccountOriginalNewBoundGameplayIssuanceRepository.Status.PENDING); - assertThat(created.lineageId()).isEqualTo(lineageId); - assertThat(created.tokenJti()).isEqualTo(tokenJti); - assertThat(new String(created.membershipBaselineCanonicalBytes(), StandardCharsets.UTF_8)) - .contains("\"membershipLifecycleState\":\"ACTIVE\""); - assertThat(new String(created.outboxCheckpointsCanonicalBytes(), StandardCharsets.UTF_8)) - .contains("account:auth-authority:v1:account/"); - assertThat(created.tokenHash()).isNull(); - assertThat(created.rebindHandleSha256()).isNull(); - assertThat(created.confirmedAdmissionAtMillis()).isNull(); - - // A lost reply supplies fresh proposed IDs and times; the durable owner returns the original - // lineage and frozen claims rather than opening another generation or signing identity. - var retry = - context - .transaction() - .execute( - status -> - repository.beginGenesis( - ack.evidence(), - receipt, - UUID.randomUUID(), - UUID.randomUUID(), - nowSeconds + 1L, - nowSeconds + 1L, - nowSeconds + 301L)); - assertThat(retry.lineageId()).isEqualTo(created.lineageId()); - assertThat(retry.tokenJti()).isEqualTo(created.tokenJti()); - assertThat(retry.issuedAtEpochSecond()).isEqualTo(created.issuedAtEpochSecond()); - assertThat(retry.notBeforeEpochSecond()).isEqualTo(created.notBeforeEpochSecond()); - assertThat(retry.expiresAtEpochSecond()).isEqualTo(created.expiresAtEpochSecond()); - assertThat(retry.membershipBaselineCanonicalBytes()) - .containsExactly(created.membershipBaselineCanonicalBytes()); - assertThat(retry.membershipVersionCanonicalBytes()) - .containsExactly(created.membershipVersionCanonicalBytes()); - assertThat(retry.outboxCheckpointsCanonicalBytes()) - .containsExactly(created.outboxCheckpointsCanonicalBytes()); - assertThat(context.dsl().fetchCount(DSL.table("account_original_new_bound_gameplay_issuances"))) - .isOne(); - - byte[] registryRecord = "controlled-pending-record".getBytes(StandardCharsets.UTF_8); - byte[] protectedEnvelope = "controlled-encrypted-result".getBytes(StandardCharsets.UTF_8); - byte[] opaqueHandle = new byte[32]; - java.util.Arrays.fill(opaqueHandle, (byte) 0x2a); - String tokenHash = "a".repeat(64); - String handleHash = sha256(opaqueHandle); - var bound = - context - .transaction() - .execute( - status -> - repository.bindSignedResult( - retry, - tokenHash, - "controlled-test-kid", - "1", - registryRecord, - handleHash, - protectedEnvelope)); - assertThat(bound.status()) - .isEqualTo(AccountOriginalNewBoundGameplayIssuanceRepository.Status.PENDING); - assertThat(bound.rebindHandleSha256()).isEqualTo(handleHash); - assertThat(bound.confirmedAdmissionAtMillis()).isNull(); - assertThat(bound.handleConsumedAtMillis()).isNull(); - assertThatThrownBy( - () -> - context - .transaction() - .execute( - status -> - repository.bindSignedResult( - bound, - "c".repeat(64), - "controlled-test-kid", - "1", - registryRecord, - handleHash, - protectedEnvelope))) - .hasMessageContaining("Original-new bound gameplay issuance is unavailable"); - assertThat(repositoryRead(context, repository, ack.evidence()).tokenHash()) - .isEqualTo(tokenHash); - - String pendingRegistryReceipt = "d".repeat(64); - var committed = - context.transaction().execute(status -> repository.commit(bound, pendingRegistryReceipt)); - assertThat(committed.status()) - .isEqualTo(AccountOriginalNewBoundGameplayIssuanceRepository.Status.COMMITTED); - assertThat(committed.committedRegistryReceiptSha256()).isEqualTo(pendingRegistryReceipt); - TokenIdentity tokenIdentity = - new TokenIdentity( - committed.accountId(), - committed.lineageId(), - committed.requestId(), - committed.tokenHash(), - committed.tokenJti(), - committed.notBeforeEpochSecond(), - committed.tokenGeneration(), - committed.issuanceFence(), - SourceKind.ORIGINAL_NEW); - var activeTokenFence = - context - .transaction() - .execute( - status -> - new AccountGameplayTokenIdentityFenceRepository(context.dsl()) - .registerCommittedOriginalNewIssuance(tokenIdentity)); - assertThat(activeTokenFence.identity().sourceKind()).isEqualTo(SourceKind.ORIGINAL_NEW); - assertThat(activeTokenFence.tokenIdentityFence()).isEqualTo(1L); - var recoveredActiveTokenFence = - context - .transaction() - .execute( - status -> - new AccountGameplayTokenIdentityFenceRepository(context.dsl()) - .requireActiveForUpdate(tokenIdentity)); - assertThat(recoveredActiveTokenFence).isEqualTo(activeTokenFence); - UUID consumeRequest = UUID.randomUUID(); - assertThatThrownBy( - () -> - context - .transaction() - .execute( - status -> - repository.consumeOneUseHandle( - committed, handleHash, consumeRequest, 1L))) - .hasMessageContaining("Original-new bound gameplay issuance is unavailable"); - - long databaseNow = - context - .dsl() - .fetchSingle("SELECT floor(extract(epoch FROM clock_timestamp()) * 1000)::bigint") - .get(0, Long.class); - long actualAdmissionAt = databaseNow - 1L; - long continuityExpiresAt = actualAdmissionAt + 300000L; - String authenticatedReadback = - sha256("authenticated-final-readback".getBytes(StandardCharsets.UTF_8)); - var confirmed = - context - .transaction() - .execute( - status -> - repository.confirmFinalAdmission( - committed, actualAdmissionAt, continuityExpiresAt, authenticatedReadback)); - assertThat(confirmed.confirmedAdmissionAtMillis()).isEqualTo(actualAdmissionAt); - assertThat(confirmed.confirmedContinuityExpiresAtMillis()).isEqualTo(continuityExpiresAt); - assertThat(confirmed.confirmationReadbackSha256()).isEqualTo(authenticatedReadback); - var sameConfirmationRetry = - context - .transaction() - .execute( - status -> - repository.confirmFinalAdmission( - confirmed, actualAdmissionAt, continuityExpiresAt, authenticatedReadback)); - assertThat(sameConfirmationRetry.confirmedAdmissionAtMillis()).isEqualTo(actualAdmissionAt); - assertThat(sameConfirmationRetry.confirmationReadbackSha256()).isEqualTo(authenticatedReadback); - assertThatThrownBy( - () -> - context - .transaction() - .execute( - status -> - repository.confirmFinalAdmission( - confirmed, - actualAdmissionAt + 1L, - continuityExpiresAt + 1L, - authenticatedReadback))) - .hasMessageContaining("Original-new bound gameplay issuance is unavailable"); - - var consumed = - context - .transaction() - .execute( - status -> - repository.consumeOneUseHandle( - confirmed, handleHash, consumeRequest, actualAdmissionAt)); - assertThat(consumed.handleConsumptionRequestId()).isEqualTo(consumeRequest); - assertThat(consumed.handleConsumedAtMillis()).isBetween(actualAdmissionAt, continuityExpiresAt); - var sameConsumeRetry = - context - .transaction() - .execute( - status -> - repository.consumeOneUseHandle( - consumed, handleHash, consumeRequest, actualAdmissionAt)); - assertThat(sameConsumeRetry.handleConsumedAtMillis()) - .isEqualTo(consumed.handleConsumedAtMillis()); - assertThatThrownBy( - () -> - context - .transaction() - .execute( - status -> - repository.consumeOneUseHandle( - sameConsumeRetry, - handleHash, - UUID.randomUUID(), - actualAdmissionAt))) - .hasMessageContaining("Original-new bound gameplay issuance is unavailable"); - - java.util.Arrays.fill(registryRecord, (byte) 0); - java.util.Arrays.fill(protectedEnvelope, (byte) 0); - java.util.Arrays.fill(opaqueHandle, (byte) 0); - } - private static Context context() { - return context("latest"); - } - - private static Context context(String target) { String schema = "protected_" + UUID.randomUUID().toString().replace("-", ""); var admin = POSTGRES.dataSource(schema); Flyway.configure() @@ -1272,7 +855,6 @@ private static Context context(String target) { .defaultSchema(schema) .placeholders(Map.of("serviceSchema", schema)) .locations("classpath:db/migration") - .target(target) .load() .migrate(); var transaction = new TransactionTemplate(new DataSourceTransactionManager(admin)); @@ -1284,26 +866,6 @@ private static Context context(String target) { transaction); } - private static AccountOriginalNewBoundGameplayIssuanceRepository.Genesis repositoryRead( - Context context, - AccountOriginalNewBoundGameplayIssuanceRepository repository, - AccountGameplayAdmissionLeaseEvidence evidence) { - return context - .transaction() - .execute( - status -> - repository.readByLease( - UUID.fromString((String) evidence.carrier().get("leaseId")))); - } - - private static String sha256(byte[] value) { - try { - return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value)); - } catch (NoSuchAlgorithmException impossible) { - throw new AssertionError(impossible); - } - } - private static javax.sql.DataSource loseCommitAcknowledgementAfter( javax.sql.DataSource delegate, java.util.concurrent.atomic.AtomicInteger physicalCommits, @@ -1353,12 +915,7 @@ public Connection getConnection() throws SQLException { } private static OriginalCommitAcknowledgement finalized(Context context, long lifetime) { - return finalized(context, lifetime, 7L); - } - - private static OriginalCommitAcknowledgement finalized( - Context context, long lifetime, long issuanceFence) { - var evidence = pending(context, lifetime, issuanceFence); + var evidence = pending(context, lifetime); long startedAtNanos = System.nanoTime(); try { return new AccountGameplayAdmissionOriginalCommitExecutor(context.admin()) @@ -1405,11 +962,6 @@ private static OriginalCommitAcknowledgement finalized( } private static AccountGameplayAdmissionLeaseEvidence pending(Context context, long lifetime) { - return pending(context, lifetime, 7L); - } - - private static AccountGameplayAdmissionLeaseEvidence pending( - Context context, long lifetime, long issuanceFence) { return context .transaction() .execute( @@ -1436,17 +988,14 @@ private static AccountGameplayAdmissionLeaseEvidence pending( .fetchSingle( "SELECT floor(extract(epoch FROM clock_timestamp()) * 1000)::bigint") .get(0, Long.class); - var evidence = evidence(allocation, lifetime, databaseNow, issuanceFence); + var evidence = evidence(allocation, lifetime, databaseNow); repository.beginPending(evidence); return evidence; }); } private static AccountGameplayAdmissionLeaseEvidence evidence( - AccountGameplayAdmissionLeaseRepository.Allocation allocation, - long lifetime, - long now, - long issuanceFence) { + AccountGameplayAdmissionLeaseRepository.Allocation allocation, long lifetime, long now) { String account = allocation.accountId().toString(); Map carrier = new LinkedHashMap<>(); carrier.put("schema", AccountGameplayAdmissionLeaseEvidence.SCHEMA); @@ -1489,7 +1038,7 @@ private static AccountGameplayAdmissionLeaseEvidence evidence( Map.of(TENANT, "1"), "privateRealmGrantVersions", List.of())); - carrier.put("issuanceFence", Long.toString(issuanceFence)); + carrier.put("issuanceFence", "7"); carrier.put( "membershipBaseline", Map.of( @@ -1522,7 +1071,7 @@ private static AccountGameplayAdmissionLeaseEvidence evidence( token.put("tokenSHA256", "a".repeat(64)); token.put("tokenProfile", "game-session-account-delegation"); token.put("tokenGeneration", "1"); - token.put("issuanceFence", Long.toString(issuanceFence)); + token.put("issuanceFence", "7"); token.put("tokenIdentityFence", "9"); token.put("issuedAt", Long.toString(now / 1000 - 1)); token.put("notBefore", Long.toString(now / 1000 - 1)); @@ -1577,21 +1126,6 @@ private static Map sourceSnapshot(Context context) { return snapshot; } - private static Map ackStorageSnapshot(Context context) { - return Map.of( - "operation", - context - .dsl() - .fetchSingle( - "SELECT *, xmin::text AS original_xmin FROM account_gameplay_admission_lease_operations") - .intoMap(), - "receipt", - context - .dsl() - .fetchSingle("SELECT *, xmin::text AS original_xmin FROM " + RECEIPTS) - .intoMap()); - } - private static Map receipt(Context context) { return context.dsl().fetchSingle("SELECT * FROM " + RECEIPTS).intoMap(); } diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountOriginalNewBoundGameplayCredentialOwnerIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountOriginalNewBoundGameplayCredentialOwnerIntegrationTest.java deleted file mode 100644 index ca69e100a5..0000000000 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountOriginalNewBoundGameplayCredentialOwnerIntegrationTest.java +++ /dev/null @@ -1,693 +0,0 @@ -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.when; - -import com.fasterxml.jackson.databind.ObjectMapper; -import io.grpc.Context; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.nio.file.Path; -import java.security.MessageDigest; -import java.time.Clock; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Base64; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.UUID; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.atomic.AtomicReference; -import net.firedevops.firemud.accountservice.client.AccountOriginalNewFinalAdmissionReadClient; -import net.firedevops.firemud.accountservice.client.AccountOriginalNewFinalAdmissionReadClient.AuthenticatedFinalAdmissionReadback; -import net.firedevops.firemud.accountservice.client.AccountOriginalNewFinalAdmissionReadClient.ExpectedOriginalAdmission; -import net.firedevops.firemud.accountservice.dto.AccountGameplayTokenIdentityFence.SourceKind; -import net.firedevops.firemud.accountservice.dto.AccountGameplayTokenIdentityFence.TokenIdentity; -import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationResponseEnvelopeRepository.CallerIdentity; -import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationResponseEnvelopeRepository.RecoveredCredential; -import net.firedevops.firemud.accountservice.repository.AccountOriginalNewBoundGameplayIssuanceRepository.Genesis; -import net.firedevops.firemud.accountservice.service.session.AccountGameplayAdmissionCallerVerifier; -import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationRedisClient.ActiveRegistryReadback; -import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationTokenRegistry; -import net.firedevops.firemud.accountservice.service.session.AccountResponseEnvelopeCryptography; -import net.firedevops.firemud.accountservice.service.session.AccountResponseEnvelopeKeyring; -import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; -import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseGrpcCodec.OriginalNewCredential; -import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; -import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; -import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; -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.BeforeEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.TestInstance; -import org.junit.jupiter.api.io.TempDir; -import org.junit.jupiter.api.parallel.Execution; -import org.junit.jupiter.api.parallel.ExecutionMode; -import org.springframework.jdbc.datasource.DataSourceTransactionManager; -import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; -import org.springframework.transaction.TransactionDefinition; -import org.springframework.transaction.support.TransactionTemplate; - -/** - * Actual Account ORIGINAL_NEW owner proof over the existing current-source PostgreSQL fixture and - * its primary/replica Redis fixture. - * - *

The first LOGIN credential, current Account sources, original NEW lease COMMIT and durable ACK - * receipt, Account ORIGINAL_NEW signer operation, encrypted result recovery, token identity fence, - * and Redis pending/active transition use their existing owners. The signer fixture retains its - * controlled signer-custody/materializer inputs. The explicitly controlled Game Session final-read - * callback supplies schema-v2 COMPLETE results and exercises Account's activation and durable - * confirmation owner; it is not evidence of a real Game Session final CAS or protected final-result - * reader. - */ -@Execution(ExecutionMode.SAME_THREAD) -@TestInstance(TestInstance.Lifecycle.PER_CLASS) -class AccountOriginalNewBoundGameplayCredentialOwnerIntegrationTest { - private static final String NAMESPACE = "test"; - private static final String GAME_SESSION_WORKLOAD = - "spiffe://firemud/ns/test/sa/game-session-service"; - private static final String CONFIRMATION_FAULT_FUNCTION = - "account_original_new_test_fail_confirmation_update"; - private static final String CONFIRMATION_FAULT_TRIGGER = - "account_original_new_test_confirmation_update_failure"; - private static final long SESSION_DURATION_MILLIS = 120_000L; - private static final long REDIS_CLEANUP_MARGIN_MILLIS = 30_000L; - private static final ObjectMapper JSON = new ObjectMapper(); - - @TempDir Path temporaryDirectory; - private AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest fixtureHarness; - private AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.Fixture sourceFixture; - private AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.PhysicalRedisFixture - redisFixture; - - @BeforeAll - static void startPostgres() { - AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.startPostgres(); - } - - @AfterAll - static void stopPostgres() { - AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.stopPostgres(); - } - - @BeforeEach - void createActualSourceFixture() throws Exception { - fixtureHarness = new AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest(); - fixtureHarness.temporaryDirectory = temporaryDirectory; - redisFixture = - AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.PhysicalRedisFixture.start(); - sourceFixture = fixtureHarness.newFixture(redisFixture.client()); - } - - @AfterEach - void cleanOwnedFixture() { - if (redisFixture != null) redisFixture.close(); - if (fixtureHarness != null) fixtureHarness.dropRunOwnedSchemas(); - } - - @Test - void lostSqlConfirmationRecoversOnlyAfterFreshExactControlledFinalReadback() throws Exception { - DSLContext dsl = - DSL.using( - new TransactionAwareDataSourceProxy(sourceFixture.dataSource), SQLDialect.POSTGRES); - DataSourceTransactionManager transactionManager = - new DataSourceTransactionManager(sourceFixture.dataSource); - TransactionTemplate serializable = new TransactionTemplate(transactionManager); - serializable.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE); - var initialIdentity = sourceFixture.committedCandidate.identity(); - CallerIdentity recoveryCaller = - new CallerIdentity(initialIdentity.callerWorkload(), initialIdentity.callerContextId()); - RecoveredCredential recoveredLogin = - sourceFixture.responseRecoveryOwner.recoverInitialLoginResponse( - initialIdentity.requestId(), initialIdentity.accountId(), recoveryCaller); - byte[] loginJwtBytes = recoveredLogin.compactJwtBytes(); - String loginJwt = new String(loginJwtBytes, StandardCharsets.US_ASCII); - Arrays.fill(loginJwtBytes, (byte) 0); - - var authorityGenerations = new AccountAuthorityGenerationRepository(dsl); - var authorityOutbox = new AccountAuthorityOutboxRepository(dsl); - var sourceEvidence = - new AccountAuthoritySourceEvidenceRepository(dsl, authorityGenerations, authorityOutbox); - var authEvidenceBundles = - new AccountAuthEvidenceBundleRepository(dsl, authorityGenerations, authorityOutbox); - var issuanceRepository = - new AccountGameplayDelegationIssuanceRepository(dsl, sourceEvidence, authEvidenceBundles); - var tokenRegistry = - new AccountGameplayDelegationTokenRegistry( - issuanceRepository, - transactionManager, - redisFixture.client(), - Clock.systemUTC(), - GameSessionAccountDelegationProfile.MAX_REGISTRY_RECORD_BYTES, - REDIS_CLEANUP_MARGIN_MILLIS); - AccountResponseEnvelopeCryptography responseCryptography = - testResponseCryptography(temporaryDirectory.resolve("original-new-response-keyring")); - AtomicInteger finalReadCalls = new AtomicInteger(); - AtomicReference expectedAdmission = new AtomicReference<>(); - AtomicReference finalReadMode = new AtomicReference<>(FinalReadMode.EXACT); - List finalReadExpectations = new ArrayList<>(); - List observedFinalReadModes = new ArrayList<>(); - List finalReadResults = new ArrayList<>(); - long controlledAdmissionAtMillis = System.currentTimeMillis() - 100L; - AccountOriginalNewFinalAdmissionReadClient controlledFinalReadback = - expected -> { - finalReadCalls.incrementAndGet(); - expectedAdmission.set(expected); - finalReadExpectations.add(expected); - FinalReadMode mode = finalReadMode.get(); - observedFinalReadModes.add(mode); - if (mode == FinalReadMode.UNAVAILABLE) { - throw new IllegalStateException("controlled Game Session final read unavailable"); - } - AuthenticatedFinalAdmissionReadback readback = - mock(AuthenticatedFinalAdmissionReadback.class); - when(readback.sessionSchemaVersion()).thenReturn(2); - when(readback.admissionState()).thenReturn("COMPLETE"); - when(readback.anchors()) - .thenReturn(mode == FinalReadMode.CHANGED ? changedTokenHash(expected) : expected); - when(readback.admissionAtMillis()).thenReturn(controlledAdmissionAtMillis); - when(readback.continuityExpiresAtMillis()) - .thenReturn(controlledAdmissionAtMillis + SESSION_DURATION_MILLIS); - when(readback.canonicalSessionDurationMillis()).thenReturn(SESSION_DURATION_MILLIS); - when(readback.canonicalReadbackSha256()).thenReturn("f".repeat(64)); - finalReadResults.add(readback); - return readback; - }; - var owner = - new AccountOriginalNewBoundGameplayCredentialOwner( - sourceFixture.dataSource, - NAMESPACE, - new AccountGameplayAdmissionCallerVerifier( - sourceFixture.signerFixture.trustedJwksSource(), - sourceFixture.committedIssuanceOwner, - Clock.systemUTC()), - sourceFixture.signerFixture.signer(), - tokenRegistry, - responseCryptography, - Clock.systemUTC(), - controlledFinalReadback); - GrpcPeerIdentity peer = GrpcPeerIdentity.parseUri(GAME_SESSION_WORKLOAD).orElseThrow(); - AccountGameplayAdmissionLeaseEvidence originalLease = - commitActualOriginalNewLease(dsl, serializable); - UUID originalRequestId = UUID.fromString((String) originalLease.carrier().get("requestId")); - UUID originalDecisionId = - dsl.fetchSingle( - "SELECT binding_decision_id FROM account_gameplay_admission_lease_operations " - + "WHERE request_id = ?", - originalRequestId) - .get(0, UUID.class); - if (originalDecisionId == null) throw new IllegalStateException("Original decision is absent"); - String originalEvidenceSha256 = originalLease.sha256(); - - OriginalNewCredential first = - Context.current() - .withValue(GrpcPeerIdentity.CONTEXT_KEY, peer) - .call(() -> owner.issue(loginJwt, originalLease)); - OriginalNewCredential lostReplyRetry = - Context.current() - .withValue(GrpcPeerIdentity.CONTEXT_KEY, peer) - .call(() -> owner.issue(loginJwt, originalLease)); - try (first; - lostReplyRetry) { - Genesis committed = readGenesis(dsl, serializable, originalLease); - byte[] firstHandle = first.opaqueRebindHandle(); - byte[] retryHandle = lostReplyRetry.opaqueRebindHandle(); - byte[] pendingRecord = committed.pendingRegistryRecordBytes(); - byte[] encryptedResult = committed.encryptedResultEnvelopeBytes(); - try { - assertThat(committed.status()) - .isEqualTo(AccountOriginalNewBoundGameplayIssuanceRepository.Status.COMMITTED); - assertThat(committed.tokenGeneration()).isEqualTo(1L); - assertThat(committed.originalLeaseEvidenceSha256()).isEqualTo(originalEvidenceSha256); - assertThat(committed.bindingDecisionId()).isEqualTo(originalDecisionId); - assertThat(committed.issuanceFence()) - .isEqualTo(Long.parseLong((String) originalLease.carrier().get("issuanceFence"))); - assertExactLeaseSource(committed, originalLease, "authorityTuple"); - assertExactLeaseSource(committed, originalLease, "membershipBaseline"); - assertExactLeaseSource(committed, originalLease, "outboxCheckpoints"); - assertThat(committed.lineageId()).isEqualTo(first.lineageId()); - assertThat(committed.tokenJti()).isEqualTo(first.tokenJti()); - assertThat(first.lineageId()).isNotEqualTo(first.tokenJti()); - assertThat(first.tokenJti()).isNotEqualTo(initialIdentity.tokenJti()); - assertThat(first.originalLeaseId()) - .isEqualTo(UUID.fromString((String) originalLease.carrier().get("leaseId"))); - assertThat(first.originalLeaseFence()) - .isEqualTo(originalLease.leaseFence().longValueExact()); - assertThat(first.issuanceFence()).isEqualTo(committed.issuanceFence()); - assertThat(first.tokenSha256()).isEqualTo(committed.tokenHash()); - assertThat(first.checkpointsSha256()) - .isEqualTo(sha256AndWipe(committed.outboxCheckpointsCanonicalBytes())); - assertThat(sha256(firstHandle)).isEqualTo(committed.rebindHandleSha256()); - assertThat(MessageDigest.isEqual(firstHandle, retryHandle)).isTrue(); - assertThat(lostReplyRetry.tokenSha256()).isEqualTo(first.tokenSha256()); - assertThat(lostReplyRetry.lineageId()).isEqualTo(first.lineageId()); - assertThat(lostReplyRetry.tokenJti()).isEqualTo(first.tokenJti()); - assertThat(lostReplyRetry.issuanceFence()).isEqualTo(first.issuanceFence()); - assertThat(lostReplyRetry.originalAckReceiptXid()).isEqualTo(first.originalAckReceiptXid()); - assertThat(lostReplyRetry.checkpointsSha256()).isEqualTo(first.checkpointsSha256()); - assertThat(committed.confirmedAdmissionAtMillis()).isNull(); - assertThat(committed.handleConsumedAtMillis()).isNull(); - assertThat(encryptedResult.length > 0).isTrue(); - assertThat(first.toString()) - .isEqualTo("AccountGameplayAdmissionLeaseGrpcCodec.OriginalNewCredential[redacted]"); - redisFixture - .client() - .requirePendingRecord( - committed.tokenHash(), - pendingRecord, - Math.addExact( - Math.multiplyExact(committed.expiresAtEpochSecond(), 1_000L), - REDIS_CLEANUP_MARGIN_MILLIS)); - TokenIdentity registeredIdentity = activeIdentity(dsl, committed); - assertThat(registeredIdentity.sourceKind()).isEqualTo(SourceKind.ORIGINAL_NEW); - assertThat(registeredIdentity.operationId()).isEqualTo(committed.lineageId()); - assertThat(registeredIdentity.tokenJti()).isEqualTo(first.tokenJti()); - assertThat(registeredIdentity.tokenSha256()).isEqualTo(first.tokenSha256()); - assertThat(registeredIdentity.tokenGeneration()).isEqualTo(1L); - assertThat(registeredIdentity.issuanceFence()).isEqualTo(committed.issuanceFence()); - assertThat(dsl.fetchCount(DSL.table("account_original_new_bound_gameplay_issuances"))) - .isOne(); - } finally { - Arrays.fill(firstHandle, (byte) 0); - Arrays.fill(retryHandle, (byte) 0); - Arrays.fill(pendingRecord, (byte) 0); - Arrays.fill(encryptedResult, (byte) 0); - } - - long exactRedisExpiryMillis = - Math.addExact( - Math.multiplyExact(committed.expiresAtEpochSecond(), 1_000L), - REDIS_CLEANUP_MARGIN_MILLIS); - installOwnedConfirmationUpdateFailure(dsl); - try { - assertThatThrownBy( - () -> - Context.current() - .withValue(GrpcPeerIdentity.CONTEXT_KEY, peer) - .call(() -> owner.confirmOriginalFinalAdmission(loginJwt, originalLease))) - .isInstanceOf(RuntimeException.class) - .hasMessageContaining("controlled owned original-new confirmation SQL fault"); - } finally { - removeOwnedConfirmationUpdateFailure(dsl); - } - Genesis afterLostConfirmation = assertUnconfirmed(dsl, serializable, originalLease); - assertThat(afterLostConfirmation.tokenHash()).isEqualTo(first.tokenSha256()); - var activeAfterLostConfirmation = - tokenRegistry.requireExactOriginalNewActiveRecord(afterLostConfirmation); - assertThat(activeAfterLostConfirmation.absoluteExpiryMillis()) - .isEqualTo(exactRedisExpiryMillis); - assertThat(finalReadCalls.get()).isEqualTo(1); - - // ACTIVE Redis state cannot substitute for a new authenticated Game Session final read. - finalReadMode.set(FinalReadMode.CHANGED); - assertFinalConfirmationUnavailable(owner, peer, loginJwt, originalLease); - Genesis afterChangedRead = assertUnconfirmed(dsl, serializable, originalLease); - assertSameActiveRegistryReadback( - activeAfterLostConfirmation, - tokenRegistry.requireExactOriginalNewActiveRecord(afterChangedRead)); - - finalReadMode.set(FinalReadMode.UNAVAILABLE); - assertFinalConfirmationUnavailable(owner, peer, loginJwt, originalLease); - Genesis afterUnavailableRead = assertUnconfirmed(dsl, serializable, originalLease); - assertSameActiveRegistryReadback( - activeAfterLostConfirmation, - tokenRegistry.requireExactOriginalNewActiveRecord(afterUnavailableRead)); - - // Recovery makes a fresh read of the same controlled final result and confirms the same - // frozen lineage, token, anchors, continuity deadline, and physical registry expiry. - finalReadMode.set(FinalReadMode.EXACT); - var confirmed = confirm(owner, peer, loginJwt, originalLease); - assertThat(confirmed.lineageId()).isEqualTo(first.lineageId()); - assertThat(confirmed.originalLeaseId()) - .isEqualTo(UUID.fromString((String) originalLease.carrier().get("leaseId"))); - assertThat(confirmed.admissionAtMillis()).isEqualTo(controlledAdmissionAtMillis); - assertThat(confirmed.continuityExpiresAtMillis()) - .isEqualTo(controlledAdmissionAtMillis + SESSION_DURATION_MILLIS); - assertThat(expectedAdmission.get()).isNotNull(); - assertThat(expectedAdmission.get().tokenSha256()).isEqualTo(first.tokenSha256()); - assertThat(expectedAdmission.get().lineageId()).isEqualTo(first.lineageId()); - assertThat(expectedAdmission.get().tokenJti()).isEqualTo(first.tokenJti()); - assertThat(expectedAdmission.get().originalLeaseEvidenceSha256()) - .isEqualTo(originalEvidenceSha256); - assertThat(expectedAdmission.get().tokenGeneration()).isEqualTo(1L); - assertThat(expectedAdmission.get().issuanceFence()).isEqualTo(committed.issuanceFence()); - assertThat(expectedAdmission.get().bindingScopeSha256()) - .isEqualTo(committed.bindingScopeSha256()); - assertThat(expectedAdmission.get().membershipBaselineSha256()) - .isEqualTo(sha256AndWipe(committed.membershipBaselineCanonicalBytes())); - assertThat(expectedAdmission.get().checkpointsSha256()) - .isEqualTo(sha256AndWipe(committed.outboxCheckpointsCanonicalBytes())); - assertThat(expectedAdmission.get().rebindHandleSha256()) - .isEqualTo(committed.rebindHandleSha256()); - assertThat(finalReadCalls.get()).isEqualTo(4); - assertThat(observedFinalReadModes) - .containsExactly( - FinalReadMode.EXACT, - FinalReadMode.CHANGED, - FinalReadMode.UNAVAILABLE, - FinalReadMode.EXACT); - assertThat(finalReadExpectations).hasSize(4).containsOnly(expectedAdmission.get()); - assertThat(finalReadResults).hasSize(3); - assertThat(finalReadResults.get(0).anchors()).isEqualTo(finalReadResults.get(2).anchors()); - assertThat(finalReadResults.get(0).admissionAtMillis()) - .isEqualTo(finalReadResults.get(2).admissionAtMillis()); - assertThat(finalReadResults.get(0).continuityExpiresAtMillis()) - .isEqualTo(finalReadResults.get(2).continuityExpiresAtMillis()); - assertThat(finalReadResults.get(0).canonicalSessionDurationMillis()) - .isEqualTo(finalReadResults.get(2).canonicalSessionDurationMillis()); - assertThat(finalReadResults.get(0).canonicalReadbackSha256()) - .isEqualTo(finalReadResults.get(2).canonicalReadbackSha256()); - - Genesis confirmedGenesis = readGenesis(dsl, serializable, originalLease); - assertThat(confirmedGenesis.lineageId()).isEqualTo(first.lineageId()); - assertThat(confirmedGenesis.tokenJti()).isEqualTo(first.tokenJti()); - assertThat(confirmedGenesis.tokenHash()).isEqualTo(first.tokenSha256()); - assertThat(confirmedGenesis.expiresAtEpochSecond()) - .isEqualTo(committed.expiresAtEpochSecond()); - assertThat(confirmedGenesis.confirmedAdmissionAtMillis()) - .isEqualTo(controlledAdmissionAtMillis); - assertThat(confirmedGenesis.confirmedContinuityExpiresAtMillis()) - .isEqualTo(controlledAdmissionAtMillis + SESSION_DURATION_MILLIS); - assertSameActiveRegistryReadback( - activeAfterLostConfirmation, - tokenRegistry.requireExactOriginalNewActiveRecord(confirmedGenesis)); - - var sameConfirmation = confirm(owner, peer, loginJwt, originalLease); - assertThat(sameConfirmation.lineageId()).isEqualTo(confirmed.lineageId()); - assertThat(sameConfirmation.authenticatedConfirmationSha256()) - .isEqualTo(confirmed.authenticatedConfirmationSha256()); - assertThat(finalReadCalls.get()).isEqualTo(4); - - OriginalNewCredential committedRetry = - Context.current() - .withValue(GrpcPeerIdentity.CONTEXT_KEY, peer) - .call(() -> owner.issue(loginJwt, originalLease)); - try (committedRetry) { - assertThat(committedRetry.tokenSha256()).isEqualTo(first.tokenSha256()); - assertThat(committedRetry.lineageId()).isEqualTo(first.lineageId()); - assertThat(committedRetry.tokenJti()).isEqualTo(first.tokenJti()); - assertThat(committedRetry.issuanceFence()).isEqualTo(first.issuanceFence()); - assertThat(committedRetry.originalAckReceiptXid()).isEqualTo(first.originalAckReceiptXid()); - assertThat(finalReadCalls.get()).isEqualTo(4); - } - assertOriginalLeaseAndAckRemainExact(dsl, originalLease, originalEvidenceSha256); - } - } - - private AccountGameplayAdmissionLeaseEvidence commitActualOriginalNewLease( - DSLContext dsl, TransactionTemplate serializable) { - UUID accountId = sourceFixture.committedCandidate.identity().accountId(); - UUID tenantId = - dsl.fetchSingle( - "SELECT membership.tenant_uuid FROM account_tenant_membership membership " - + "JOIN accounts account ON account.id = membership.account_id " - + "WHERE account.account_uuid = ? AND membership.tenant_uuid IS NOT NULL", - accountId) - .get(0, UUID.class); - if (tenantId == null) - throw new IllegalStateException("Current-source fixture tenant is absent"); - - AccountGameplayAdmissionLeaseEvidence evidence = - serializable.execute( - status -> { - var current = - AccountGameplayAdmissionCurrentSources.bind(dsl, NAMESPACE) - .readCurrentPublicProductionNew( - tenantId, - sourceFixture.committedCandidate.identity().tokenJti(), - sourceFixture.committedCandidate); - UUID requestId = UUID.randomUUID(); - UUID leaseId = UUID.randomUUID(); - var leaseRepository = new AccountGameplayAdmissionLeaseRepository(dsl); - var allocation = leaseRepository.allocate(accountId, requestId, leaseId); - long evaluatedAt = - dsl.fetchSingle( - "SELECT floor(extract(epoch FROM clock_timestamp()) * 1000)::bigint") - .get(0, Long.class); - long maxLeaseExpiry = - Math.addExact( - evaluatedAt, AccountGameplayAdmissionLeaseEvidence.MAX_DURATION_MILLIS); - long initialTokenExpiry = - Math.multiplyExact( - sourceFixture.committedCandidate.identity().expiresAtEpochSecond(), 1_000L); - Map carrier = new LinkedHashMap<>(); - carrier.put("schema", AccountGameplayAdmissionLeaseEvidence.SCHEMA); - carrier.put("schemaVersion", "1"); - carrier.put("mode", "PUBLIC_PRODUCTION"); - carrier.put("targetNamespace", NAMESPACE); - carrier.put("callerWorkload", GAME_SESSION_WORKLOAD); - carrier.put("requestId", allocation.requestId().toString()); - carrier.put("leaseId", allocation.leaseId().toString()); - carrier.put("leaseFence", Long.toString(allocation.leaseFence())); - carrier.put("leaseKind", "NEW_BINDING"); - carrier.put( - "bindingScope", - Map.ofEntries( - Map.entry("accountId", accountId.toString()), - Map.entry("tenantId", tenantId.toString()), - Map.entry("realmId", UUID.randomUUID().toString()), - Map.entry("worldSlug", "world"), - Map.entry("realmSlug", "realm"), - Map.entry("playableStateNamespaceId", UUID.randomUUID().toString()), - Map.entry("playableStateScope", "SHARED"), - Map.entry("gameInstanceId", UUID.randomUUID().toString()), - Map.entry("characterId", UUID.randomUUID().toString()), - Map.entry("sessionId", UUID.randomUUID().toString()), - Map.entry("bindingGeneration", "1"), - Map.entry("catalogRevision", "1"), - Map.entry("pointerVersion", "1"), - Map.entry("regionId", UUID.randomUUID().toString()), - Map.entry("regionEpoch", "1"))); - carrier.putAll(current.leaseSourceFields()); - carrier.put("evaluatedAt", Long.toString(evaluatedAt)); - carrier.put("expiresAt", Long.toString(Math.min(maxLeaseExpiry, initialTokenExpiry))); - var originalLease = AccountGameplayAdmissionLeaseEvidence.fromCarrier(carrier); - leaseRepository.beginPending(originalLease); - return originalLease; - }); - - UUID decisionId = UUID.randomUUID(); - var acknowledgement = - new AccountGameplayAdmissionOriginalCommitExecutor(sourceFixture.dataSource) - .executeWithCurrentSources( - evidence, decisionId, NAMESPACE, sourceFixture.committedCandidate); - var receipt = - new AccountGameplayAdmissionOriginalAckReceiptCommitExecutor(sourceFixture.dataSource) - .confirm(acknowledgement); - assertThat(receipt.evidenceSha256()).isEqualTo(evidence.sha256()); - assertThat(receipt.bindingDecisionId()).isEqualTo(decisionId); - return evidence; - } - - private static Genesis readGenesis( - DSLContext dsl, - TransactionTemplate transaction, - AccountGameplayAdmissionLeaseEvidence originalLease) { - return transaction.execute( - status -> - new AccountOriginalNewBoundGameplayIssuanceRepository(dsl) - .readByLease(UUID.fromString((String) originalLease.carrier().get("leaseId")))); - } - - private static AccountOriginalNewBoundGameplayCredentialOwner.OriginalAdmissionConfirmation - confirm( - AccountOriginalNewBoundGameplayCredentialOwner owner, - GrpcPeerIdentity peer, - String loginJwt, - AccountGameplayAdmissionLeaseEvidence originalLease) - throws Exception { - return Context.current() - .withValue(GrpcPeerIdentity.CONTEXT_KEY, peer) - .call(() -> owner.confirmOriginalFinalAdmission(loginJwt, originalLease)); - } - - private static void assertFinalConfirmationUnavailable( - AccountOriginalNewBoundGameplayCredentialOwner owner, - GrpcPeerIdentity peer, - String loginJwt, - AccountGameplayAdmissionLeaseEvidence originalLease) - throws Exception { - assertThatThrownBy(() -> confirm(owner, peer, loginJwt, originalLease)) - .isInstanceOf(IllegalStateException.class) - .hasMessage("Original-new bound gameplay credential is unavailable"); - } - - private static Genesis assertUnconfirmed( - DSLContext dsl, - TransactionTemplate transaction, - AccountGameplayAdmissionLeaseEvidence originalLease) { - Genesis unconfirmed = readGenesis(dsl, transaction, originalLease); - assertThat(unconfirmed.confirmedAdmissionAtMillis()).isNull(); - assertThat(unconfirmed.confirmedContinuityExpiresAtMillis()).isNull(); - assertThat(unconfirmed.confirmationReadbackSha256()).isNull(); - return unconfirmed; - } - - private static void assertSameActiveRegistryReadback( - ActiveRegistryReadback expected, ActiveRegistryReadback actual) { - assertThat(actual.tokenHash()).isEqualTo(expected.tokenHash()); - assertThat(actual.accountId()).isEqualTo(expected.accountId()); - assertThat(actual.jti()).isEqualTo(expected.jti()); - assertThat(actual.tokenExpiryEpochSecond()).isEqualTo(expected.tokenExpiryEpochSecond()); - assertThat(actual.absoluteExpiryMillis()).isEqualTo(expected.absoluteExpiryMillis()); - assertThat(actual.canonicalPendingRecordSha256()) - .isEqualTo(expected.canonicalPendingRecordSha256()); - } - - private static ExpectedOriginalAdmission changedTokenHash(ExpectedOriginalAdmission expected) { - String changedTokenHash = - (expected.tokenSha256().startsWith("0") ? "1" : "0") + expected.tokenSha256().substring(1); - return new ExpectedOriginalAdmission( - expected.requestId(), - expected.accountId(), - expected.tenantId(), - expected.sessionId(), - expected.bindingDecisionId(), - expected.originalLeaseId(), - expected.originalLeaseFence(), - expected.originalLeaseEvidenceSha256(), - expected.lineageId(), - expected.tokenJti(), - changedTokenHash, - expected.tokenGeneration(), - expected.issuanceFence(), - expected.bindingScopeSha256(), - expected.membershipBaselineSha256(), - expected.checkpointsSha256(), - expected.rebindHandleSha256()); - } - - private static void installOwnedConfirmationUpdateFailure(DSLContext dsl) { - dsl.execute( - "CREATE FUNCTION " - + CONFIRMATION_FAULT_FUNCTION - + "() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN " - + "RAISE EXCEPTION 'controlled owned original-new confirmation SQL fault'; " - + "RETURN NEW; END; $$"); - dsl.execute( - "CREATE TRIGGER " - + CONFIRMATION_FAULT_TRIGGER - + " BEFORE UPDATE ON account_original_new_bound_gameplay_issuances " - + "FOR EACH ROW WHEN (OLD.confirmed_admission_at_ms IS NULL " - + "AND NEW.confirmed_admission_at_ms IS NOT NULL) EXECUTE FUNCTION " - + CONFIRMATION_FAULT_FUNCTION - + "()"); - } - - private static void removeOwnedConfirmationUpdateFailure(DSLContext dsl) { - dsl.execute( - "DROP TRIGGER " - + CONFIRMATION_FAULT_TRIGGER - + " ON account_original_new_bound_gameplay_issuances"); - dsl.execute("DROP FUNCTION " + CONFIRMATION_FAULT_FUNCTION + "()"); - } - - private static TokenIdentity activeIdentity(DSLContext dsl, Genesis genesis) { - TokenIdentity exact = - new TokenIdentity( - genesis.accountId(), - genesis.lineageId(), - genesis.requestId(), - genesis.tokenHash(), - genesis.tokenJti(), - genesis.notBeforeEpochSecond(), - genesis.tokenGeneration(), - genesis.issuanceFence(), - SourceKind.ORIGINAL_NEW); - return new AccountGameplayTokenIdentityFenceRepository(dsl) - .requireActiveReadback(exact) - .identity(); - } - - private static void assertExactLeaseSource( - Genesis genesis, AccountGameplayAdmissionLeaseEvidence lease, String field) throws Exception { - byte[] actual = - switch (field) { - case "authorityTuple" -> genesis.authorityTupleCanonicalBytes(); - case "membershipBaseline" -> genesis.membershipBaselineCanonicalBytes(); - case "outboxCheckpoints" -> genesis.outboxCheckpointsCanonicalBytes(); - default -> throw new IllegalArgumentException("Unsupported original lease source field"); - }; - byte[] expected = canonicalBytes(lease.carrier().get(field)); - try { - assertThat(actual).containsExactly(expected); - } finally { - Arrays.fill(actual, (byte) 0); - Arrays.fill(expected, (byte) 0); - } - } - - private static void assertOriginalLeaseAndAckRemainExact( - DSLContext dsl, - AccountGameplayAdmissionLeaseEvidence originalLease, - String originalEvidenceSha256) { - UUID requestId = UUID.fromString((String) originalLease.carrier().get("requestId")); - var operation = - dsl.fetchSingle( - "SELECT evidence_sha256, evidence_json, status " - + "FROM account_gameplay_admission_lease_operations WHERE request_id = ?", - requestId); - assertThat(operation.get("evidence_sha256", String.class)).isEqualTo(originalEvidenceSha256); - assertThat(operation.get("evidence_json", String.class)) - .isEqualTo(originalLease.canonicalJson()); - assertThat(operation.get("status", String.class)).isEqualTo("COMMITTED"); - var receipt = - dsl.fetchSingle( - "SELECT evidence_sha256, lease_id, lease_fence FROM " - + "account_gameplay_admission_original_commit_ack_receipts WHERE request_id = ?", - requestId); - assertThat(receipt.get("evidence_sha256", String.class)).isEqualTo(originalEvidenceSha256); - assertThat(receipt.get("lease_id", UUID.class)) - .isEqualTo(UUID.fromString((String) originalLease.carrier().get("leaseId"))); - assertThat(receipt.get("lease_fence", Long.class)) - .isEqualTo(originalLease.leaseFence().longValueExact()); - } - - private static AccountResponseEnvelopeCryptography testResponseCryptography(Path keyringRoot) - throws Exception { - Files.createDirectories(keyringRoot); - byte[] key = new byte[32]; - for (int index = 0; index < key.length; index++) key[index] = (byte) (index + 1); - try { - String encoded = Base64.getUrlEncoder().withoutPadding().encodeToString(key); - Files.writeString( - keyringRoot.resolve("keyring"), - "firemud-account-response-envelope-keyring-v1\nactive integration-key " + encoded + "\n", - StandardCharsets.US_ASCII); - return new AccountResponseEnvelopeCryptography( - new AccountResponseEnvelopeKeyring(keyringRoot.toString())); - } finally { - Arrays.fill(key, (byte) 0); - } - } - - private static String sha256(byte[] bytes) throws Exception { - return java.util.HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); - } - - private static byte[] canonicalBytes(Object value) throws Exception { - return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); - } - - private static String sha256AndWipe(byte[] bytes) throws Exception { - try { - return sha256(bytes); - } finally { - Arrays.fill(bytes, (byte) 0); - } - } - - private enum FinalReadMode { - EXACT, - CHANGED, - UNAVAILABLE - } -} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptCommitExecutorTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptCommitExecutorTest.java index 09b34f2311..b3bba74e0b 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptCommitExecutorTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptCommitExecutorTest.java @@ -18,7 +18,6 @@ import java.sql.Connection; import java.sql.DatabaseMetaData; -import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; @@ -43,11 +42,6 @@ * JDBC/repository/opaque-ACK doubles; not PostgreSQL durability, authentication or admission proof. */ class AccountGameplayAdmissionOriginalAckReceiptCommitExecutorTest { - private static final String WAL_UPPER_FENCE = "0/16B6C50"; - private static final String WAL_COVERAGE_SQL = - "SELECT current_setting('server_version_num')::integer, pg_is_in_recovery(), " - + "current_setting('fsync'), pg_current_wal_flush_lsn() >= ?::pg_lsn"; - @AfterEach void clearTransaction() { for (Object key : TransactionSynchronizationManager.getResourceMap().keySet()) { @@ -92,15 +86,6 @@ void creationApiAcceptsOnlyOpaqueAcknowledgement() { .containsExactly(java.util.List.of(OriginalCommitAcknowledgement.class)); } - @Test - void historicalPendingReceiptConstructorRemainsPrivate() { - var constructors = - AccountGameplayAdmissionOriginalAckReceiptRepository.PendingHistoricalReceipt.class - .getDeclaredConstructors(); - assertThat(constructors).hasSize(1); - assertThat(java.lang.reflect.Modifier.isPrivate(constructors[0].getModifiers())).isTrue(); - } - @Test void anotherDataSourceIsRejectedBeforeAnyConnection() throws Exception { var fixture = new Fixture(); @@ -141,42 +126,33 @@ void changedOriginalProofRollsBackWithoutIndependentRead(String fault) throws Ex } @Test - void retryCommitCannotSubstituteForUnavailableHistoricalFenceCoverage() throws Exception { + void retryCommitCannotSubstituteForUnavailableHistoricalDurability() throws Exception { var fixture = new Fixture(); fixture.inserted = false; - fixture.flush.covered = false; - fixture.prepareHistoricalRead(true); + fixture.failRead = true; try (var repositories = fixture.repositories()) { assertThatThrownBy(() -> fixture.executor.confirm(fixture.acknowledgement)) - .hasMessageContaining("WAL coverage unavailable"); + .hasMessage("read unavailable"); verify(fixture.first.connection).commit(); - verify(repositories.constructed().get(1)) - .captureHistorical(fixture.evidence, fixture.decision); - verify(repositories.constructed().get(1), never()).readExact(any(), any()); + verify(repositories.constructed().get(1)).readDurably(fixture.evidence, fixture.decision); verify(repositories.constructed().get(1), never()).create(any()); - verify(repositories.constructed().get(1), never()).readDurably(any(), any()); - assertThat(repositories.constructed()).hasSize(2); - verify(fixture.second.connection).commit(); - verify(fixture.second.connection).close(); - verify(fixture.flush.connection).close(); - verifyNoInteractions(fixture.fourth.connection); + verify(fixture.second.connection, never()).commit(); } } @Test - void retainedReceiptUsesFrozenFenceCoverageAndExactReread() throws Exception { + void retainedReceiptUsesHistoricalDurabilityRatherThanRetryCommitProof() throws Exception { var fixture = new Fixture(); fixture.inserted = false; - fixture.prepareHistoricalRead(true); try (var repositories = fixture.repositories()) { assertThat(fixture.executor.confirm(fixture.acknowledgement)).isSameAs(fixture.receipt); - var capture = repositories.constructed().get(1); - var read = repositories.constructed().get(2); - verify(capture).captureHistorical(fixture.evidence, fixture.decision); - verify(read).readExact(fixture.evidence, fixture.decision); - verify(capture, never()).readDurably(any(), any()); + var read = repositories.constructed().get(1); + verify(read).readDurably(fixture.evidence, fixture.decision); + verify(read, never()).readExact(any(), any()); verify(read, never()).create(any()); - assertHistoricalReadSequence(fixture, capture, read, true); + int[] closes = invocationSequences(fixture.first.connection, "close"); + int[] reads = invocationSequences(read, "readDurably"); + assertThat(reads[0]).isGreaterThan(closes[0]); } } @@ -264,76 +240,14 @@ void poolMayReuseConnectionAfterCompletedCommitAndCleanup() throws Exception { @Test void readOnlyValidatesExistingReceipt() throws Exception { var fixture = new Fixture(); - fixture.prepareHistoricalRead(false); try (var repositories = fixture.repositories()) { assertThat(fixture.executor.read(fixture.evidence, fixture.decision)) .isSameAs(fixture.receipt); - var capture = repositories.constructed().getFirst(); - var read = repositories.constructed().get(1); - verify(capture, never()).create(any()); - verify(capture).captureHistorical(fixture.evidence, fixture.decision); - verify(read).readExact(fixture.evidence, fixture.decision); - verify(capture, never()).readDurably(any(), any()); - verify(fixture.first.connection).commit(); - assertHistoricalReadSequence(fixture, capture, read, false); - } - } - - @ParameterizedTest - @ValueSource(strings = {"coverage", "sql", "version", "recovery", "fsync", "autocommit"}) - void historicalReadDoesNotReachExactRereadWithoutValidFenceCoverage(String fault) - throws Exception { - var fixture = new Fixture(); - fixture.prepareHistoricalRead(false); - switch (fault) { - case "coverage" -> fixture.flush.covered = false; - case "sql" -> fixture.flush.failFenceQuery = true; - case "version" -> when(fixture.flush.fenceResult.getInt(1)).thenReturn(160000); - case "recovery" -> when(fixture.flush.fenceResult.getBoolean(2)).thenReturn(true); - case "fsync" -> when(fixture.flush.fenceResult.getString(3)).thenReturn("off"); - case "autocommit" -> when(fixture.flush.connection.getAutoCommit()).thenReturn(false); - default -> throw new IllegalArgumentException(fault); - } - try (var repositories = fixture.repositories()) { - assertThatThrownBy(() -> fixture.executor.read(fixture.evidence, fixture.decision)) - .isInstanceOf(RuntimeException.class); - assertThat(repositories.constructed()).hasSize(1); - verify(repositories.constructed().getFirst()) - .captureHistorical(fixture.evidence, fixture.decision); + verify(repositories.constructed().getFirst(), never()).create(any()); verify(repositories.constructed().getFirst(), never()).readExact(any(), any()); + verify(repositories.constructed().getFirst()).readDurably(fixture.evidence, fixture.decision); verify(fixture.first.connection).commit(); - verify(fixture.first.connection).close(); - verify(fixture.flush.connection).close(); - verifyNoInteractions(fixture.third.connection); - } - } - - @Test - void historicalReadDoesNotExposeReceiptWhenIndependentExactRereadChanges() throws Exception { - var fixture = new Fixture(); - fixture.prepareHistoricalRead(false); - var r = fixture.receipt; - fixture.readReceipt = - new AccountGameplayAdmissionOriginalAckReceipt( - r.operation(), - r.schemaVersion(), - r.requestId(), - r.accountId(), - r.leaseId(), - r.leaseFence(), - r.evidenceSha256(), - r.bindingDecisionId(), - r.expiresAtMs(), - r.finalizationXid(), - r.committedBeforeMs(), - "123458"); - try (var repositories = fixture.repositories()) { - assertThatThrownBy(() -> fixture.executor.read(fixture.evidence, fixture.decision)) - .hasMessageContaining("Fresh owned"); - assertThat(repositories.constructed()).hasSize(2); - verify(repositories.constructed().get(1)).readExact(fixture.evidence, fixture.decision); - verify(fixture.third.connection).commit(); - verify(fixture.third.connection, never()).rollback(); + verifyNoInteractions(fixture.second.connection); } } @@ -419,47 +333,6 @@ private static void assertIndependentAcquisition( assertThat(acquisitions[1]).isLessThan(reads[0]); } - private static void assertHistoricalReadSequence( - Fixture fixture, - AccountGameplayAdmissionOriginalAckReceiptRepository capture, - AccountGameplayAdmissionOriginalAckReceiptRepository read, - boolean creationPrecededCapture) - throws SQLException { - Jdbc captureJdbc = creationPrecededCapture ? fixture.second : fixture.first; - Jdbc flushJdbc = fixture.flush; - Jdbc finalReadJdbc = creationPrecededCapture ? fixture.fourth : fixture.third; - int[] captureCalls = invocationSequences(capture, "captureHistorical"); - int[] captureCommits = invocationSequences(captureJdbc.connection, "commit"); - int[] captureCloses = invocationSequences(captureJdbc.connection, "close"); - int[] fenceQueries = invocationSequences(flushJdbc.connection, "prepareStatement"); - int[] fenceParameters = invocationSequences(flushJdbc.fenceStatement, "setString"); - int[] fenceExecutions = invocationSequences(flushJdbc.fenceStatement, "executeQuery"); - int[] fenceCloses = invocationSequences(flushJdbc.connection, "close"); - int[] exactReads = invocationSequences(read, "readExact"); - int[] finalCommits = invocationSequences(finalReadJdbc.connection, "commit"); - - assertThat(captureCalls).hasSize(1); - assertThat(captureCommits).hasSize(1); - assertThat(captureCloses).hasSize(1); - assertThat(fenceQueries).hasSize(1); - assertThat(fenceParameters).hasSize(1); - assertThat(fenceExecutions).hasSize(1); - assertThat(fenceCloses).hasSize(1); - assertThat(exactReads).hasSize(1); - assertThat(finalCommits).hasSize(1); - assertThat(captureCalls[0]).isLessThan(captureCommits[0]); - assertThat(captureCommits[0]).isLessThan(captureCloses[0]); - assertThat(captureCloses[0]).isLessThan(fenceQueries[0]); - assertThat(fenceQueries[0]).isLessThan(fenceParameters[0]); - assertThat(fenceParameters[0]).isLessThan(fenceExecutions[0]); - assertThat(fenceExecutions[0]).isLessThan(fenceCloses[0]); - assertThat(fenceCloses[0]).isLessThan(exactReads[0]); - assertThat(exactReads[0]).isLessThan(finalCommits[0]); - verify(capture).captureHistorical(fixture.evidence, fixture.decision); - verify(fixture.pending).walUpperFence(); - verify(flushJdbc.fenceStatement).setString(1, WAL_UPPER_FENCE); - } - private static int[] invocationSequences(Object mock, String method) { return mockingDetails(mock).getInvocations().stream() .filter(invocation -> invocation.getMethod().getName().equals(method)) @@ -471,9 +344,6 @@ private static final class Fixture { private final DataSource source = mock(DataSource.class); private final Jdbc first = new Jdbc(); private final Jdbc second = new Jdbc(); - private final Jdbc third = new Jdbc(); - private final Jdbc fourth = new Jdbc(); - private final Jdbc flush = new Jdbc(); private Connection readConnection = second.connection; private final AccountGameplayAdmissionLeaseEvidence evidence = AccountGameplayAdmissionOriginalAckReceiptTestFixtures.fixture(); @@ -481,26 +351,15 @@ private static final class Fixture { private final OriginalCommitAcknowledgement acknowledgement = mock(OriginalCommitAcknowledgement.class); private final AccountGameplayAdmissionOriginalAckReceipt receipt = receipt(evidence, decision); - // Unit-only mock of the private pending capability; the production constructor is asserted - // private by historicalPendingReceiptConstructorRemainsPrivate. - private final AccountGameplayAdmissionOriginalAckReceiptRepository.PendingHistoricalReceipt - pending = - mock( - AccountGameplayAdmissionOriginalAckReceiptRepository.PendingHistoricalReceipt - .class); private boolean inserted = true; private AccountGameplayAdmissionOriginalAckReceipt readReceipt = receipt; private boolean failRead; private String creationFault; - private boolean historicalRead; - private boolean historicalAfterCreate; private final AccountGameplayAdmissionOriginalAckReceiptCommitExecutor executor = new AccountGameplayAdmissionOriginalAckReceiptCommitExecutor(source); private Fixture() throws SQLException { when(source.getConnection()).thenReturn(first.connection, second.connection); - when(pending.receipt()).thenReturn(receipt); - when(pending.walUpperFence()).thenReturn(WAL_UPPER_FENCE); when(acknowledgement.belongsTo(source)).thenReturn(true); when(acknowledgement.evidence()).thenReturn(evidence); when(acknowledgement.decisionId()).thenReturn(decision); @@ -508,18 +367,6 @@ private Fixture() throws SQLException { when(acknowledgement.committedBeforeMs()).thenReturn(receipt.committedBeforeMs()); } - private void prepareHistoricalRead(boolean afterCreate) throws SQLException { - historicalRead = true; - historicalAfterCreate = afterCreate; - if (afterCreate) { - when(source.getConnection()) - .thenReturn(first.connection, second.connection, flush.connection, fourth.connection); - } else { - when(source.getConnection()) - .thenReturn(first.connection, flush.connection, third.connection); - } - } - private MockedConstruction repositories() { return mockConstruction( @@ -527,7 +374,8 @@ private void prepareHistoricalRead(boolean afterCreate) throws SQLException { (repository, context) -> { DSLContext dsl = (DSLContext) context.arguments().getFirst(); Connection enlisted = dsl.connectionResult(value -> value); - assertThat(enlisted).isSameAs(repositoryConnection(context.getCount())); + assertThat(enlisted) + .isSameAs(context.getCount() == 1 ? first.connection : readConnection); assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); assertThat(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel()) @@ -558,27 +406,9 @@ yield receipt( }); when(repository.readExact(evidence, decision)).thenAnswer(ignored -> readResult()); when(repository.readDurably(evidence, decision)).thenAnswer(ignored -> readResult()); - when(repository.captureHistorical(evidence, decision)).thenReturn(pending); }); } - private Connection repositoryConnection(int count) { - if (!historicalRead) return count == 1 ? first.connection : readConnection; - if (historicalAfterCreate) { - return switch (count) { - case 1 -> first.connection; - case 2 -> second.connection; - case 3 -> fourth.connection; - default -> throw new IllegalArgumentException("Unexpected repository " + count); - }; - } - return switch (count) { - case 1 -> first.connection; - case 2 -> third.connection; - default -> throw new IllegalArgumentException("Unexpected repository " + count); - }; - } - private AccountGameplayAdmissionOriginalAckReceipt readResult() { if (failRead) throw new IllegalStateException("read unavailable"); return readReceipt; @@ -593,19 +423,6 @@ private static AccountGameplayAdmissionOriginalAckReceipt receipt( private static final class Jdbc { private final DatabaseMetaData metadata = mock(DatabaseMetaData.class); private final ResultSet settings = mock(ResultSet.class); - private final ResultSet fenceResult = mock(ResultSet.class); - private boolean covered = true; - private boolean failFenceQuery; - private final PreparedStatement fenceStatement = - mock( - PreparedStatement.class, - invocation -> { - if (invocation.getMethod().getName().equals("executeQuery")) { - if (failFenceQuery) throw new SQLException("flush observation unavailable"); - return fenceResult; - } - return Answers.RETURNS_DEFAULTS.answer(invocation); - }); private final Statement statement = mock( Statement.class, @@ -620,11 +437,9 @@ private static final class Jdbc { mock( Connection.class, invocation -> - switch (invocation.getMethod().getName()) { - case "createStatement" -> statement; - case "prepareStatement" -> fenceStatement; - default -> Answers.RETURNS_DEFAULTS.answer(invocation); - }); + invocation.getMethod().getName().equals("createStatement") + ? statement + : Answers.RETURNS_DEFAULTS.answer(invocation)); private boolean badIsolation; private boolean badAutoCommit; @@ -656,20 +471,6 @@ private Jdbc() throws SQLException { when(settings.getString(4)).thenReturn("on"); when(settings.getString(5)).thenReturn("serializable"); when(settings.getString(6)).thenReturn("off"); - when(fenceResult.next()) - .thenAnswer( - new org.mockito.stubbing.Answer() { - private final AtomicInteger row = new AtomicInteger(); - - @Override - public Boolean answer(org.mockito.invocation.InvocationOnMock ignored) { - return row.getAndIncrement() % 2 == 0; - } - }); - when(fenceResult.getInt(1)).thenReturn(180011); - when(fenceResult.getBoolean(2)).thenReturn(false); - when(fenceResult.getString(3)).thenReturn("on"); - when(fenceResult.getBoolean(4)).thenAnswer(ignored -> covered); } } } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayTokenIdentityFenceRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayTokenIdentityFenceRepositoryTest.java index 079de0a485..2a03eac2fb 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayTokenIdentityFenceRepositoryTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayTokenIdentityFenceRepositoryTest.java @@ -14,7 +14,6 @@ import java.lang.reflect.Modifier; import java.util.UUID; -import net.firedevops.firemud.accountservice.dto.AccountGameplayTokenIdentityFence.SourceKind; import net.firedevops.firemud.accountservice.dto.AccountGameplayTokenIdentityFence.State; import net.firedevops.firemud.accountservice.dto.AccountGameplayTokenIdentityFence.TokenIdentity; import net.firedevops.firemud.accountservice.repository.AccountGameplayTokenIdentityFenceRepository; @@ -93,7 +92,7 @@ void activeReadLocksAccountBeforeTokenAndIndependentlyReadsExactCommittedSource( .verify(dsl) .fetchOne( "SELECT account_uuid, operation_id, issuance_request_id, token_hash, token_jti, " - + "not_before_epoch_second, token_generation, issuance_fence, source_kind, token_identity_fence, " + + "not_before_epoch_second, token_generation, issuance_fence, token_identity_fence, " + "state, revocation_request_id, revocation_digest " + "FROM account_gameplay_token_identity_fences WHERE operation_id = ? FOR UPDATE", IDENTITY.operationId()); @@ -128,52 +127,6 @@ void missingCommittedSourceCannotAuthorizeEvenWithActiveTokenRow() { .isInstanceOf(TokenFenceUnavailableException.class); } - @Test - void originalNewFenceReadsOnlyItsSeparateCommittedLineageAndIgnoresLoginDisposal() { - DSLContext dsl = mock(DSLContext.class); - TokenIdentity originalNew = - new TokenIdentity( - IDENTITY.accountId(), - IDENTITY.operationId(), - IDENTITY.issuanceRequestId(), - IDENTITY.tokenSha256(), - IDENTITY.tokenJti(), - IDENTITY.notBeforeEpochSecond(), - 1L, - IDENTITY.issuanceFence(), - SourceKind.ORIGINAL_NEW); - Record account = mock(Record.class); - Record token = tokenRow(State.ACTIVE, originalNew); - Record source = mock(Record.class); - when(dsl.fetchOne( - "SELECT account_uuid FROM accounts WHERE account_uuid = ? FOR UPDATE", - originalNew.accountId())) - .thenReturn(account); - when(dsl.fetchOne( - "SELECT account_uuid, operation_id, issuance_request_id, token_hash, token_jti, " - + "not_before_epoch_second, token_generation, issuance_fence, source_kind, token_identity_fence, " - + "state, revocation_request_id, revocation_digest " - + "FROM account_gameplay_token_identity_fences WHERE operation_id = ? FOR UPDATE", - originalNew.operationId())) - .thenReturn(token); - when(dsl.fetchOne( - startsWith("SELECT operation_id FROM account_original_new_bound_gameplay_issuances "), - any(Object[].class))) - .thenReturn(source); - transaction(); - - var fence = - new AccountGameplayTokenIdentityFenceRepository(dsl).requireActiveForUpdate(originalNew); - - assertThat(fence.identity().sourceKind()).isEqualTo(SourceKind.ORIGINAL_NEW); - assertThat(fence.tokenIdentityFence()).isEqualTo(1L); - verify(dsl, never()).fetchOne(DISPOSAL_GUARD_SELECT, originalNew.issuanceRequestId()); - verify(dsl, never()) - .fetchOne( - startsWith("SELECT operation_id FROM account_gameplay_delegation_issuance_operations "), - any(Object[].class)); - } - @Test void exactIdentityMismatchCannotUseAnotherActiveFence() { DSLContext dsl = mock(DSLContext.class); @@ -421,21 +374,16 @@ void callerClaimedDigestCannotStartRevocationOrAcquireLocks() { } private static Record tokenRow(State state) { - return tokenRow(state, IDENTITY); - } - - private static Record tokenRow(State state, TokenIdentity identity) { Record row = mock(Record.class); - when(row.get("account_uuid", UUID.class)).thenReturn(identity.accountId()); - when(row.get("operation_id", UUID.class)).thenReturn(identity.operationId()); - when(row.get("issuance_request_id", UUID.class)).thenReturn(identity.issuanceRequestId()); - when(row.get("token_hash", String.class)).thenReturn(identity.tokenSha256()); - when(row.get("token_jti", UUID.class)).thenReturn(identity.tokenJti()); + when(row.get("account_uuid", UUID.class)).thenReturn(IDENTITY.accountId()); + when(row.get("operation_id", UUID.class)).thenReturn(IDENTITY.operationId()); + when(row.get("issuance_request_id", UUID.class)).thenReturn(IDENTITY.issuanceRequestId()); + when(row.get("token_hash", String.class)).thenReturn(IDENTITY.tokenSha256()); + when(row.get("token_jti", UUID.class)).thenReturn(IDENTITY.tokenJti()); when(row.get("not_before_epoch_second", Long.class)) - .thenReturn(identity.notBeforeEpochSecond()); - when(row.get("token_generation", Long.class)).thenReturn(identity.tokenGeneration()); - when(row.get("issuance_fence", Long.class)).thenReturn(identity.issuanceFence()); - when(row.get("source_kind", String.class)).thenReturn(identity.sourceKind().name()); + .thenReturn(IDENTITY.notBeforeEpochSecond()); + when(row.get("token_generation", Long.class)).thenReturn(IDENTITY.tokenGeneration()); + when(row.get("issuance_fence", Long.class)).thenReturn(IDENTITY.issuanceFence()); when(row.get("state", String.class)).thenReturn(state.name()); when(row.get("token_identity_fence", Long.class)) .thenReturn(state == State.ACTIVE ? 1L : state == State.PENDING ? 2L : 3L); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountOriginalNewBoundGameplayCredentialOwnerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountOriginalNewBoundGameplayCredentialOwnerTest.java deleted file mode 100644 index 30f2a85f32..0000000000 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountOriginalNewBoundGameplayCredentialOwnerTest.java +++ /dev/null @@ -1,50 +0,0 @@ -package net.firedevops.firemud.accountservice.repository; - -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verifyNoInteractions; - -import java.time.Clock; -import java.time.Instant; -import java.time.ZoneOffset; -import javax.sql.DataSource; -import net.firedevops.firemud.accountservice.service.session.AccountGameplayAdmissionCallerVerifier; -import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationSigner; -import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationTokenRegistry; -import net.firedevops.firemud.accountservice.service.session.AccountResponseEnvelopeCryptography; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.Test; -import org.springframework.transaction.support.TransactionSynchronizationManager; - -class AccountOriginalNewBoundGameplayCredentialOwnerTest { - @AfterEach - void clearTransactionContext() { - TransactionSynchronizationManager.clear(); - } - - @Test - void finalConfirmationFailsClosedUntilProtectedGsReadbackIsWired() { - DataSource dataSource = mock(DataSource.class); - AccountGameplayAdmissionCallerVerifier callerVerifier = - mock(AccountGameplayAdmissionCallerVerifier.class); - AccountGameplayDelegationSigner signer = mock(AccountGameplayDelegationSigner.class); - AccountGameplayDelegationTokenRegistry tokenRegistry = - mock(AccountGameplayDelegationTokenRegistry.class); - AccountResponseEnvelopeCryptography responseCryptography = - mock(AccountResponseEnvelopeCryptography.class); - var owner = - new AccountOriginalNewBoundGameplayCredentialOwner( - dataSource, - "test", - callerVerifier, - signer, - tokenRegistry, - responseCryptography, - Clock.fixed(Instant.parse("2026-10-27T00:00:00Z"), ZoneOffset.UTC)); - - assertThatThrownBy(() -> owner.confirmOriginalFinalAdmission("unlogged-test-token", null)) - .isInstanceOf(IllegalStateException.class) - .hasMessage("Original-new bound gameplay credential is unavailable"); - verifyNoInteractions(dataSource, callerVerifier, signer, tokenRegistry, responseCryptography); - } -} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayAdmissionLeaseGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayAdmissionLeaseGrpcServiceTest.java index 18c4aa8b0c..1dea26640e 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayAdmissionLeaseGrpcServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayAdmissionLeaseGrpcServiceTest.java @@ -164,16 +164,14 @@ void rejectsNullOversizedAndClosedShapeRequestsBeforeCallingOwner() { } @Test - void manualFactoryExposesExactlyTheSixPurposeSpecificMethodsWithoutSpringRegistration() { + void manualFactoryExposesExactlyTheFourPurposeSpecificMethodsWithoutSpringRegistration() { assertThat(service.bindService().getServiceDescriptor().getMethods()) .extracting(method -> method.getFullMethodName()) .containsExactlyInAnyOrder( "account.v1.AccountGameplayAdmissionLeaseService/AcquireGameplayAdmissionLease", "account.v1.AccountGameplayAdmissionLeaseService/FinalizeGameplayAdmissionLease", "account.v1.AccountGameplayAdmissionLeaseService/ReadGameplayAdmissionLease", - "account.v1.AccountGameplayAdmissionLeaseService/AbortGameplayAdmissionLease", - "account.v1.AccountGameplayAdmissionLeaseService/IssueOriginalNewGameplayCredential", - "account.v1.AccountGameplayAdmissionLeaseService/ConfirmOriginalNewGameplayAdmission"); + "account.v1.AccountGameplayAdmissionLeaseService/AbortGameplayAdmissionLease"); } @Test diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationSignerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationSignerTest.java index 44674f3587..447680ddc7 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationSignerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationSignerTest.java @@ -1,6 +1,5 @@ package net.firedevops.firemud.accountservice.service.session; -import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; @@ -32,7 +31,6 @@ import java.util.Arrays; import java.util.Base64; import java.util.HexFormat; -import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Optional; @@ -89,12 +87,10 @@ import org.springframework.transaction.support.DefaultTransactionStatus; import org.springframework.transaction.support.TransactionSynchronizationManager; import org.springframework.transaction.support.TransactionTemplate; -import tools.jackson.databind.json.JsonMapper; class AccountGameplayDelegationSignerTest { private static final Instant NOW = Instant.parse("2026-10-05T00:00:00Z"); private static final Clock CLOCK = Clock.fixed(NOW, ZoneOffset.UTC); - private static final JsonMapper JSON = JsonMapper.builder().build(); private static final String ENVIRONMENT = "staging"; private static final String CLUSTER = "cluster-a"; private static final String NAMESPACE = "firemud"; @@ -140,22 +136,6 @@ private static synchronized void ensureEphemeralRsaPairs() throws Exception { mismatchedPair = generator.generateKeyPair(); } - private static Map jwtClaims(byte[] compactJwt) throws Exception { - String[] parts = new String(compactJwt, StandardCharsets.US_ASCII).split("\\.", -1); - assertEquals(3, parts.length); - return JSON.readValue(Base64.getUrlDecoder().decode(parts[1]), Map.class); - } - - private static Map castClaims(Map claims) { - Map copy = new LinkedHashMap<>(); - claims.forEach( - (key, value) -> { - if (!(key instanceof String text)) throw new AssertionError("JWT claim key is not text"); - copy.put(text, value); - }); - return copy; - } - @Test void remainsUnwiredAndFailsClosedWithoutProtectedSignerTrust() { AccountGameplayDelegationIssuanceRepository issuance = @@ -195,129 +175,6 @@ void remainsUnwiredAndFailsClosedWithoutProtectedSignerTrust() { verifyNoInteractions(configMapClient); } - @Test - void originalNewCredentialUsesBoundClaimsWhileLoginRetainsItsUnscopedShape() throws Exception { - Fixture fixture = new Fixture(temporaryDirectory, false); - UUID tenantId = UUID.fromString("22222222-2222-4222-8222-222222222222"); - Map tuple = - new LinkedHashMap<>(GameSessionAccountDelegationProfile.authorityTuple(1L, 1L)); - tuple.put("tenantAuthorityGeneration", Map.of(tenantId.toString(), "3")); - tuple.put("membershipAuthorityGeneration", Map.of(tenantId.toString(), "8")); - var bound = - new AccountMountedJwtSignerBundle.BoundDelegationClaims( - tenantId.toString(), tuple, Map.of(tenantId.toString(), "8")); - - assertThrows( - net.firedevops.firemud.common.security.AccountAsymmetricJwtVerifier.VerificationException - .class, - () -> - new AccountMountedJwtSignerBundle.BoundDelegationClaims( - tenantId.toString(), - GameSessionAccountDelegationProfile.authorityTuple(1L, 1L), - Map.of())); - - AtomicReference loginJwt = new AtomicReference<>(); - AccountMountedJwtSignerBundle.signCommittedGameplayDelegationDigest( - fixture.privateRoot, - Path.of("current.key"), - fixture.publicRoot, - Path.of("jwks.json"), - fixture.mountedIdentity, - new AccountMountedJwtSignerBundle.DelegationSigningSpec( - fixture.pendingIdentity, fixture.authoritySnapshot), - (digest, compact) -> loginJwt.set(compact.clone())); - - UUID lineageId = UUID.randomUUID(); - UUID boundJti = UUID.randomUUID(); - while (lineageId.equals(boundJti) || boundJti.equals(TOKEN_JTI)) { - boundJti = UUID.randomUUID(); - } - AtomicReference boundJwt = new AtomicReference<>(); - var result = - AccountMountedJwtSignerBundle.signOriginalNewBoundGameplayDelegationDigest( - fixture.privateRoot, - Path.of("current.key"), - fixture.publicRoot, - Path.of("jwks.json"), - fixture.mountedIdentity, - new AccountMountedJwtSignerBundle.OriginalNewBoundDelegationSigningSpec( - lineageId, - REQUEST_ID, - ACCOUNT_ID, - boundJti, - NOW.getEpochSecond(), - NOW.getEpochSecond(), - NOW.plusSeconds(120).getEpochSecond(), - fixture.authoritySnapshot.issuanceFence(), - fixture.authoritySnapshot, - bound), - (digest, compact) -> boundJwt.set(compact.clone())); - - Map loginClaims = jwtClaims(loginJwt.get()); - Map boundClaims = jwtClaims(boundJwt.get()); - assertThat(result.issuanceOperationId()).isEqualTo(lineageId); - assertThat(result.jti()).isEqualTo(boundJti); - assertThat(boundClaims.get("tenantId")).isEqualTo(tenantId.toString()); - assertThat(boundClaims.get("tokenGeneration")).isEqualTo("1"); - assertThat(boundClaims.get("issuanceFence")).isEqualTo("1"); - assertThat(boundClaims.get("authorityTuple")).isEqualTo(tuple); - assertThat(boundClaims.get("membershipVersion")).isEqualTo(Map.of(tenantId.toString(), "8")); - assertThat(boundClaims.containsKey("globalRoles")).isFalse(); - assertThat(boundClaims.containsKey("scopedRoles")).isFalse(); - assertThat(loginClaims.containsKey("tenantId")).isFalse(); - assertThat(loginClaims.get("membershipVersion")).isEqualTo(Map.of()); - assertThat(loginClaims.get("tokenGeneration")).isEqualTo("1"); - net.firedevops.firemud.common.security.GameSessionAccountDelegationJwtProfileValidator - .validateClaims(castClaims(boundClaims)); - assertThat(result.toString()) - .doesNotContain(new String(boundJwt.get(), StandardCharsets.US_ASCII)); - var genesis = - mock( - net.firedevops.firemud.accountservice.repository - .AccountOriginalNewBoundGameplayIssuanceRepository.Genesis.class); - when(genesis.accountId()).thenReturn(ACCOUNT_ID); - when(genesis.lineageId()).thenReturn(lineageId); - when(genesis.tokenJti()).thenReturn(boundJti); - when(genesis.tokenHash()).thenReturn(result.compactTokenSha256()); - when(genesis.signerKid()).thenReturn(result.kid()); - when(genesis.signerGeneration()).thenReturn(result.signerGeneration()); - when(genesis.issuedAtEpochSecond()).thenReturn(NOW.getEpochSecond()); - when(genesis.notBeforeEpochSecond()).thenReturn(NOW.getEpochSecond()); - when(genesis.expiresAtEpochSecond()).thenReturn(NOW.plusSeconds(120).getEpochSecond()); - when(genesis.issuanceFence()).thenReturn(fixture.authoritySnapshot.issuanceFence()); - String savedBoundJwt = new String(boundJwt.get(), StandardCharsets.US_ASCII); - fixture.replaceCommittedEvidence(ownerEvidence(mismatchedPair, "43", "account-key-43")); - fixture.sourceJwks.set( - jwksJson(signerPair, KID, mismatchedPair, "account-key-43") - .getBytes(StandardCharsets.UTF_8)); - Files.writeString(fixture.privateRoot.resolve("current.key"), "unavailable private material"); - var recovered = - fixture.signer.verifyOriginalNewBoundCredential( - savedBoundJwt, - genesis, - fixture.authoritySnapshot, - tenantId.toString(), - tuple, - Map.of(tenantId.toString(), "8")); - assertThat(recovered.tokenSha256()).isEqualTo(result.compactTokenSha256()); - assertThat(recovered.lineageId()).isEqualTo(lineageId); - assertThat(recovered.tokenJti()).isEqualTo(boundJti); - fixture.sourceJwks.set( - jwksJson(mismatchedPair, "account-key-43").getBytes(StandardCharsets.UTF_8)); - assertThrows( - AccountGameplayDelegationSigner.SigningUnavailableException.class, - () -> - fixture.signer.verifyOriginalNewBoundCredential( - savedBoundJwt, - genesis, - fixture.authoritySnapshot, - tenantId.toString(), - tuple, - Map.of(tenantId.toString(), "8"))); - Arrays.fill(loginJwt.get(), (byte) 0); - Arrays.fill(boundJwt.get(), (byte) 0); - } - @Test void signsCanonicalPendingCandidateAndSealsOnlyMetadataWithLiveSourceOutsideTransactions() throws Exception { diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/account/admission/AccountGameplayAdmissionLeaseGrpcCodec.java b/services/common-security/src/main/java/net/firedevops/firemud/common/account/admission/AccountGameplayAdmissionLeaseGrpcCodec.java index 80853d6e24..97799f0d09 100644 --- a/services/common-security/src/main/java/net/firedevops/firemud/common/account/admission/AccountGameplayAdmissionLeaseGrpcCodec.java +++ b/services/common-security/src/main/java/net/firedevops/firemud/common/account/admission/AccountGameplayAdmissionLeaseGrpcCodec.java @@ -20,22 +20,15 @@ import net.firedevops.firemud.account.v1.AccountGameplayAdmissionLeaseState; import net.firedevops.firemud.account.v1.AccountGameplayAdmissionOriginalAckReceiptEvidence; import net.firedevops.firemud.account.v1.AcquireGameplayAdmissionLeaseRequest; -import net.firedevops.firemud.account.v1.ConfirmOriginalNewGameplayAdmissionRequest; import net.firedevops.firemud.account.v1.FinalizeGameplayAdmissionLeaseRequest; -import net.firedevops.firemud.account.v1.IssueOriginalNewGameplayCredentialRequest; -import net.firedevops.firemud.account.v1.OriginalNewAdmissionConfirmationResponse; -import net.firedevops.firemud.account.v1.OriginalNewGameplayCredentialResult; import net.firedevops.firemud.account.v1.ReadGameplayAdmissionLeaseRequest; import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec; import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.Candidate; import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.Target; -import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; import net.firedevops.firemud.common.security.AccountJwtExactValues; -import net.firedevops.firemud.common.security.GameSessionAccountDelegationJwtProfileValidator; import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; import net.firedevops.firemud.gamesession.v1.CanonicalGameplayAdmissionCandidate; import net.firedevops.firemud.gamesession.v1.CanonicalPlayableTargetEvidence; -import tools.jackson.databind.json.JsonMapper; /** * Closed schema-1 transport mapping for Account's exact original public-production NEW lease. @@ -54,15 +47,12 @@ public final class AccountGameplayAdmissionLeaseGrpcCodec { + GameSessionAccountDelegationProfile.MAX_COMPACT_JWT_BYTES + 1024; public static final int MAX_RESPONSE_WIRE_BYTES = - AccountGameplayAdmissionLeaseEvidence.MAX_EVIDENCE_BYTES - + GameSessionAccountDelegationProfile.MAX_COMPACT_JWT_BYTES - + 16 * 1024; + AccountGameplayAdmissionLeaseEvidence.MAX_EVIDENCE_BYTES + 8 * 1024; private static final int SCHEMA_VERSION = 1; private static final BigInteger UINT64_MAX = BigInteger.ONE.shiftLeft(64).subtract(BigInteger.ONE); private static final UUID NIL_UUID = new UUID(0L, 0L); - private static final JsonMapper JSON = JsonMapper.builder().build(); private AccountGameplayAdmissionLeaseGrpcCodec() {} @@ -157,214 +147,6 @@ public String toString() { } } - /** Exact original-lease issuance request. The initial LOGIN JWT is transient and redacted. */ - public static final class OriginalNewCredentialRequest { - private final String presentedInitialGsACompactJwt; - private final AccountGameplayAdmissionLeaseEvidence originalLeaseEvidence; - private final byte[] originalLeaseEvidenceUtf8; - - private OriginalNewCredentialRequest( - String presentedInitialGsACompactJwt, - AccountGameplayAdmissionLeaseEvidence originalLeaseEvidence, - byte[] originalLeaseEvidenceUtf8) { - this.presentedInitialGsACompactJwt = presentedInitialGsACompactJwt; - this.originalLeaseEvidence = originalLeaseEvidence; - this.originalLeaseEvidenceUtf8 = originalLeaseEvidenceUtf8.clone(); - } - - public String presentedInitialGsACompactJwt() { - return presentedInitialGsACompactJwt; - } - - public AccountGameplayAdmissionLeaseEvidence originalLeaseEvidence() { - return originalLeaseEvidence; - } - - public byte[] originalLeaseEvidenceUtf8() { - return originalLeaseEvidenceUtf8.clone(); - } - - @Override - public String toString() { - return "AccountGameplayAdmissionLeaseGrpcCodec.OriginalNewCredentialRequest[redacted]"; - } - } - - /** Internal Account-to-Game-Session credential carrier; diagnostics never reveal its contents. */ - public static final class OriginalNewCredential implements AutoCloseable { - private final String signedBoundGsACompactJwt; - private byte[] opaqueRebindHandle; - private final UUID lineageId; - private final UUID tokenJti; - private final String tokenSha256; - private final long issuanceFence; - private final UUID originalLeaseId; - private final long originalLeaseFence; - private final String originalAckReceiptXid; - private final String checkpointsSha256; - - private OriginalNewCredential( - String signedBoundGsACompactJwt, - byte[] opaqueRebindHandle, - UUID lineageId, - UUID tokenJti, - String tokenSha256, - long issuanceFence, - UUID originalLeaseId, - long originalLeaseFence, - String originalAckReceiptXid, - String checkpointsSha256) { - this.signedBoundGsACompactJwt = signedBoundGsACompactJwt; - this.opaqueRebindHandle = opaqueRebindHandle.clone(); - this.lineageId = lineageId; - this.tokenJti = tokenJti; - this.tokenSha256 = tokenSha256; - this.issuanceFence = issuanceFence; - this.originalLeaseId = originalLeaseId; - this.originalLeaseFence = originalLeaseFence; - this.originalAckReceiptXid = originalAckReceiptXid; - this.checkpointsSha256 = checkpointsSha256; - } - - public String signedBoundGsACompactJwt() { - return signedBoundGsACompactJwt; - } - - public byte[] opaqueRebindHandle() { - if (opaqueRebindHandle == null) - throw new IllegalStateException("Credential result is closed"); - return opaqueRebindHandle.clone(); - } - - public UUID lineageId() { - return lineageId; - } - - public UUID tokenJti() { - return tokenJti; - } - - public String tokenSha256() { - return tokenSha256; - } - - public long issuanceFence() { - return issuanceFence; - } - - public UUID originalLeaseId() { - return originalLeaseId; - } - - public long originalLeaseFence() { - return originalLeaseFence; - } - - public String originalAckReceiptXid() { - return originalAckReceiptXid; - } - - public String checkpointsSha256() { - return checkpointsSha256; - } - - @Override - public void close() { - if (opaqueRebindHandle != null) Arrays.fill(opaqueRebindHandle, (byte) 0); - opaqueRebindHandle = null; - } - - @Override - public String toString() { - return "AccountGameplayAdmissionLeaseGrpcCodec.OriginalNewCredential[redacted]"; - } - } - - /** Exact Account confirmation recovery request; no caller-supplied proof or time fields. */ - public static final class OriginalFinalAdmissionConfirmationRequest { - private final String presentedInitialGsACompactJwt; - private final AccountGameplayAdmissionLeaseEvidence originalLeaseEvidence; - private final byte[] originalLeaseEvidenceUtf8; - - private OriginalFinalAdmissionConfirmationRequest( - String compactJwt, AccountGameplayAdmissionLeaseEvidence lease, byte[] exactLeaseBytes) { - this.presentedInitialGsACompactJwt = compactJwt; - this.originalLeaseEvidence = lease; - this.originalLeaseEvidenceUtf8 = exactLeaseBytes.clone(); - } - - public String presentedInitialGsACompactJwt() { - return presentedInitialGsACompactJwt; - } - - public AccountGameplayAdmissionLeaseEvidence originalLeaseEvidence() { - return originalLeaseEvidence; - } - - public byte[] originalLeaseEvidenceUtf8() { - return originalLeaseEvidenceUtf8.clone(); - } - - @Override - public String toString() { - return "AccountGameplayAdmissionLeaseGrpcCodec.OriginalFinalAdmissionConfirmationRequest[redacted]"; - } - } - - /** Exact current Account confirmation anchors; values alone are not an admission proof. */ - public static final class OriginalFinalAdmissionConfirmation { - private final UUID lineageId; - private final UUID originalLeaseId; - private final long originalLeaseFence; - private final long admissionAtMillis; - private final long continuityExpiresAtMillis; - private final String confirmationReadbackSha256; - - private OriginalFinalAdmissionConfirmation( - UUID lineageId, - UUID originalLeaseId, - long originalLeaseFence, - long admissionAtMillis, - long continuityExpiresAtMillis, - String confirmationReadbackSha256) { - this.lineageId = lineageId; - this.originalLeaseId = originalLeaseId; - this.originalLeaseFence = originalLeaseFence; - this.admissionAtMillis = admissionAtMillis; - this.continuityExpiresAtMillis = continuityExpiresAtMillis; - this.confirmationReadbackSha256 = confirmationReadbackSha256; - } - - public UUID lineageId() { - return lineageId; - } - - public UUID originalLeaseId() { - return originalLeaseId; - } - - public long originalLeaseFence() { - return originalLeaseFence; - } - - public long admissionAtMillis() { - return admissionAtMillis; - } - - public long continuityExpiresAtMillis() { - return continuityExpiresAtMillis; - } - - public String confirmationReadbackSha256() { - return confirmationReadbackSha256; - } - - @Override - public String toString() { - return "AccountGameplayAdmissionLeaseGrpcCodec.OriginalFinalAdmissionConfirmation[redacted]"; - } - } - /** Complete original-operation response shape with a redacted, typed receipt carrier. */ public static final class OperationEvidence { private final AccountGameplayAdmissionLeaseEvidence originalLeaseEvidence; @@ -708,235 +490,6 @@ public static OriginalLeaseRequest parseAbortRequest(AbortGameplayAdmissionLease OriginalLeasePurpose.ABORT, compactJwt, evidence, leaseBytes, decisionId); } - public static IssueOriginalNewGameplayCredentialRequest toIssueOriginalNewCredentialRequest( - String presentedInitialGsACompactJwt, byte[] originalLeaseEvidenceUtf8) { - byte[] leaseBytes = requireOriginalLeaseEvidenceBytes(originalLeaseEvidenceUtf8); - var request = - IssueOriginalNewGameplayCredentialRequest.newBuilder() - .addSchemaVersion(SCHEMA_VERSION) - .addPresentedInitialGsaCompactJwt(compactJwt(presentedInitialGsACompactJwt)) - .addOriginalLeaseEvidenceUtf8(ByteString.copyFrom(leaseBytes)) - .build(); - requireWireSize( - request.getSerializedSize(), - MAX_ORIGINAL_LEASE_REQUEST_WIRE_BYTES, - "original-new credential request"); - parseIssueOriginalNewCredentialRequest(request); - return request; - } - - public static OriginalNewCredentialRequest parseIssueOriginalNewCredentialRequest( - IssueOriginalNewGameplayCredentialRequest request) { - Objects.requireNonNull(request, "request"); - requireWireSize( - request.getSerializedSize(), - MAX_ORIGINAL_LEASE_REQUEST_WIRE_BYTES, - "original-new credential request"); - requireNoUnknownFields(request.getUnknownFields().asMap().isEmpty(), "original-new request"); - requireSchema(one(request.getSchemaVersionList(), "originalNew.schemaVersion")); - String compactJwt = - compactJwt(one(request.getPresentedInitialGsaCompactJwtList(), "originalNew.presentedJwt")); - byte[] leaseBytes = - one(request.getOriginalLeaseEvidenceUtf8List(), "originalNew.originalLeaseEvidenceUtf8") - .toByteArray(); - AccountGameplayAdmissionLeaseEvidence evidence = parseFreshNewLease(leaseBytes); - requirePresentedJwtMatchesLease(evidence, compactJwt); - return new OriginalNewCredentialRequest(compactJwt, evidence, leaseBytes); - } - - public static ConfirmOriginalNewGameplayAdmissionRequest - toConfirmOriginalNewGameplayAdmissionRequest( - String presentedInitialGsACompactJwt, byte[] originalLeaseEvidenceUtf8) { - byte[] leaseBytes = requireOriginalLeaseEvidenceBytes(originalLeaseEvidenceUtf8); - var request = - ConfirmOriginalNewGameplayAdmissionRequest.newBuilder() - .addSchemaVersion(SCHEMA_VERSION) - .addPresentedInitialGsaCompactJwt(compactJwt(presentedInitialGsACompactJwt)) - .addOriginalLeaseEvidenceUtf8(ByteString.copyFrom(leaseBytes)) - .build(); - requireWireSize( - request.getSerializedSize(), - MAX_ORIGINAL_LEASE_REQUEST_WIRE_BYTES, - "original-new admission confirmation request"); - parseConfirmOriginalNewGameplayAdmissionRequest(request); - return request; - } - - public static OriginalFinalAdmissionConfirmationRequest - parseConfirmOriginalNewGameplayAdmissionRequest( - ConfirmOriginalNewGameplayAdmissionRequest request) { - Objects.requireNonNull(request, "request"); - requireWireSize( - request.getSerializedSize(), - MAX_ORIGINAL_LEASE_REQUEST_WIRE_BYTES, - "original-new admission confirmation request"); - requireNoUnknownFields(request.getUnknownFields().asMap().isEmpty(), "confirmation request"); - requireSchema(one(request.getSchemaVersionList(), "confirmation.schemaVersion")); - String compactJwt = - compactJwt( - one(request.getPresentedInitialGsaCompactJwtList(), "confirmation.presentedJwt")); - byte[] leaseBytes = - one(request.getOriginalLeaseEvidenceUtf8List(), "confirmation.originalLeaseEvidence") - .toByteArray(); - AccountGameplayAdmissionLeaseEvidence lease = parseFreshNewLease(leaseBytes); - requirePresentedJwtMatchesLease(lease, compactJwt); - return new OriginalFinalAdmissionConfirmationRequest(compactJwt, lease, leaseBytes); - } - - public static OriginalNewAdmissionConfirmationResponse - toConfirmOriginalNewGameplayAdmissionResponse( - OriginalFinalAdmissionConfirmationRequest request, - UUID lineageId, - UUID originalLeaseId, - long originalLeaseFence, - long admissionAtMillis, - long continuityExpiresAtMillis, - String confirmationReadbackSha256) { - Objects.requireNonNull(request); - UUID leaseId = leaseId(request.originalLeaseEvidence()); - long leaseFence = positiveLong(request.originalLeaseEvidence().leaseFence()); - if (!leaseId.equals(originalLeaseId) - || leaseFence != originalLeaseFence - || admissionAtMillis <= 0L - || continuityExpiresAtMillis <= admissionAtMillis) { - throw invalid("Confirmation changed the exact original lease or deadline anchors"); - } - var response = - OriginalNewAdmissionConfirmationResponse.newBuilder() - .addSchemaVersion(SCHEMA_VERSION) - .addLineageUuid(highEntropyUuid(lineageId).toString()) - .addOriginalLeaseUuid(leaseId.toString()) - .addOriginalLeaseFence(Long.toString(leaseFence)) - .addAdmissionAtMs(Long.toString(admissionAtMillis)) - .addContinuityExpiresAtMs(Long.toString(continuityExpiresAtMillis)) - .addConfirmationReadbackSha256(digest(confirmationReadbackSha256)) - .build(); - requireWireSize(response.getSerializedSize(), 1024, "original-new confirmation response"); - parseConfirmOriginalNewGameplayAdmissionResponse(request, response); - return response; - } - - public static OriginalFinalAdmissionConfirmation parseConfirmOriginalNewGameplayAdmissionResponse( - OriginalFinalAdmissionConfirmationRequest request, - OriginalNewAdmissionConfirmationResponse response) { - Objects.requireNonNull(request); - Objects.requireNonNull(response); - requireWireSize(response.getSerializedSize(), 1024, "original-new confirmation response"); - requireNoUnknownFields(response.getUnknownFields().asMap().isEmpty(), "confirmation response"); - requireSchema(one(response.getSchemaVersionList(), "confirmationResponse.schemaVersion")); - UUID lineage = - highEntropyUuid(one(response.getLineageUuidList(), "confirmationResponse.lineageId")); - UUID lease = - highEntropyUuid(one(response.getOriginalLeaseUuidList(), "confirmationResponse.leaseId")); - long leaseFence = - positiveLongDecimal( - one(response.getOriginalLeaseFenceList(), "confirmationResponse.leaseFence"), - "leaseFence"); - long admissionAt = - positiveLongDecimal( - one(response.getAdmissionAtMsList(), "confirmationResponse.admissionAtMs"), - "admissionAtMs"); - long continuityExpires = - positiveLongDecimal( - one( - response.getContinuityExpiresAtMsList(), - "confirmationResponse.continuityExpiresAtMs"), - "continuityExpiresAtMs"); - String readbackDigest = - digest( - one( - response.getConfirmationReadbackSha256List(), - "confirmationResponse.readbackSha256")); - if (!lease.equals(leaseId(request.originalLeaseEvidence())) - || leaseFence != positiveLong(request.originalLeaseEvidence().leaseFence()) - || continuityExpires <= admissionAt) { - throw invalid("Confirmation response differs from the exact original lease"); - } - return new OriginalFinalAdmissionConfirmation( - lineage, lease, leaseFence, admissionAt, continuityExpires, readbackDigest); - } - - public static AccountGameplayAdmissionLeaseResponse toIssueOriginalNewCredentialResponse( - OriginalNewCredentialRequest request, - AccountGameplayAdmissionLeaseEvidence originalLeaseEvidence, - State state, - UUID bindingDecisionId, - OriginalAckReceiptEvidence originalAckReceipt, - OriginalNewCredential credential) { - Objects.requireNonNull(request, "request"); - Objects.requireNonNull(credential, "credential"); - if (!request.originalLeaseEvidence().hasSameIdentity(originalLeaseEvidence) - || !Arrays.equals( - request.originalLeaseEvidenceUtf8(), canonicalLeaseBytes(originalLeaseEvidence))) { - throw invalid("Original-new result changed the exact lease evidence"); - } - AccountGameplayAdmissionLeaseResponse base = - buildResponse( - request.originalLeaseEvidenceUtf8(), - originalLeaseEvidence, - state, - bindingDecisionId, - null, - originalAckReceipt); - var response = - base.toBuilder().addOriginalNewCredential(toWireOriginalNewCredential(credential)).build(); - OriginalNewCredential parsed = parseIssueOriginalNewCredentialResponse(request, response); - parsed.close(); - return response; - } - - public static OriginalNewCredential parseIssueOriginalNewCredentialResponse( - OriginalNewCredentialRequest request, AccountGameplayAdmissionLeaseResponse response) { - Objects.requireNonNull(request, "request"); - OperationEvidence operation = parseResponse(response, true); - if (operation.state() != State.COMMITTED - || operation.bindingDecisionId() == null - || operation.originalAckReceipt() == null - || operation.orphanCleanupId() != null - || !Arrays.equals( - request.originalLeaseEvidenceUtf8(), - response.getOriginalLeaseEvidenceUtf8(0).toByteArray()) - || !request.originalLeaseEvidence().hasSameIdentity(operation.originalLeaseEvidence())) { - throw invalid("Original-new credential result requires the exact committed original lease"); - } - OriginalNewCredential result = - fromWireOriginalNewCredential(one(response.getOriginalNewCredentialList(), "originalNew")); - validateOriginalNewCredential( - operation.originalLeaseEvidence(), operation.originalAckReceipt(), result); - return result; - } - - /** Builds the redacted internal result value for Account's protected envelope recovery path. */ - public static OriginalNewCredential originalNewCredential( - String signedBoundGsACompactJwt, - byte[] opaqueRebindHandle, - UUID lineageId, - UUID tokenJti, - String tokenSha256, - long issuanceFence, - UUID originalLeaseId, - long originalLeaseFence, - String originalAckReceiptXid, - String checkpointsSha256) { - if (opaqueRebindHandle == null - || opaqueRebindHandle.length != 32 - || issuanceFence <= 0L - || originalLeaseFence <= 0L) { - throw invalid("Original-new credential result metadata is malformed"); - } - return new OriginalNewCredential( - compactJwt(signedBoundGsACompactJwt), - Objects.requireNonNull(opaqueRebindHandle).clone(), - highEntropyUuid(lineageId), - highEntropyUuid(tokenJti), - digest(tokenSha256), - issuanceFence, - highEntropyUuid(originalLeaseId), - originalLeaseFence, - xid(originalAckReceiptXid), - digest(checkpointsSha256)); - } - /** * Serializes a complete original-operation response and revalidates it against the acquisition. */ @@ -1192,21 +745,9 @@ private static AccountGameplayAdmissionLeaseResponse buildResponse( } private static OperationEvidence parseResponse(AccountGameplayAdmissionLeaseResponse response) { - return parseResponse(response, false); - } - - private static OperationEvidence parseResponse( - AccountGameplayAdmissionLeaseResponse response, boolean allowOriginalNewCredential) { Objects.requireNonNull(response, "response"); requireWireSize(response.getSerializedSize(), MAX_RESPONSE_WIRE_BYTES, "lease response"); requireNoUnknownFields(response.getUnknownFields().asMap().isEmpty(), "lease response"); - if (allowOriginalNewCredential) { - if (response.getOriginalNewCredentialCount() != 1) { - throw invalid("Original-new response must carry one credential result"); - } - } else if (response.getOriginalNewCredentialCount() != 0) { - throw invalid("Lease response cannot carry an original-new credential result"); - } requireSchema(one(response.getSchemaVersionList(), "response.schemaVersion")); byte[] leaseBytes = one(response.getOriginalLeaseEvidenceUtf8List(), "response.leaseEvidence").toByteArray(); @@ -1225,157 +766,6 @@ private static OperationEvidence parseResponse( return new OperationEvidence(lease, state, decisionId, cleanupId, receipt); } - private static OriginalNewGameplayCredentialResult toWireOriginalNewCredential( - OriginalNewCredential credential) { - byte[] handle = credential.opaqueRebindHandle(); - try { - return OriginalNewGameplayCredentialResult.newBuilder() - .addSchemaVersion(SCHEMA_VERSION) - .addSignedBoundGsaCompactJwt(credential.signedBoundGsACompactJwt()) - .addOpaqueRebindHandle(ByteString.copyFrom(handle)) - .addLineageUuid(credential.lineageId().toString()) - .addTokenJtiUuid(credential.tokenJti().toString()) - .addTokenSha256(credential.tokenSha256()) - .addIssuanceFence(Long.toString(credential.issuanceFence())) - .addOriginalLeaseUuid(credential.originalLeaseId().toString()) - .addOriginalLeaseFence(Long.toString(credential.originalLeaseFence())) - .addOriginalAckReceiptXid(credential.originalAckReceiptXid()) - .addCheckpointsSha256(credential.checkpointsSha256()) - .build(); - } finally { - Arrays.fill(handle, (byte) 0); - } - } - - private static OriginalNewCredential fromWireOriginalNewCredential( - OriginalNewGameplayCredentialResult wire) { - requireNoUnknownFields(wire.getUnknownFields().asMap().isEmpty(), "original-new credential"); - int schema = one(wire.getSchemaVersionList(), "originalNew.schemaVersion"); - requireSchema(schema); - String jwt = compactJwt(one(wire.getSignedBoundGsaCompactJwtList(), "originalNew.compactJwt")); - byte[] handle = one(wire.getOpaqueRebindHandleList(), "originalNew.rebindHandle").toByteArray(); - if (handle.length != 32) throw invalid("Opaque rebind handle must be exactly 32 bytes"); - try { - return originalNewCredential( - jwt, - handle, - highEntropyUuid(one(wire.getLineageUuidList(), "originalNew.lineageId")), - highEntropyUuid(one(wire.getTokenJtiUuidList(), "originalNew.tokenJti")), - digest(one(wire.getTokenSha256List(), "originalNew.tokenSha256")), - positiveLongDecimal( - one(wire.getIssuanceFenceList(), "originalNew.issuanceFence"), "issuanceFence"), - highEntropyUuid(one(wire.getOriginalLeaseUuidList(), "originalNew.leaseId")), - positiveLongDecimal( - one(wire.getOriginalLeaseFenceList(), "originalNew.leaseFence"), "leaseFence"), - xid(one(wire.getOriginalAckReceiptXidList(), "originalNew.ackReceiptXid")), - digest(one(wire.getCheckpointsSha256List(), "originalNew.checkpointsSha256"))); - } finally { - Arrays.fill(handle, (byte) 0); - } - } - - private static void validateOriginalNewCredential( - AccountGameplayAdmissionLeaseEvidence lease, - OriginalAckReceiptEvidence receipt, - OriginalNewCredential result) { - byte[] jwtBytes = compactJwtUtf8(result.signedBoundGsACompactJwt()); - try { - Map claims = parseCompactJwtClaims(result.signedBoundGsACompactJwt()); - Map carrier = lease.carrier(); - Map scope = object(carrier.get("bindingScope"), "bindingScope"); - Map baseline = object(carrier.get("membershipBaseline"), "membershipBaseline"); - Map tokenIdentity = - object(carrier.get("tokenIdentityEvidence"), "tokenIdentityEvidence"); - String accountId = string(scope, "accountId"); - String tenantId = string(scope, "tenantId"); - String originalJti = string(tokenIdentity, "tokenJti"); - long issuanceFence = positiveLongValue(carrier.get("issuanceFence"), "issuanceFence"); - long leaseFence = positiveLong(lease.leaseFence()); - byte[] checkpoints = canonicalJsonBytes(carrier.get("outboxCheckpoints")); - try { - if (!sha256(jwtBytes).equals(result.tokenSha256()) - || result.lineageId().equals(result.tokenJti()) - || result.tokenJti().toString().equals(originalJti) - || !leaseId(lease).equals(result.originalLeaseId()) - || leaseFence != result.originalLeaseFence() - || issuanceFence != result.issuanceFence() - || !sha256(checkpoints).equals(result.checkpointsSha256()) - || receipt == null - || !receipt.receiptXid().equals(result.originalAckReceiptXid()) - || !accountId.equals(claims.get("sub")) - || !accountId.equals(claims.get("accountId")) - || !tenantId.equals(claims.get("tenantId")) - || !result.tokenJti().toString().equals(claims.get("jti")) - || positiveClaim(claims, "tokenGeneration") != 1L - || positiveClaim(claims, "issuanceFence") != issuanceFence - || !Objects.equals(carrier.get("authorityTuple"), claims.get("authorityTuple")) - || !Objects.equals(baseline.get("membershipVersion"), claims.get("membershipVersion")) - || claims.containsKey("globalRoles") - || claims.containsKey("scopedRoles")) { - throw invalid("Original-new credential differs from the exact committed lease binding"); - } - } finally { - Arrays.fill(checkpoints, (byte) 0); - } - } finally { - Arrays.fill(jwtBytes, (byte) 0); - } - } - - private static Map parseCompactJwtClaims(String compact) { - String[] parts = compact.split("\\.", -1); - if (parts.length != 3 || parts[0].isEmpty() || parts[1].isEmpty() || parts[2].isEmpty()) { - throw invalid("Signed bound GSA compact JWT is malformed"); - } - byte[] payload; - try { - payload = java.util.Base64.getUrlDecoder().decode(parts[1]); - } catch (IllegalArgumentException malformed) { - throw invalid("Signed bound GSA compact JWT payload is malformed"); - } - try { - Map claims = JSON.readValue(payload, Map.class); - GameSessionAccountDelegationJwtProfileValidator.validateClaims(claims); - return claims; - } catch (Exception malformed) { - throw invalid("Signed bound GSA claims are malformed"); - } finally { - Arrays.fill(payload, (byte) 0); - } - } - - private static byte[] canonicalJsonBytes(Object value) { - try { - return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); - } catch (Exception malformed) { - throw invalid("Original lease checkpoints are malformed"); - } - } - - private static UUID leaseId(AccountGameplayAdmissionLeaseEvidence lease) { - return highEntropyUuid(string(lease.carrier(), "leaseId")); - } - - private static long positiveLongValue(Object value, String field) { - try { - return AccountJwtExactValues.positiveDecimalCounter(value).longValueExact(); - } catch (RuntimeException malformed) { - throw invalid(field + " is outside its supported positive signed-long range"); - } - } - - private static long positiveClaim(Map claims, String field) { - return positiveLongValue(claims.get(field), field); - } - - private static String sha256(byte[] value) { - try { - return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value)); - } catch (NoSuchAlgorithmException unavailable) { - throw new IllegalStateException("SHA-256 is unavailable", unavailable); - } - } - private static void validateOperationState( AccountGameplayAdmissionLeaseEvidence lease, State state, diff --git a/services/common-security/src/test/java/net/firedevops/firemud/common/account/admission/AccountGameplayAdmissionLeaseGrpcCodecTest.java b/services/common-security/src/test/java/net/firedevops/firemud/common/account/admission/AccountGameplayAdmissionLeaseGrpcCodecTest.java index d592de651b..207f05a239 100644 --- a/services/common-security/src/test/java/net/firedevops/firemud/common/account/admission/AccountGameplayAdmissionLeaseGrpcCodecTest.java +++ b/services/common-security/src/test/java/net/firedevops/firemud/common/account/admission/AccountGameplayAdmissionLeaseGrpcCodecTest.java @@ -10,9 +10,7 @@ import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.time.Instant; -import java.util.Base64; import java.util.HexFormat; -import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.UUID; @@ -22,18 +20,15 @@ import net.firedevops.firemud.account.v1.AcquireGameplayAdmissionLeaseRequest; import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseGrpcCodec.AcquireRequest; import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseGrpcCodec.OriginalAckReceiptEvidence; -import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseGrpcCodec.OriginalNewCredential; import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseGrpcCodec.State; import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.Candidate; import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.OriginKind; import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.OwnerProofOutcome; import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.Target; -import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold; import net.firedevops.firemud.gamesession.v1.CanonicalPlayableTargetEvidence; import org.junit.jupiter.api.Test; -import tools.jackson.databind.json.JsonMapper; /** Shape and tuple checks only; these carriers grant no Account or gameplay authority. */ class AccountGameplayAdmissionLeaseGrpcCodecTest { @@ -48,7 +43,6 @@ class AccountGameplayAdmissionLeaseGrpcCodecTest { private static final UUID VERSION_ID = UUID.fromString("99999999-9999-4999-8999-999999999999"); private static final UUID HOLD_ID = UUID.fromString("55555555-5555-4555-8555-555555555555"); private static final UUID HOLD_FENCE = UUID.fromString("66666666-6666-4666-8666-666666666666"); - private static final JsonMapper JSON = JsonMapper.builder().build(); @Test void roundTripsExactAcquireLeaseBytesAndCompleteAckWithoutClaimingAuthority() { @@ -208,110 +202,6 @@ void rejectsAcquireResponseWhenTokenDigestDiffersFromPresentedCredential() { assertRejected(request, pendingResponse(changedLease)); } - @Test - void originalNewCredentialCarrierKeepsHandleOpaqueAndRejectsUnboundClaims() throws Exception { - var lease = lease(); - byte[] leaseBytes = lease.canonicalJson().getBytes(StandardCharsets.UTF_8); - var request = - AccountGameplayAdmissionLeaseGrpcCodec.parseIssueOriginalNewCredentialRequest( - AccountGameplayAdmissionLeaseGrpcCodec.toIssueOriginalNewCredentialRequest( - JWT, leaseBytes)); - Map carrier = lease.carrier(); - Map scope = object(carrier, "bindingScope"); - UUID requestId = UUID.fromString((String) carrier.get("requestId")); - UUID accountId = UUID.fromString((String) scope.get("accountId")); - UUID leaseId = UUID.fromString((String) carrier.get("leaseId")); - long leaseFence = lease.leaseFence().longValueExact(); - UUID lineageId = UUID.randomUUID(); - UUID tokenJti = UUID.randomUUID(); - while (tokenJti.equals(lineageId) - || tokenJti - .toString() - .equals(String.valueOf(object(carrier, "tokenIdentityEvidence").get("tokenJti")))) { - tokenJti = UUID.randomUUID(); - } - long issuedAt = Instant.now().getEpochSecond(); - Map claims = boundClaims(lease, tokenJti, issuedAt); - String boundJwt = compactJwt(claims); - byte[] handle = new byte[32]; - java.util.Arrays.fill(handle, (byte) 0x2a); - String checkpointsSha256 = checkpointsSha256(carrier.get("outboxCheckpoints")); - OriginalNewCredential credential = - AccountGameplayAdmissionLeaseGrpcCodec.originalNewCredential( - boundJwt, - handle, - lineageId, - tokenJti, - jwtSha256(boundJwt), - Long.parseLong((String) carrier.get("issuanceFence")), - leaseId, - leaseFence, - "102", - checkpointsSha256); - var ack = - OriginalAckReceiptEvidence.fromFields( - 1, - requestId, - accountId, - leaseId, - leaseFence, - lease.sha256(), - DECISION_ID, - 1_015_000L, - "101", - 1_014_999L, - "102"); - - var response = - AccountGameplayAdmissionLeaseGrpcCodec.toIssueOriginalNewCredentialResponse( - request, lease, State.COMMITTED, DECISION_ID, ack, credential); - OriginalNewCredential parsed = - AccountGameplayAdmissionLeaseGrpcCodec.parseIssueOriginalNewCredentialResponse( - request, response); - byte[] firstHandleRead = parsed.opaqueRebindHandle(); - String handleHex = HexFormat.of().formatHex(handle); - assertThat(parsed.lineageId()).isEqualTo(lineageId); - assertThat(parsed.signedBoundGsACompactJwt()).isEqualTo(boundJwt); - assertThat(firstHandleRead).containsExactly(handle); - assertThat(parsed.toString()).doesNotContain(boundJwt, handleHex); - assertThat(request.toString()).doesNotContain(JWT, handleHex); - java.util.Arrays.fill(firstHandleRead, (byte) 0); - byte[] secondHandleRead = parsed.opaqueRebindHandle(); - assertThat(secondHandleRead).containsExactly(handle); - java.util.Arrays.fill(secondHandleRead, (byte) 0); - parsed.close(); - assertThatThrownBy(parsed::opaqueRebindHandle) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("Credential result is closed"); - - Map unboundClaims = new LinkedHashMap<>(claims); - unboundClaims.remove("tenantId"); - unboundClaims.put("membershipVersion", Map.of()); - unboundClaims.put("authorityTuple", GameSessionAccountDelegationProfile.authorityTuple(1L, 1L)); - String unboundJwt = compactJwt(unboundClaims); - OriginalNewCredential unboundCredential = - AccountGameplayAdmissionLeaseGrpcCodec.originalNewCredential( - unboundJwt, - handle, - lineageId, - tokenJti, - jwtSha256(unboundJwt), - Long.parseLong((String) carrier.get("issuanceFence")), - leaseId, - leaseFence, - "102", - checkpointsSha256); - assertThatThrownBy( - () -> - AccountGameplayAdmissionLeaseGrpcCodec.toIssueOriginalNewCredentialResponse( - request, lease, State.COMMITTED, DECISION_ID, ack, unboundCredential)) - .isInstanceOf(IllegalArgumentException.class); - credential.close(); - unboundCredential.close(); - java.util.Arrays.fill(handle, (byte) 0); - java.util.Arrays.fill(leaseBytes, (byte) 0); - } - @Test void rejectsMissingDuplicateAndUnknownAcquireAndResponseFields() { var lease = lease(); @@ -890,48 +780,6 @@ private static String jwtSha256(String jwt) { } } - private static Map boundClaims( - AccountGameplayAdmissionLeaseEvidence lease, UUID tokenJti, long issuedAt) { - Map carrier = lease.carrier(); - Map scope = object(carrier, "bindingScope"); - Map baseline = object(carrier, "membershipBaseline"); - Map claims = new LinkedHashMap<>(); - claims.put("iss", GameSessionAccountDelegationProfile.ISSUER); - claims.put("sub", scope.get("accountId")); - claims.put("accountId", scope.get("accountId")); - claims.put("jti", tokenJti.toString()); - claims.put("aud", GameSessionAccountDelegationProfile.AUDIENCE); - claims.put("iat", issuedAt); - claims.put("nbf", issuedAt); - claims.put("exp", issuedAt + 120L); - claims.put("tokenGeneration", "1"); - claims.put("authorityTuple", carrier.get("authorityTuple")); - claims.put("membershipVersion", baseline.get("membershipVersion")); - claims.put("issuanceFence", carrier.get("issuanceFence")); - claims.put("tenantId", scope.get("tenantId")); - return claims; - } - - private static String compactJwt(Map claims) throws Exception { - String header = - Base64.getUrlEncoder() - .withoutPadding() - .encodeToString( - "{\"alg\":\"RS256\",\"kid\":\"controlled-test\"}".getBytes(StandardCharsets.UTF_8)); - String payload = - Base64.getUrlEncoder().withoutPadding().encodeToString(JSON.writeValueAsBytes(claims)); - return header + "." + payload + ".c2ln"; - } - - private static String checkpointsSha256(Object checkpoints) throws Exception { - byte[] canonical = Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(checkpoints)); - try { - return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(canonical)); - } finally { - java.util.Arrays.fill(canonical, (byte) 0); - } - } - private static Map object(Map carrier, String field) { return (Map) carrier.get(field); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountGameplayAdmissionLeaseClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountGameplayAdmissionLeaseClient.java index 6caf868995..a03f2a7bae 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountGameplayAdmissionLeaseClient.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountGameplayAdmissionLeaseClient.java @@ -14,11 +14,7 @@ import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseGrpcCodec; import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseGrpcCodec.AcquireRequest; import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseGrpcCodec.OperationEvidence; -import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseGrpcCodec.OriginalFinalAdmissionConfirmation; -import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseGrpcCodec.OriginalFinalAdmissionConfirmationRequest; import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseGrpcCodec.OriginalLeaseRequest; -import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseGrpcCodec.OriginalNewCredential; -import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseGrpcCodec.OriginalNewCredentialRequest; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.Candidate; import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.Target; @@ -29,9 +25,7 @@ import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; -/** - * Manual Game Session to Account transport for NEW lease and ORIGINAL-NEW credential operations. - */ +/** Manual Game Session to Account transport for the four exact NEW-binding lease operations. */ public final class AccountGameplayAdmissionLeaseClient extends AbstractReloadingBlockingGrpcClient< AccountGameplayAdmissionLeaseServiceGrpc.AccountGameplayAdmissionLeaseServiceBlockingStub> { @@ -202,72 +196,6 @@ public OperationEvidence abort( } } - /** - * Requests the first bound ORIGINAL-NEW credential after Account's actual COMMITTED lease/ACK - * readback. The returned handle is an internal opaque value; callers must not log it or forward - * it to any player-facing response. - */ - public OriginalNewCredential issueOriginalNewBoundGameplayCredential( - String presentedInitialGsACompactJwt, byte[] originalLeaseEvidenceUtf8) { - requireNoAmbientSql("Original-new credential issuance requires no ambient SQL"); - var wireRequest = - AccountGameplayAdmissionLeaseGrpcCodec.toIssueOriginalNewCredentialRequest( - presentedInitialGsACompactJwt, originalLeaseEvidenceUtf8); - OriginalNewCredentialRequest expected = - AccountGameplayAdmissionLeaseGrpcCodec.parseIssueOriginalNewCredentialRequest(wireRequest); - requireLeaseCorrelation(expected.originalLeaseEvidence()); - try { - OriginalNewCredential credential = - AccountGameplayAdmissionLeaseGrpcCodec.parseIssueOriginalNewCredentialResponse( - expected, - requireInitializedStub("Account lease service is not initialized") - .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) - .issueOriginalNewGameplayCredential(wireRequest)); - if (!credential - .originalLeaseId() - .equals( - UUID.fromString( - (String) expected.originalLeaseEvidence().carrier().get("leaseId"))) - || credential.originalLeaseFence() - != expected.originalLeaseEvidence().leaseFence().longValueExact()) { - throw new IllegalArgumentException("Account credential result changed its original lease"); - } - return credential; - } catch (StatusRuntimeException failure) { - throw statusFailure("Account original-new credential issuance failed", failure); - } catch (IllegalArgumentException malformed) { - throw invalidEvidence("Account returned invalid original-new credential evidence", malformed); - } - } - - /** - * Requests Account's durable confirmation after it fetches the authenticated actual GS result. - */ - public OriginalFinalAdmissionConfirmation confirmOriginalNewGameplayAdmission( - String presentedInitialGsACompactJwt, byte[] originalLeaseEvidenceUtf8) { - requireNoAmbientSql("Original-new admission confirmation requires no ambient SQL"); - var wireRequest = - AccountGameplayAdmissionLeaseGrpcCodec.toConfirmOriginalNewGameplayAdmissionRequest( - presentedInitialGsACompactJwt, originalLeaseEvidenceUtf8); - OriginalFinalAdmissionConfirmationRequest expected = - AccountGameplayAdmissionLeaseGrpcCodec.parseConfirmOriginalNewGameplayAdmissionRequest( - wireRequest); - requireLeaseCorrelation(expected.originalLeaseEvidence()); - try { - return AccountGameplayAdmissionLeaseGrpcCodec - .parseConfirmOriginalNewGameplayAdmissionResponse( - expected, - requireInitializedStub("Account lease service is not initialized") - .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) - .confirmOriginalNewGameplayAdmission(wireRequest)); - } catch (StatusRuntimeException failure) { - throw statusFailure("Account original-new admission confirmation failed", failure); - } catch (IllegalArgumentException malformed) { - throw invalidEvidence( - "Account returned invalid original-new admission confirmation", malformed); - } - } - private void requireLeaseCorrelation(AccountGameplayAdmissionLeaseEvidence lease) { Objects.requireNonNull(lease, "lease"); Object targetNamespace = lease.carrier().get("targetNamespace"); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepository.java index cbdf2a8d96..8b37c0dd96 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepository.java @@ -284,115 +284,6 @@ CanonicalGameplayBindingProvisionalCasEvidence readProvisionalCasEvidence(UUID t }); } - /** - * Claims the one permitted original-NEW candidate installation. The immutable candidate and - * DISPATCH_POSSIBLE marker commit together before the caller can reach Redis. A returned create - * permission exists only for that first committed claim; later calls are read-only. - */ - OriginalNewCandidateInstallationClaim claimOriginalNewCandidateInstallation( - CanonicalGameplayAdmissionDecision originalDecision) { - Objects.requireNonNull(originalDecision, "originalDecision"); - requireNoAmbientTransaction(); - return dsl.transactionResult( - configuration -> { - DSLContext transaction = DSL.using(configuration); - BigInteger currentRevision = lockInventoryRevision(transaction); - CanonicalGameplayAccountCoverageEvidence accountCoverage = - lockAccountCoverageEvidence(transaction, originalDecision.candidate().accountId()); - lockLeaseBoundRuntimeBeforeTransition( - transaction, - originalDecision.bindingDecisionId(), - originalDecision.candidate().bindingRef().bytes(), - originalDecision.targetEvidence()); - CanonicalGameplayBindingProvisionalCasEvidence evidence = - loadProvisionalCasEvidence(transaction, originalDecision.bindingDecisionId(), true); - if (!accountCoverage.equals(evidence.transition().accountCoverageEvidence())) { - throw conflict("Original NEW account control changed before candidate dispatch claim"); - } - requireDecisionMatchesOperation(originalDecision, evidence); - CanonicalGameplayOriginalNewCandidate candidate; - try { - candidate = - CanonicalGameplayOriginalNewCandidate.fromOriginalSources( - evidence, originalDecision); - } catch (RuntimeException invalidSource) { - throw conflict("Original NEW candidate source is not exact and public-production"); - } - - Record transition = findTransition(transaction, evidence.transition().transitionId()); - byte[] storedBytes = transition.get("original_new_candidate_bytes", byte[].class); - String storedDigest = transition.get("original_new_candidate_digest", String.class); - String storedState = transition.get("original_new_candidate_state", String.class); - String storedReadbackDigest = - transition.get("original_new_candidate_readback_digest", String.class); - if (storedBytes == null) { - if (storedDigest != null - || storedState != null - || storedReadbackDigest != null - || evidence.transition().status() - != CanonicalGameplayBindingTransitionSnapshot.Status.PREPARED - || transition.get("admission_lease_id", UUID.class) != null) { - throw conflict("Only an untouched PREPARED original NEW row can claim creation"); - } - byte[] bytes = candidate.canonicalBytes(); - String digest = CanonicalGameplayIssuerMemberV2Codec.sha256(bytes); - BigInteger priorRevision = evidence.transition().inventoryRevision(); - BigInteger nextRevision = currentRevision.add(BigInteger.ONE); - updateOriginalNewCandidateRevisionRows( - transaction, evidence, priorRevision, nextRevision, bytes, digest); - bumpInventoryClock(transaction, currentRevision, nextRevision); - CanonicalGameplayBindingProvisionalCasEvidence current = - loadProvisionalCasEvidence(transaction, evidence.transition().transitionId(), true); - return new OriginalNewCandidateInstallationClaim( - current, - originalDecision, - candidate, - OriginalNewCandidateInstallationState.DISPATCH_POSSIBLE, - new OriginalNewCandidateCreatePermission()); - } - - if (storedDigest == null - || !storedDigest.equals(CanonicalGameplayIssuerMemberV2Codec.sha256(storedBytes)) - || !Arrays.equals(storedBytes, candidate.canonicalBytes()) - || (!"DISPATCH_POSSIBLE".equals(storedState) - && !"READBACK_CONFIRMED".equals(storedState))) { - throw conflict("Original NEW candidate retry differs from its immutable SQL source"); - } - CanonicalGameplayOriginalNewCandidate parsed = - CanonicalGameplayOriginalNewCandidate.parseCanonical(storedBytes); - if (!parsed.equals(candidate) - || !parsed.matchesOriginalDecision(originalDecision) - || !parsed.matchesProvisionalSources(evidence)) { - throw conflict("Stored original NEW candidate no longer matches its durable sources"); - } - if (evidence.transition().status() - == CanonicalGameplayBindingTransitionSnapshot.Status.PROVISIONAL) { - CanonicalGameplayAdmissionDecision stored = toAdmissionDecision(transition, evidence); - requireSameAdmissionDecision(originalDecision, stored); - if (!"READBACK_CONFIRMED".equals(storedState) || storedReadbackDigest == null) { - throw conflict("PROVISIONAL original NEW source lacks retained physical readback"); - } - } - return new OriginalNewCandidateInstallationClaim( - evidence, - originalDecision, - parsed, - OriginalNewCandidateInstallationState.valueOf(storedState), - null); - }); - } - - /** - * Records only actual owner-produced physical readback, then reuses the existing provisional CAS. - */ - CanonicalGameplayBindingTransitionSnapshot markOriginalNewCandidateProvisional( - OriginalNewCandidateInstallationClaim claim, - CanonicalGameplayOriginalNewCandidateRedisOwner.PhysicalReadback readback) { - Objects.requireNonNull(claim, "candidate installation claim"); - Objects.requireNonNull(readback, "owner-produced physical readback"); - return markProvisional(claim.evidence(), claim.originalDecision(), claim.candidate(), readback); - } - void requireSameProvisionalSource( CanonicalGameplayBindingProvisionalCasEvidence expected, CanonicalGameplayBindingProvisionalCasEvidence current) { @@ -763,87 +654,6 @@ private static void writeRevisionRows( "Candidate issuer reservation changed before region bridge revision"); } - private static void updateOriginalNewCandidateRevisionRows( - DSLContext transaction, - CanonicalGameplayBindingProvisionalCasEvidence evidence, - BigInteger oldRevision, - BigInteger nextRevision, - byte[] candidateBytes, - String candidateDigest) { - UUID transitionId = evidence.transition().transitionId(); - requireOne( - transaction.execute( - "UPDATE " - + TRANSITION - + " SET original_new_candidate_bytes = ?, original_new_candidate_digest = ?," - + " original_new_candidate_state = 'DISPATCH_POSSIBLE', inventory_revision = ?" - + " WHERE transition_id = ? AND status = 'PREPARED' AND inventory_revision = ?" - + " AND expected_prior_binding_ref IS NULL" - + " AND expected_prior_binding_generation IS NULL" - + " AND admission_lease_id IS NULL AND original_new_candidate_bytes IS NULL" - + " AND original_new_candidate_digest IS NULL AND original_new_candidate_state IS NULL" - + " AND original_new_candidate_readback_digest IS NULL", - candidateBytes, - candidateDigest, - decimal(nextRevision), - transitionId, - decimal(oldRevision)), - "Original NEW candidate lost its first durable dispatch claim"); - requireOne( - transaction.execute( - "UPDATE " - + INVENTORY - + " SET inventory_revision = ? WHERE binding_ref = ? AND transition_id = ?" - + " AND lifecycle = 'CANDIDATE_PREPARED' AND binding_generation = ?" - + " AND account_index_state = 'REPAIR_REQUIRED'" - + " AND issuer_index_state = 'REPAIR_REQUIRED' AND inventory_revision = ?", - decimal(nextRevision), - evidence.candidate().bindingRef().bytes(), - transitionId, - decimal(evidence.transition().bindingGeneration()), - decimal(oldRevision)), - "Original NEW candidate inventory row changed before first dispatch claim"); - requireCount( - transaction.execute( - "UPDATE " - + ACCOUNT_OBLIGATION - + " SET inventory_revision = ? WHERE transition_id = ? AND inventory_revision = ?", - decimal(nextRevision), - transitionId, - decimal(oldRevision)), - 1, - "Original NEW account-index obligation changed before first dispatch claim"); - requireOne( - transaction.execute( - "UPDATE " - + ISSUER_OBLIGATION - + " SET inventory_revision = ? WHERE transition_id = ? AND inventory_revision = ?", - decimal(nextRevision), - transitionId, - decimal(oldRevision)), - "Original NEW issuer-index obligation changed before first dispatch claim"); - requireOne( - transaction.execute( - "UPDATE " - + REGION_OBLIGATION - + " SET inventory_revision = ? WHERE transition_id = ? AND inventory_revision = ?", - decimal(nextRevision), - transitionId, - decimal(oldRevision)), - "Original NEW region obligation changed before first dispatch claim"); - requireOne( - transaction.execute( - "UPDATE " - + RESERVATION - + " SET inventory_revision = ? WHERE reservation_id = ? AND transition_id = ?" - + " AND lifecycle = 'RESERVED' AND inventory_revision = ?", - decimal(nextRevision), - evidence.candidateReservation().reservationId(), - transitionId, - decimal(oldRevision)), - "Original NEW issuer reservation changed before first dispatch claim"); - } - private static void bumpInventoryClock( DSLContext transaction, BigInteger currentRevision, BigInteger nextRevision) { requireOne( @@ -1701,18 +1511,7 @@ CanonicalGameplayBindingTransitionSnapshot markProvisional( CanonicalGameplayBindingTransitionSnapshot markProvisional( CanonicalGameplayBindingProvisionalCasEvidence expectedEvidence, CanonicalGameplayAdmissionDecision expectedDecision) { - return markProvisional(expectedEvidence, expectedDecision, null, null); - } - - private CanonicalGameplayBindingTransitionSnapshot markProvisional( - CanonicalGameplayBindingProvisionalCasEvidence expectedEvidence, - CanonicalGameplayAdmissionDecision expectedDecision, - CanonicalGameplayOriginalNewCandidate candidate, - CanonicalGameplayOriginalNewCandidateRedisOwner.PhysicalReadback readback) { Objects.requireNonNull(expectedEvidence, "expectedEvidence"); - if ((candidate == null) != (readback == null)) { - throw new IllegalArgumentException("Candidate and owner readback must be supplied together"); - } return dsl.transactionResult( configuration -> { DSLContext transaction = DSL.using(configuration); @@ -1736,68 +1535,6 @@ private CanonicalGameplayBindingTransitionSnapshot markProvisional( throw conflict( "First-binding provisional publication requires the exact Account lease decision"); } - boolean originalNew = current.expectedPrior() == null && expectedDecision != null; - if (originalNew && candidate != null) { - if (readback == null) throw conflict("Original NEW readback source is unavailable"); - requireDecisionMatchesOperation(expectedDecision, current); - CanonicalGameplayOriginalNewCandidate actualCandidate; - try { - actualCandidate = - CanonicalGameplayOriginalNewCandidate.fromOriginalSources( - current, expectedDecision); - } catch (RuntimeException invalidSource) { - throw conflict("Original NEW candidate sources are not exact"); - } - if (!actualCandidate.equals(candidate) - || !candidate.matchesOriginalDecision(expectedDecision) - || !candidate.matchesProvisionalSources(current) - || !readback.matches(candidate, current)) { - throw conflict("Owner readback does not bind the exact original NEW source"); - } - Record installation = findTransition(transaction, current.transition().transitionId()); - byte[] storedCandidate = installation.get("original_new_candidate_bytes", byte[].class); - String storedCandidateDigest = - installation.get("original_new_candidate_digest", String.class); - String installationState = - installation.get("original_new_candidate_state", String.class); - String storedReadbackDigest = - installation.get("original_new_candidate_readback_digest", String.class); - if (storedCandidate == null - || !Arrays.equals(storedCandidate, candidate.canonicalBytes()) - || !Objects.equals( - storedCandidateDigest, - CanonicalGameplayIssuerMemberV2Codec.sha256(storedCandidate))) { - throw conflict("Original NEW candidate bytes differ from the retained SQL source"); - } - if ("READBACK_CONFIRMED".equals(installationState)) { - if (!Objects.equals(storedReadbackDigest, readback.digest())) { - throw conflict("Original NEW candidate has a different retained physical readback"); - } - } else if ("DISPATCH_POSSIBLE".equals(installationState) - && current.transition().status() - == CanonicalGameplayBindingTransitionSnapshot.Status.PREPARED) { - requireOne( - transaction.execute( - "UPDATE " - + TRANSITION - + " SET original_new_candidate_state = 'READBACK_CONFIRMED'," - + " original_new_candidate_readback_digest = ?" - + " WHERE transition_id = ? AND status = 'PREPARED'" - + " AND original_new_candidate_bytes = ?" - + " AND original_new_candidate_digest = ?" - + " AND original_new_candidate_state = 'DISPATCH_POSSIBLE'" - + " AND original_new_candidate_readback_digest IS NULL", - readback.digest(), - current.transition().transitionId(), - candidate.canonicalBytes(), - storedCandidateDigest), - "Original NEW candidate readback source changed before provisional CAS"); - } else { - throw conflict("Original NEW candidate is not in a readback-confirmable state"); - } - } else if (candidate != null || readback != null) { - throw conflict("Original NEW candidate readback cannot authorize a transfer"); - } if (current.transition().status() == CanonicalGameplayBindingTransitionSnapshot.Status.PROVISIONAL) { Record row = findTransition(transaction, current.transition().transitionId()); @@ -4947,69 +4684,6 @@ private record AccountCoverageControl( BigInteger coverageGeneration, CanonicalGameplayAccountCoverageEvidence evidence) {} - enum OriginalNewCandidateInstallationState { - DISPATCH_POSSIBLE, - READBACK_CONFIRMED - } - - /** SQL-issued, one-use permission returned only by the transaction that first claims dispatch. */ - static final class OriginalNewCandidateCreatePermission { - private boolean consumed; - - private OriginalNewCandidateCreatePermission() {} - - synchronized boolean consume() { - if (consumed) return false; - consumed = true; - return true; - } - } - - /** - * Exact SQL source plus the optional first-dispatch permission; constructors stay - * repository-owned. - */ - static final class OriginalNewCandidateInstallationClaim { - private final CanonicalGameplayBindingProvisionalCasEvidence evidence; - private final CanonicalGameplayAdmissionDecision originalDecision; - private final CanonicalGameplayOriginalNewCandidate candidate; - private final OriginalNewCandidateInstallationState state; - private final OriginalNewCandidateCreatePermission createPermission; - - private OriginalNewCandidateInstallationClaim( - CanonicalGameplayBindingProvisionalCasEvidence evidence, - CanonicalGameplayAdmissionDecision originalDecision, - CanonicalGameplayOriginalNewCandidate candidate, - OriginalNewCandidateInstallationState state, - OriginalNewCandidateCreatePermission createPermission) { - this.evidence = Objects.requireNonNull(evidence, "evidence"); - this.originalDecision = Objects.requireNonNull(originalDecision, "originalDecision"); - this.candidate = Objects.requireNonNull(candidate, "candidate"); - this.state = Objects.requireNonNull(state, "state"); - this.createPermission = createPermission; - } - - CanonicalGameplayBindingProvisionalCasEvidence evidence() { - return evidence; - } - - CanonicalGameplayAdmissionDecision originalDecision() { - return originalDecision; - } - - CanonicalGameplayOriginalNewCandidate candidate() { - return candidate; - } - - OriginalNewCandidateInstallationState state() { - return state; - } - - boolean consumeCreatePermission() { - return createPermission != null && createPermission.consume(); - } - } - private static void requireOne(int changed, String message) { if (changed != 1) { throw conflict(message); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerCohortSql.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerCohortSql.java index ad5ea91fba..ff7eae1fc0 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerCohortSql.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerCohortSql.java @@ -15,14 +15,9 @@ final class CanonicalGameplayIssuerCohortSql { + " t.inventory_revision AS source_revision," // Preserve frozen pre-V1035 transition bytes for the absence-equivalent new NULL field. // A definitive abort UUID remains part of the full captured source. - + " (CASE WHEN to_jsonb(t)->'admission_orphan_cleanup_id' = 'null'::jsonb" - + " THEN to_jsonb(t) - 'admission_orphan_cleanup_id'" - + " ELSE to_jsonb(t) END" - // V1048 preserves old pending cohorts until an actual candidate dispatch is claimed. - + " - CASE WHEN to_jsonb(t)->'original_new_candidate_bytes' = 'null'::jsonb" - + " THEN ARRAY['original_new_candidate_bytes', 'original_new_candidate_digest'," - + " 'original_new_candidate_state', 'original_new_candidate_readback_digest']" - + " ELSE ARRAY[]::text[] END)::text AS source_row_json" + + " CASE WHEN to_jsonb(t)->'admission_orphan_cleanup_id' = 'null'::jsonb" + + " THEN (to_jsonb(t) - 'admission_orphan_cleanup_id')::text" + + " ELSE to_jsonb(t)::text END AS source_row_json" + " FROM game_session_canonical_binding_transition t WHERE t.inventory_revision <= ?" + " UNION ALL SELECT CASE WHEN r.issuer_id = ? THEN 'RESERVATION'" + " ELSE 'UNRESOLVED_LEGACY_RESERVATION' END AS source_kind," diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewAuthenticatedSession.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewAuthenticatedSession.java deleted file mode 100644 index 84b3bfda37..0000000000 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewAuthenticatedSession.java +++ /dev/null @@ -1,587 +0,0 @@ -package net.firedevops.firemud.gamesession.repository; - -import com.fasterxml.jackson.core.JsonFactory; -import com.fasterxml.jackson.core.StreamReadConstraints; -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.ByteBuffer; -import java.nio.charset.CharacterCodingException; -import java.nio.charset.CodingErrorAction; -import java.nio.charset.StandardCharsets; -import java.time.Clock; -import java.util.Arrays; -import java.util.Base64; -import java.util.Map; -import java.util.Objects; -import java.util.Set; -import java.util.regex.Pattern; -import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; -import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseGrpcCodec; -import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; - -/** - * Strict in-memory ORIGINAL_NEW gameplay-session payload template and schema-2 reader. - * - *

{@link Template} produces only the canonical bytes consumed by the final tenant-local session - * CAS. Its two unique time placeholders are never a finalized session and must never be persisted - * as a session record. Only {@link #parseFinalized(byte[], Clock)} accepts a complete schema-2 - * value. This class parses and correlates data; it does not perform the final CAS or prove current - * Account, Redis-registry, lease, barrier, or gameplay-admission authority. - */ -public final class CanonicalGameplayOriginalNewAuthenticatedSession { - public static final int SCHEMA_VERSION = 2; - public static final int MAX_SESSION_BYTES = 1024 * 1024; - public static final long MAX_CANONICAL_SESSION_DURATION_MILLIS = 300_000L; - public static final long FINAL_ADMISSION_CLOCK_SKEW_MILLIS = 5_000L; - - private static final String ADMISSION_AT_PLACEHOLDER = "__ORIGINAL_NEW_ADMISSION_AT_MS__"; - private static final String CONTINUITY_PLACEHOLDER = "__ORIGINAL_NEW_CONTINUITY_EXPIRES_AT_MS__"; - private static final Pattern SHA256 = Pattern.compile("[0-9a-f]{64}"); - private static final Pattern POSITIVE_DECIMAL = Pattern.compile("[1-9][0-9]{0,18}"); - private static final JsonFactory JSON_FACTORY = - JsonFactory.builder() - .streamReadConstraints( - StreamReadConstraints.builder() - .maxNestingDepth(64) - .maxStringLength(MAX_SESSION_BYTES) - .maxNumberLength(16) - .build()) - .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) - .build(); - private static final ObjectMapper JSON = - new ObjectMapper(JSON_FACTORY).enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS); - private static final Set SESSION_FIELDS = - Set.of( - "schemaVersion", - "admissionState", - "originalCandidate", - "bindingGeneration", - "accountIndexState", - "issuerIndexState", - "regionBridgeState", - "admissionAt", - "authTokenHash", - "authTokenIssuedAt", - "authTokenExpiresAt", - "tokenGeneration", - "issuanceFence", - "rebindHandle", - "continuityBindingExpiresAt", - "membershipBaseline", - "authorityTuple", - "outboxCheckpoints", - "canonicalSessionDurationMillis"); - private static final Set AUTHENTICATION_FIELDS = - Set.of( - "authTokenHash", - "authTokenIssuedAt", - "authTokenExpiresAt", - "tokenGeneration", - "issuanceFence", - "rebindHandle", - "continuityBindingExpiresAt", - "membershipBaseline", - "authorityTuple", - "outboxCheckpoints"); - - private CanonicalGameplayOriginalNewAuthenticatedSession() {} - - /** - * Verifies Account's complete signed result and freezes a non-persistable final-CAS template. - * - *

The duration must be the canonical, already-frozen session duration. The returned bytes - * contain the exact candidate and unchanged Account membership, tuple, and checkpoint values. - */ - public static Template template( - CanonicalGameplayOriginalNewCandidate originalCandidate, - AccountGameplayAdmissionLeaseGrpcCodec.OriginalNewCredential accountCredential, - CanonicalGameplayOriginalNewBoundCredentialVerifier credentialVerifier, - long canonicalSessionDurationMillis) { - Objects.requireNonNull(originalCandidate, "original NEW candidate is required"); - Objects.requireNonNull(accountCredential, "Account credential is required"); - Objects.requireNonNull(credentialVerifier, "bound credential verifier is required"); - requireCanonicalDuration(canonicalSessionDurationMillis); - - byte[] candidateBytes = null; - try (var verified = credentialVerifier.verify(originalCandidate, accountCredential)) { - candidateBytes = originalCandidate.canonicalBytes(); - CanonicalGameplayOriginalNewCandidate exactCandidate = - CanonicalGameplayOriginalNewCandidate.parseCanonical(candidateBytes); - if (!exactCandidate.exactlyMatches(candidateBytes)) throw invalid(); - byte[] templateBytes = makeTemplate(exactCandidate, verified, canonicalSessionDurationMillis); - try { - requireTemplateOnlyHasTimePlaceholders(templateBytes); - return new Template( - templateBytes, credentialVerifier.clock(), canonicalSessionDurationMillis); - } finally { - wipe(templateBytes); - } - } finally { - wipe(candidateBytes); - } - } - - /** - * Strictly reads a completed schema-2 session without establishing current admission authority. - */ - public static Finalized parseFinalized(byte[] encoded, Clock clock) { - Objects.requireNonNull(clock, "clock is required"); - if (encoded == null || encoded.length == 0 || encoded.length > MAX_SESSION_BYTES) { - throw invalid(); - } - byte[] handle = null; - byte[] canonical = null; - byte[] candidateBytes = null; - try { - String json = strictUtf8(encoded); - JsonNode parsed = JSON.readTree(json); - if (!(parsed instanceof ObjectNode root)) throw invalid(); - requireExactFields(root, SESSION_FIELDS); - requireSchemaAndAcknowledgements(root); - - candidateBytes = canonicalNode(root.get("originalCandidate")); - CanonicalGameplayOriginalNewCandidate candidate = - CanonicalGameplayOriginalNewCandidate.parseCanonical(candidateBytes); - AccountGameplayAdmissionLeaseEvidence lease = candidate.leaseEvidence(); - requireBindingAnchors(root, candidate, lease); - - String admissionAt = requiredText(root, "admissionAt"); - String continuityExpires = requiredText(root, "continuityBindingExpiresAt"); - String tokenHash = requiredText(root, "authTokenHash"); - String issuedAt = requiredText(root, "authTokenIssuedAt"); - String expiresAt = requiredText(root, "authTokenExpiresAt"); - String tokenGeneration = requiredText(root, "tokenGeneration"); - String issuanceFence = requiredText(root, "issuanceFence"); - String encodedHandle = requiredText(root, "rebindHandle"); - String duration = requiredText(root, "canonicalSessionDurationMillis"); - - if (!SHA256.matcher(tokenHash).matches()) throw invalid(); - long admissionAtMillis = positiveDecimal(admissionAt); - long continuityExpiresAtMillis = positiveDecimal(continuityExpires); - long tokenIssuedAtSeconds = positiveDecimal(issuedAt); - long tokenExpiresAtSeconds = positiveDecimal(expiresAt); - positiveDecimal(issuanceFence); - long durationMillis = positiveDecimal(duration); - requireCanonicalDuration(durationMillis); - if (!"1".equals(tokenGeneration)) throw invalid(); - if (!issuanceFence.equals(lease.carrier().get("issuanceFence"))) { - throw invalid(); - } - if (tokenIssuedAtSeconds >= tokenExpiresAtSeconds - || tokenExpiresAtSeconds - tokenIssuedAtSeconds > 300L) throw invalid(); - long admissionAtSeconds = admissionAtMillis / 1000L; - if (tokenIssuedAtSeconds > safeAdd(admissionAtSeconds, 5L) - || tokenExpiresAtSeconds <= admissionAtSeconds) throw invalid(); - if (new java.math.BigInteger((String) lease.carrier().get("expiresAt")) - .compareTo(java.math.BigInteger.valueOf(admissionAtMillis)) - <= 0) throw invalid(); - if (continuityExpiresAtMillis != safeAdd(admissionAtMillis, durationMillis)) throw invalid(); - long nowMillis = clock.millis(); - if (nowMillis <= 0L - || admissionAtMillis > safeAdd(nowMillis, FINAL_ADMISSION_CLOCK_SKEW_MILLIS)) { - throw invalid(); - } - - handle = decodeHandle(encodedHandle); - canonical = canonicalNode(root); - if (!Arrays.equals(canonical, encoded)) throw invalid(); - return new Finalized( - canonical, - candidate, - admissionAtMillis, - continuityExpiresAtMillis, - tokenHash, - tokenIssuedAtSeconds, - tokenExpiresAtSeconds, - issuanceFence, - durationMillis, - handle); - } catch (RuntimeException rejected) { - throw invalid(); - } catch (IOException malformed) { - throw invalid(); - } finally { - wipe(handle); - wipe(canonical); - wipe(candidateBytes); - } - } - - private static byte[] makeTemplate( - CanonicalGameplayOriginalNewCandidate candidate, - CanonicalGameplayOriginalNewBoundCredentialVerifier.VerifiedBoundCredential credential, - long canonicalSessionDurationMillis) { - byte[] handle = null; - byte[] candidateBytes = null; - try { - handle = credential.opaqueRebindHandle(); - candidateBytes = candidate.canonicalBytes(); - ObjectNode root = JSON.createObjectNode(); - root.put("schemaVersion", SCHEMA_VERSION); - root.put("admissionState", "COMPLETE"); - root.set("originalCandidate", JSON.readTree(candidateBytes)); - root.put("bindingGeneration", candidate.transition().bindingGeneration().toString()); - root.put("accountIndexState", "ACKNOWLEDGED"); - root.put("issuerIndexState", "ACKNOWLEDGED"); - root.put("regionBridgeState", "ACKNOWLEDGED"); - root.put("admissionAt", ADMISSION_AT_PLACEHOLDER); - root.put("authTokenHash", credential.tokenHash()); - root.put("authTokenIssuedAt", Long.toString(credential.issuedAtEpochSeconds())); - root.put("authTokenExpiresAt", Long.toString(credential.expiresAtEpochSeconds())); - root.put("tokenGeneration", credential.tokenGeneration()); - root.put("issuanceFence", credential.issuanceFence()); - root.put("rebindHandle", Base64.getUrlEncoder().withoutPadding().encodeToString(handle)); - root.put("continuityBindingExpiresAt", CONTINUITY_PLACEHOLDER); - Map lease = candidate.leaseEvidence().carrier(); - root.set("membershipBaseline", JSON.valueToTree(lease.get("membershipBaseline"))); - root.set("authorityTuple", JSON.valueToTree(lease.get("authorityTuple"))); - root.set("outboxCheckpoints", JSON.valueToTree(lease.get("outboxCheckpoints"))); - root.put("canonicalSessionDurationMillis", Long.toString(canonicalSessionDurationMillis)); - return canonicalNode(root); - } catch (IOException | RuntimeException malformed) { - throw invalid(); - } finally { - wipe(handle); - wipe(candidateBytes); - } - } - - private static void requireTemplateOnlyHasTimePlaceholders(byte[] templateBytes) { - try { - ObjectNode root = (ObjectNode) JSON.readTree(strictUtf8(templateBytes)); - requireExactFields(root, SESSION_FIELDS); - if (!ADMISSION_AT_PLACEHOLDER.equals(requiredText(root, "admissionAt")) - || !CONTINUITY_PLACEHOLDER.equals(requiredText(root, "continuityBindingExpiresAt"))) - throw invalid(); - root.fieldNames() - .forEachRemaining( - name -> { - if (!name.equals("admissionAt") && !name.equals("continuityBindingExpiresAt")) { - JsonNode value = root.get(name); - if (containsPlaceholder(value)) throw invalid(); - } - }); - } catch (IOException | RuntimeException malformed) { - throw invalid(); - } - } - - private static boolean containsPlaceholder(JsonNode value) { - if (value.isTextual()) { - return ADMISSION_AT_PLACEHOLDER.equals(value.textValue()) - || CONTINUITY_PLACEHOLDER.equals(value.textValue()); - } - if (value.isObject()) { - var fields = value.fields(); - while (fields.hasNext()) if (containsPlaceholder(fields.next().getValue())) return true; - } else if (value.isArray()) { - for (JsonNode item : value) if (containsPlaceholder(item)) return true; - } - return false; - } - - private static void requireSchemaAndAcknowledgements(ObjectNode root) { - JsonNode schema = root.get("schemaVersion"); - if (schema == null - || !schema.isIntegralNumber() - || !schema.canConvertToInt() - || schema.intValue() != SCHEMA_VERSION) { - throw invalid(); - } - if (!"COMPLETE".equals(requiredText(root, "admissionState")) - || !"ACKNOWLEDGED".equals(requiredText(root, "accountIndexState")) - || !"ACKNOWLEDGED".equals(requiredText(root, "issuerIndexState")) - || !"ACKNOWLEDGED".equals(requiredText(root, "regionBridgeState"))) throw invalid(); - for (String field : AUTHENTICATION_FIELDS) { - JsonNode value = root.get(field); - if (value == null || value.isNull()) throw invalid(); - } - } - - private static void requireBindingAnchors( - ObjectNode root, - CanonicalGameplayOriginalNewCandidate candidate, - AccountGameplayAdmissionLeaseEvidence lease) - throws IOException { - if (!candidate - .transition() - .bindingGeneration() - .toString() - .equals(requiredText(root, "bindingGeneration"))) throw invalid(); - Map carrier = lease.carrier(); - requireCanonicalEqual(root.get("membershipBaseline"), carrier.get("membershipBaseline")); - requireCanonicalEqual(root.get("authorityTuple"), carrier.get("authorityTuple")); - requireCanonicalEqual(root.get("outboxCheckpoints"), carrier.get("outboxCheckpoints")); - } - - private static void requireCanonicalEqual(JsonNode node, Object source) throws IOException { - byte[] left = canonicalNode(node); - byte[] right = Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(source)); - try { - if (!Arrays.equals(left, right)) throw invalid(); - } finally { - wipe(left); - wipe(right); - } - } - - private static byte[] decodeHandle(String encoded) { - if (encoded.isEmpty() || !encoded.matches("[A-Za-z0-9_-]+")) throw invalid(); - try { - byte[] result = Base64.getUrlDecoder().decode(encoded); - if (result.length != 32 - || !Base64.getUrlEncoder().withoutPadding().encodeToString(result).equals(encoded)) { - wipe(result); - throw invalid(); - } - return result; - } catch (IllegalArgumentException malformed) { - throw invalid(); - } - } - - private static byte[] canonicalNode(JsonNode node) throws IOException { - if (node == null) throw invalid(); - byte[] canonical = Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(node)); - if (canonical.length > MAX_SESSION_BYTES) { - wipe(canonical); - throw invalid(); - } - return canonical; - } - - private static String strictUtf8(byte[] encoded) { - try { - return StandardCharsets.UTF_8 - .newDecoder() - .onMalformedInput(CodingErrorAction.REPORT) - .onUnmappableCharacter(CodingErrorAction.REPORT) - .decode(ByteBuffer.wrap(encoded)) - .toString(); - } catch (CharacterCodingException malformed) { - throw invalid(); - } - } - - private static void requireExactFields(ObjectNode object, Set expected) { - Set actual = new java.util.HashSet<>(); - object.fieldNames().forEachRemaining(actual::add); - if (!actual.equals(expected)) throw invalid(); - } - - private static String requiredText(ObjectNode object, String field) { - JsonNode value = object.get(field); - if (value == null || !value.isTextual() || value.textValue().isEmpty()) throw invalid(); - return value.textValue(); - } - - private static long positiveDecimal(String value) { - if (value == null || !POSITIVE_DECIMAL.matcher(value).matches()) throw invalid(); - try { - return Long.parseLong(value); - } catch (NumberFormatException malformed) { - throw invalid(); - } - } - - private static void requireCanonicalDuration(long value) { - if (value <= 0L || value > MAX_CANONICAL_SESSION_DURATION_MILLIS) throw invalid(); - } - - private static long safeAdd(long left, long right) { - try { - return Math.addExact(left, right); - } catch (ArithmeticException malformed) { - throw invalid(); - } - } - - private static void wipe(byte[] value) { - if (value != null) Arrays.fill(value, (byte) 0); - } - - private static IllegalArgumentException invalid() { - return new IllegalArgumentException("Canonical ORIGINAL_NEW authenticated session is invalid"); - } - - /** In-memory pre-final-CAS bytes. Closing overwrites the encoded opaque handle. */ - public static final class Template implements AutoCloseable { - private byte[] canonicalTemplateBytes; - private final Clock clock; - private final long canonicalSessionDurationMillis; - - private Template( - byte[] canonicalTemplateBytes, Clock clock, long canonicalSessionDurationMillis) { - this.canonicalTemplateBytes = canonicalTemplateBytes.clone(); - this.clock = Objects.requireNonNull(clock); - this.canonicalSessionDurationMillis = canonicalSessionDurationMillis; - } - - public long canonicalSessionDurationMillis() { - return canonicalSessionDurationMillis; - } - - /** Exact canonical preimage for the final CAS; the two time strings are not final values. */ - public byte[] finalCasTemplateBytes() { - if (canonicalTemplateBytes == null) - throw new IllegalStateException("Session template is closed"); - return canonicalTemplateBytes.clone(); - } - - /** Validates final-CAS readback and allows only the two server-time values to differ. */ - public Finalized requireFinalizedReadback(byte[] finalCasReadback) { - if (canonicalTemplateBytes == null) - throw new IllegalStateException("Session template is closed"); - Finalized finalized = parseFinalized(finalCasReadback, clock); - byte[] templateCopy = canonicalTemplateBytes.clone(); - byte[] expected = null; - byte[] readbackBytes = null; - try { - ObjectNode root = (ObjectNode) JSON.readTree(strictUtf8(templateCopy)); - root.put("admissionAt", Long.toString(finalized.admissionAtMillis())); - root.put( - "continuityBindingExpiresAt", - Long.toString(finalized.continuityBindingExpiresAtMillis())); - expected = canonicalNode(root); - readbackBytes = finalized.canonicalBytes(); - if (!Arrays.equals(expected, readbackBytes)) throw invalid(); - return finalized; - } catch (RuntimeException rejected) { - finalized.close(); - throw invalid(); - } catch (Exception malformed) { - finalized.close(); - throw invalid(); - } finally { - wipe(templateCopy); - wipe(expected); - wipe(readbackBytes); - } - } - - @Override - public void close() { - wipe(canonicalTemplateBytes); - canonicalTemplateBytes = null; - } - - @Override - public String toString() { - return "CanonicalGameplayOriginalNewAuthenticatedSession.Template[nonAdmitting,redacted]"; - } - } - - /** Strictly decoded complete schema-2 bytes; the value itself supplies no current authority. */ - public static final class Finalized implements AutoCloseable { - private byte[] canonicalBytes; - private byte[] opaqueRebindHandle; - private final CanonicalGameplayOriginalNewCandidate originalCandidate; - private final long admissionAtMillis; - private final long continuityBindingExpiresAtMillis; - private final String authTokenHash; - private final long authTokenIssuedAt; - private final long authTokenExpiresAt; - private final String issuanceFence; - private final long canonicalSessionDurationMillis; - - private Finalized( - byte[] canonicalBytes, - CanonicalGameplayOriginalNewCandidate originalCandidate, - long admissionAtMillis, - long continuityBindingExpiresAtMillis, - String authTokenHash, - long authTokenIssuedAt, - long authTokenExpiresAt, - String issuanceFence, - long canonicalSessionDurationMillis, - byte[] opaqueRebindHandle) { - this.canonicalBytes = canonicalBytes.clone(); - this.originalCandidate = originalCandidate; - this.admissionAtMillis = admissionAtMillis; - this.continuityBindingExpiresAtMillis = continuityBindingExpiresAtMillis; - this.authTokenHash = authTokenHash; - this.authTokenIssuedAt = authTokenIssuedAt; - this.authTokenExpiresAt = authTokenExpiresAt; - this.issuanceFence = issuanceFence; - this.canonicalSessionDurationMillis = canonicalSessionDurationMillis; - this.opaqueRebindHandle = opaqueRebindHandle.clone(); - } - - public byte[] canonicalBytes() { - if (canonicalBytes == null) throw new IllegalStateException("Finalized session is closed"); - return canonicalBytes.clone(); - } - - public CanonicalGameplayOriginalNewCandidate originalCandidate() { - return originalCandidate; - } - - public CanonicalGameplayOriginalNewCandidate candidate() { - return originalCandidate; - } - - public long admissionAtMillis() { - return admissionAtMillis; - } - - public long continuityBindingExpiresAtMillis() { - return continuityBindingExpiresAtMillis; - } - - public long continuityExpiresAtMillis() { - return continuityBindingExpiresAtMillis; - } - - public String authTokenHash() { - return authTokenHash; - } - - public long authTokenIssuedAt() { - return authTokenIssuedAt; - } - - public long authTokenExpiresAt() { - return authTokenExpiresAt; - } - - public String tokenGeneration() { - return "1"; - } - - public String issuanceFence() { - return issuanceFence; - } - - public long canonicalSessionDurationMillis() { - return canonicalSessionDurationMillis; - } - - /** Returns only a caller-owned copy; Account remains the sole handle resolver. */ - public byte[] opaqueRebindHandle() { - if (opaqueRebindHandle == null) - throw new IllegalStateException("Finalized session is closed"); - return opaqueRebindHandle.clone(); - } - - public byte[] rebindHandle() { - return opaqueRebindHandle(); - } - - @Override - public void close() { - wipe(canonicalBytes); - wipe(opaqueRebindHandle); - canonicalBytes = null; - opaqueRebindHandle = null; - } - - @Override - public String toString() { - return "CanonicalGameplayOriginalNewAuthenticatedSession.Finalized[complete,redacted]"; - } - } -} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewBoundCredentialVerifier.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewBoundCredentialVerifier.java deleted file mode 100644 index e6df4341a8..0000000000 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewBoundCredentialVerifier.java +++ /dev/null @@ -1,318 +0,0 @@ -package net.firedevops.firemud.gamesession.repository; - -import com.fasterxml.jackson.databind.ObjectMapper; -import java.math.BigDecimal; -import java.nio.charset.StandardCharsets; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.time.Clock; -import java.util.Arrays; -import java.util.HashSet; -import java.util.HexFormat; -import java.util.Map; -import java.util.Objects; -import java.util.Set; -import java.util.UUID; -import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; -import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseGrpcCodec; -import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; -import net.firedevops.firemud.common.security.AccountAsymmetricJwtVerifier; -import net.firedevops.firemud.common.security.AccountAsymmetricJwtVerifier.ExplicitRouteProfilePolicy; -import net.firedevops.firemud.common.security.AccountAsymmetricJwtVerifier.VerifiedClaims; -import net.firedevops.firemud.common.security.AccountPublicJwksCache; -import net.firedevops.firemud.common.security.GameSessionAccountDelegationJwtProfileValidator; -import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; - -/** - * Verifies the Account-signed, tenant-bound ORIGINAL_NEW credential and its exact lease anchors. - * - *

This checks signature and claim/source shape only. It does not prove current Account - * authority, token-registry status, final admission, or gameplay admission. Those predicates stay - * with their owning readers and the final session CAS. - */ -public final class CanonicalGameplayOriginalNewBoundCredentialVerifier { - private static final ObjectMapper JSON = new ObjectMapper(); - private static final long ALLOWED_CLOCK_SKEW_SECONDS = 5L; - private static final ExplicitRouteProfilePolicy ORIGINAL_NEW_POLICY = policy(); - - private final AccountAsymmetricJwtVerifier verifier; - private final Clock clock; - - /** Requires the caller to supply the already configured trusted Account JWKS cache. */ - public CanonicalGameplayOriginalNewBoundCredentialVerifier( - AccountPublicJwksCache trustedAccountJwks, Clock clock) { - this.clock = Objects.requireNonNull(clock, "clock is required"); - this.verifier = - new AccountAsymmetricJwtVerifier( - Objects.requireNonNull(trustedAccountJwks, "trusted Account JWKS cache is required"), - clock); - } - - VerifiedBoundCredential verify( - CanonicalGameplayOriginalNewCandidate candidate, - AccountGameplayAdmissionLeaseGrpcCodec.OriginalNewCredential accountCredential) { - Objects.requireNonNull(candidate, "original NEW candidate is required"); - Objects.requireNonNull(accountCredential, "Account credential is required"); - byte[] compactBytes = null; - byte[] handle = null; - try { - String compactJwt = accountCredential.signedBoundGsACompactJwt(); - if (compactJwt == null - || compactJwt.isEmpty() - || compactJwt.length() > GameSessionAccountDelegationProfile.MAX_COMPACT_JWT_BYTES - || compactJwt.chars().anyMatch(value -> value > 0x7f)) { - throw invalid(); - } - compactBytes = compactJwt.getBytes(StandardCharsets.US_ASCII); - String tokenHash = sha256(compactBytes); - if (!tokenHash.equals(accountCredential.tokenSha256())) throw invalid(); - - VerifiedClaims verified = verifier.verify(compactJwt, ORIGINAL_NEW_POLICY); - Map claims = verified.claims(); - Map lease = candidate.leaseEvidence().carrier(); - Map bindingScope = object(lease.get("bindingScope")); - Map membershipBaseline = object(lease.get("membershipBaseline")); - Map tokenIdentityEvidence = object(lease.get("tokenIdentityEvidence")); - Object authorityTuple = lease.get("authorityTuple"); - Object checkpoints = lease.get("outboxCheckpoints"); - - String accountId = candidate.bindingIdentity().accountId().toString(); - String tenantId = candidate.bindingIdentity().tenantId().toString(); - String initialJti = text(tokenIdentityEvidence.get("tokenJti")); - String originalLeaseId = text(lease.get("leaseId")); - String issuedFence = text(lease.get("issuanceFence")); - String boundJti = accountCredential.tokenJti().toString(); - UUID lineageId = accountCredential.lineageId(); - long nowSeconds = clock.instant().getEpochSecond(); - long issuedAt = positiveEpochSecond(claims.get("iat")); - long notBefore = positiveEpochSecond(claims.get("nbf")); - long expiresAt = positiveEpochSecond(claims.get("exp")); - - if (!accountId.equals(bindingScope.get("accountId")) - || !tenantId.equals(bindingScope.get("tenantId")) - || !accountId.equals(claims.get("sub")) - || !accountId.equals(claims.get("accountId")) - || !tenantId.equals(claims.get("tenantId")) - || !boundJti.equals(claims.get("jti")) - || boundJti.equals(initialJti) - || lineageId.equals(accountCredential.tokenJti()) - || !"1".equals(claims.get("tokenGeneration")) - || !issuedFence.equals(claims.get("issuanceFence")) - || accountCredential.issuanceFence() != positiveDecimal(issuedFence) - || !originalLeaseId.equals(accountCredential.originalLeaseId().toString()) - || candidate.leaseEvidence().leaseFence().longValueExact() - != accountCredential.originalLeaseFence() - || !canonicalEquals(authorityTuple, claims.get("authorityTuple")) - || !canonicalEquals( - membershipBaseline.get("membershipVersion"), claims.get("membershipVersion")) - || !candidate - .leaseEvidence() - .leaseKind() - .equals(AccountGameplayAdmissionLeaseEvidence.LeaseKind.NEW_BINDING) - || !accountCredential.checkpointsSha256().equals(sha256Canonical(checkpoints))) { - throw invalid(); - } - - String membershipGeneration = text(membershipBaseline.get("membershipAuthorityGeneration")); - Map tuple = object(authorityTuple); - Map membershipAuthority = object(tuple.get("membershipAuthorityGeneration")); - if (!membershipGeneration.equals(membershipAuthority.get(tenantId))) throw invalid(); - - if (issuedAt > safeAdd(nowSeconds, ALLOWED_CLOCK_SKEW_SECONDS) - || notBefore > safeAdd(nowSeconds, ALLOWED_CLOCK_SKEW_SECONDS) - || expiresAt <= nowSeconds - || notBefore > expiresAt - || issuedAt >= expiresAt - || safeSubtract(notBefore, issuedAt) > ALLOWED_CLOCK_SKEW_SECONDS - || safeSubtract(issuedAt, notBefore) > ALLOWED_CLOCK_SKEW_SECONDS - || safeSubtract(expiresAt, issuedAt) - > GameSessionAccountDelegationProfile.MAX_TOKEN_LIFETIME_SECONDS) { - throw invalid(); - } - - handle = accountCredential.opaqueRebindHandle(); - if (handle.length != 32) throw invalid(); - return new VerifiedBoundCredential(tokenHash, issuedAt, expiresAt, "1", issuedFence, handle); - } catch (AccountAsymmetricJwtVerifier.VerificationUnavailableException unavailable) { - throw unavailable; - } catch (RuntimeException rejected) { - throw invalid(); - } catch (Exception malformed) { - throw invalid(); - } finally { - wipe(compactBytes); - wipe(handle); - } - } - - Clock clock() { - return clock; - } - - private static ExplicitRouteProfilePolicy policy() { - Set required = - new HashSet<>(GameSessionAccountDelegationJwtProfileValidator.REQUIRED_CLAIMS); - required.add("tenantId"); - return new ExplicitRouteProfilePolicy( - "game-session-original-new-bound-credential", - GameSessionAccountDelegationProfile.PROFILE, - GameSessionAccountDelegationProfile.TYPE, - GameSessionAccountDelegationProfile.ISSUER, - GameSessionAccountDelegationProfile.AUDIENCE, - required, - Set.of(), - GameSessionAccountDelegationProfile.MAX_TOKEN_LIFETIME_SECONDS, - ALLOWED_CLOCK_SKEW_SECONDS, - GameSessionAccountDelegationProfile.MAX_COMPACT_JWT_BYTES, - GameSessionAccountDelegationJwtProfileValidator::validatePublicTenantBoundClaims); - } - - private static boolean canonicalEquals(Object left, Object right) throws Exception { - byte[] leftBytes = null; - byte[] rightBytes = null; - try { - leftBytes = canonicalBytes(left); - rightBytes = canonicalBytes(right); - return Arrays.equals(leftBytes, rightBytes); - } finally { - wipe(leftBytes); - wipe(rightBytes); - } - } - - private static byte[] canonicalBytes(Object value) throws Exception { - return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); - } - - private static String sha256Canonical(Object value) throws Exception { - byte[] canonical = canonicalBytes(value); - try { - return sha256(canonical); - } finally { - wipe(canonical); - } - } - - private static String sha256(byte[] bytes) { - try { - return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); - } catch (NoSuchAlgorithmException unavailable) { - throw new IllegalStateException("SHA-256 is unavailable", unavailable); - } - } - - private static Map object(Object value) { - if (!(value instanceof Map map)) throw invalid(); - return map; - } - - private static String text(Object value) { - if (!(value instanceof String text) || text.isBlank()) throw invalid(); - return text; - } - - private static long positiveEpochSecond(Object value) { - if (!(value instanceof Number number)) throw invalid(); - try { - long seconds = new BigDecimal(number.toString()).longValueExact(); - if (seconds <= 0L) throw invalid(); - return seconds; - } catch (ArithmeticException | NumberFormatException malformed) { - throw invalid(); - } - } - - private static long positiveDecimal(String value) { - if (value == null || !value.matches("[1-9][0-9]{0,18}")) throw invalid(); - try { - return Long.parseLong(value); - } catch (NumberFormatException malformed) { - throw invalid(); - } - } - - private static long safeAdd(long left, long right) { - try { - return Math.addExact(left, right); - } catch (ArithmeticException malformed) { - throw invalid(); - } - } - - private static long safeSubtract(long left, long right) { - try { - return Math.subtractExact(left, right); - } catch (ArithmeticException malformed) { - throw invalid(); - } - } - - private static void wipe(byte[] value) { - if (value != null) Arrays.fill(value, (byte) 0); - } - - private static IllegalArgumentException invalid() { - return new IllegalArgumentException("Original NEW bound credential is invalid"); - } - - static final class VerifiedBoundCredential implements AutoCloseable { - private final String tokenHash; - private final long issuedAtEpochSeconds; - private final long expiresAtEpochSeconds; - private final String tokenGeneration; - private final String issuanceFence; - private byte[] opaqueRebindHandle; - - private VerifiedBoundCredential( - String tokenHash, - long issuedAtEpochSeconds, - long expiresAtEpochSeconds, - String tokenGeneration, - String issuanceFence, - byte[] opaqueRebindHandle) { - this.tokenHash = tokenHash; - this.issuedAtEpochSeconds = issuedAtEpochSeconds; - this.expiresAtEpochSeconds = expiresAtEpochSeconds; - this.tokenGeneration = tokenGeneration; - this.issuanceFence = issuanceFence; - this.opaqueRebindHandle = opaqueRebindHandle.clone(); - } - - String tokenHash() { - return tokenHash; - } - - long issuedAtEpochSeconds() { - return issuedAtEpochSeconds; - } - - long expiresAtEpochSeconds() { - return expiresAtEpochSeconds; - } - - String tokenGeneration() { - return tokenGeneration; - } - - String issuanceFence() { - return issuanceFence; - } - - byte[] opaqueRebindHandle() { - if (opaqueRebindHandle == null) - throw new IllegalStateException("Verified credential is closed"); - return opaqueRebindHandle.clone(); - } - - @Override - public void close() { - wipe(opaqueRebindHandle); - opaqueRebindHandle = null; - } - - @Override - public String toString() { - return "VerifiedBoundCredential[metadata-only,handle-redacted]"; - } - } -} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCandidate.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCandidate.java deleted file mode 100644 index dbc3418b77..0000000000 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCandidate.java +++ /dev/null @@ -1,219 +0,0 @@ -package net.firedevops.firemud.gamesession.repository; - -import java.math.BigInteger; -import java.util.Arrays; -import java.util.Objects; -import java.util.UUID; -import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; -import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAdmissionDecision; -import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingIdentity; -import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingInventoryEntry; -import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingProvisionalCasEvidence; -import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingRef; -import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingTransitionSnapshot; -import net.firedevops.firemud.gamesession.binding.CanonicalIssuerPartitionReservation; -import net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget; - -/** - * Exact, typed source bytes for the non-admitting original {@code NEW} session candidate. - * - *

This is a data carrier only. It does not prove that any input came from Account or the durable - * Game Session owners, establish a physical Redis readback, finalize the Account lease, or - * authorize gameplay. Authenticated session readers must reject its separate purpose discriminator. - * - *

The payload retains the complete immutable Account lease and original decision sources plus - * the durable candidate, transition, reservation, and target identities. It deliberately omits - * mutable preparation status and current inventory revisions so a retry after unrelated SQL - * inventory progress reproduces the original candidate bytes. - */ -public final class CanonicalGameplayOriginalNewCandidate { - public static final String PURPOSE = "original-new-non-admitting-candidate/v1"; - - private final UUID bindingDecisionId; - private final AccountGameplayAdmissionLeaseEvidence leaseEvidence; - private final CanonicalGameplayBindingIdentity bindingIdentity; - private final CanonicalPlayableTarget targetEvidence; - private final TransitionSource transition; - private final ReservationSource reservation; - - CanonicalGameplayOriginalNewCandidate( - UUID bindingDecisionId, - AccountGameplayAdmissionLeaseEvidence leaseEvidence, - CanonicalGameplayBindingIdentity bindingIdentity, - CanonicalPlayableTarget targetEvidence, - TransitionSource transition, - ReservationSource reservation) { - this.bindingDecisionId = Objects.requireNonNull(bindingDecisionId, "bindingDecisionId"); - this.leaseEvidence = Objects.requireNonNull(leaseEvidence, "leaseEvidence"); - this.bindingIdentity = Objects.requireNonNull(bindingIdentity, "bindingIdentity"); - this.targetEvidence = Objects.requireNonNull(targetEvidence, "targetEvidence"); - this.transition = Objects.requireNonNull(transition, "transition"); - this.reservation = Objects.requireNonNull(reservation, "reservation"); - } - - /** - * Freezes the selected original sources after checking their shared identity and NEW-only - * preconditions. This factory is structural and does not elevate either source to authority. - */ - static CanonicalGameplayOriginalNewCandidate fromOriginalSources( - CanonicalGameplayBindingProvisionalCasEvidence provisionalEvidence, - CanonicalGameplayAdmissionDecision originalDecision) { - Objects.requireNonNull(provisionalEvidence, "provisionalEvidence"); - Objects.requireNonNull(originalDecision, "originalDecision"); - CanonicalGameplayOriginalNewCandidateCodec.requireOriginalNewSources( - provisionalEvidence, originalDecision); - CanonicalGameplayBindingTransitionSnapshot transition = provisionalEvidence.transition(); - CanonicalGameplayBindingInventoryEntry candidate = provisionalEvidence.candidate(); - CanonicalIssuerPartitionReservation reservation = provisionalEvidence.candidateReservation(); - return new CanonicalGameplayOriginalNewCandidate( - originalDecision.bindingDecisionId(), - originalDecision.leaseEvidence(), - candidate.identity(), - originalDecision.targetEvidence(), - new TransitionSource( - transition.transitionId(), - transition.bindingRef(), - transition.bindingGeneration(), - transition.issuerReservationId(), - transition.reservationFence(), - transition.candidateAccountIndexFence()), - CanonicalGameplayOriginalNewCandidateCodec.reservationSource(reservation)); - } - - /** Parses only this closed candidate format; the result is not a verified readback capability. */ - public static CanonicalGameplayOriginalNewCandidate parseCanonical(byte[] encoded) { - return CanonicalGameplayOriginalNewCandidateCodec.decode(encoded); - } - - public UUID bindingDecisionId() { - return bindingDecisionId; - } - - /** Complete immutable lease carrier, including its unchanged baseline, tuple, and checkpoints. */ - public AccountGameplayAdmissionLeaseEvidence leaseEvidence() { - return leaseEvidence; - } - - /** Exact canonical session identity from which the session key is derived by its owner. */ - public CanonicalGameplayBindingIdentity bindingIdentity() { - return bindingIdentity; - } - - /** Full original canonical target source retained with the decision. */ - public CanonicalPlayableTarget targetEvidence() { - return targetEvidence; - } - - /** Stable transition identity and fences used by the original provisional CAS. */ - public TransitionSource transition() { - return transition; - } - - /** - * Immutable reservation identity, fences and original snapshot; current revisions may advance. - */ - public ReservationSource reservation() { - return reservation; - } - - /** The one exact canonical JSON preimage to install and later exact-compare. */ - public byte[] canonicalBytes() { - return CanonicalGameplayOriginalNewCandidateCodec.encode(this); - } - - public String canonicalJson() { - return new String(canonicalBytes(), java.nio.charset.StandardCharsets.UTF_8); - } - - /** Exact byte comparison for a physical preimage/readback or final-CAS expected value. */ - public boolean exactlyMatches(byte[] physicalValue) { - return physicalValue != null && Arrays.equals(canonicalBytes(), physicalValue); - } - - /** - * Compares every retained original-decision field. The decision class has no value equality, so - * this comparison is explicit and includes its complete Account lease and full target source. - */ - public boolean matchesOriginalDecision(CanonicalGameplayAdmissionDecision decision) { - return CanonicalGameplayOriginalNewCandidateCodec.matchesOriginalDecision(this, decision); - } - - /** - * Checks stable source identity while allowing only the documented PREPARED/PROVISIONAL retry. - */ - public boolean matchesProvisionalSources( - CanonicalGameplayBindingProvisionalCasEvidence evidence) { - return CanonicalGameplayOriginalNewCandidateCodec.matchesProvisionalSources(this, evidence); - } - - @Override - public boolean equals(Object other) { - return other instanceof CanonicalGameplayOriginalNewCandidate candidate - && Arrays.equals(canonicalBytes(), candidate.canonicalBytes()); - } - - @Override - public int hashCode() { - return Arrays.hashCode(canonicalBytes()); - } - - /** Avoid logging the lease or source payload through implicit object formatting. */ - @Override - public String toString() { - return "CanonicalGameplayOriginalNewCandidate[purpose=" + PURPOSE + ", nonAdmitting=true]"; - } - - /** Immutable stable projection of the transition's original identity and fences. */ - public record TransitionSource( - UUID transitionId, - CanonicalGameplayBindingRef bindingRef, - BigInteger bindingGeneration, - UUID issuerReservationId, - UUID reservationFence, - UUID candidateAccountIndexFence) { - public TransitionSource { - Objects.requireNonNull(transitionId, "transitionId"); - Objects.requireNonNull(bindingRef, "bindingRef"); - requirePositive(bindingGeneration, "bindingGeneration"); - Objects.requireNonNull(issuerReservationId, "issuerReservationId"); - Objects.requireNonNull(reservationFence, "reservationFence"); - Objects.requireNonNull(candidateAccountIndexFence, "candidateAccountIndexFence"); - } - } - - /** Immutable reservation source fields; the current mutable inventory revision is excluded. */ - public record ReservationSource( - UUID reservationId, - CanonicalGameplayBindingRef ownerBindingRef, - BigInteger bindingGeneration, - UUID transitionId, - BigInteger partitionId, - UUID reservationFence, - UUID issuerCoverageOperationId, - BigInteger issuerCoverageOperationFence, - BigInteger coverageFence, - BigInteger inventorySnapshotRevision) { - public ReservationSource { - Objects.requireNonNull(reservationId, "reservationId"); - Objects.requireNonNull(ownerBindingRef, "ownerBindingRef"); - requirePositive(bindingGeneration, "bindingGeneration"); - Objects.requireNonNull(transitionId, "transitionId"); - requireNonNegative(partitionId, "partitionId"); - Objects.requireNonNull(reservationFence, "reservationFence"); - Objects.requireNonNull(issuerCoverageOperationId, "issuerCoverageOperationId"); - requirePositive(issuerCoverageOperationFence, "issuerCoverageOperationFence"); - requirePositive(coverageFence, "coverageFence"); - requirePositive(inventorySnapshotRevision, "inventorySnapshotRevision"); - } - } - - private static void requirePositive(BigInteger value, String name) { - Objects.requireNonNull(value, name); - if (value.signum() <= 0) throw new IllegalArgumentException(name + " must be positive"); - } - - private static void requireNonNegative(BigInteger value, String name) { - Objects.requireNonNull(value, name); - if (value.signum() < 0) throw new IllegalArgumentException(name + " must not be negative"); - } -} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCandidateCodec.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCandidateCodec.java deleted file mode 100644 index 577341d7cf..0000000000 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCandidateCodec.java +++ /dev/null @@ -1,731 +0,0 @@ -package net.firedevops.firemud.gamesession.repository; - -import com.fasterxml.jackson.core.JsonFactory; -import com.fasterxml.jackson.core.StreamReadConstraints; -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.time.Instant; -import java.util.Arrays; -import java.util.Base64; -import java.util.HashSet; -import java.util.Objects; -import java.util.Set; -import java.util.UUID; -import java.util.regex.Pattern; -import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; -import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; -import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAdmissionDecision; -import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingIdentity; -import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingInventoryEntry; -import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingProvisionalCasEvidence; -import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingRef; -import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingTransitionSnapshot; -import net.firedevops.firemud.gamesession.binding.CanonicalIssuerPartitionReservation; -import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionOwnerProof; -import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionRequest; -import net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget; - -/** Closed, bounded RFC 8785 codec for the distinct original-NEW candidate purpose. */ -final class CanonicalGameplayOriginalNewCandidateCodec { - static final int MAX_CANDIDATE_BYTES = 128 * 1024; - private static final int MAX_COUNTER_DIGITS = 256; - private static final Pattern POSITIVE_DECIMAL = Pattern.compile("[1-9][0-9]{0,255}"); - private static final Pattern NON_NEGATIVE_DECIMAL = Pattern.compile("(?:0|[1-9][0-9]{0,255})"); - private static final JsonFactory JSON_FACTORY = - JsonFactory.builder() - .streamReadConstraints( - StreamReadConstraints.builder() - .maxNestingDepth(12) - .maxStringLength(MAX_CANDIDATE_BYTES) - .maxNumberLength(8) - .build()) - .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) - .build(); - private static final ObjectMapper JSON = - new ObjectMapper(JSON_FACTORY).enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS); - private static final Set ROOT_FIELDS = - Set.of( - "purpose", - "bindingDecisionId", - "leaseEvidence", - "binding", - "target", - "transition", - "reservation"); - private static final Set BINDING_FIELDS = - Set.of( - "accountId", - "tenantId", - "playableStateNamespaceId", - "characterId", - "playableStateScope", - "gameInstanceId", - "runtimeGameInstanceId", - "sessionId", - "regionId", - "regionEpoch", - "issuerId", - "issuerAuthGeneration", - "issuerIndexLayoutVersion", - "issuerIndexPartitionCount", - "issuerIndexPartitionCapacity"); - private static final Set TARGET_FIELDS = - Set.of( - "targetNamespace", - "tenantSlug", - "canonicalTenantId", - "worldSlug", - "worldDisplayName", - "realmId", - "realmSlug", - "realmDisplayName", - "gameSessionTenantId", - "gameInstanceId", - "playableStateNamespaceId", - "playableStateScope", - "canonicalGameInstanceId", - "canonicalVersionId", - "runtimeVersionId", - "catalogRevision", - "pointerVersion", - "admissionPointerSnapshotDigest", - "activeWorldEpoch", - "initialAdmissionRequestId", - "initialAdmissionRequestDigest", - "initialAdmissionOriginKind", - "holdId", - "holdFence", - "holdBindingDigest", - "auditEventId", - "ownerProofDigest", - "ownerProofOutcome", - "positiveDurableAbort", - "ownerProofTerminalAt", - "characterCreationPolicy"); - private static final Set TRANSITION_FIELDS = - Set.of( - "transitionId", - "bindingRef", - "bindingGeneration", - "issuerReservationId", - "reservationFence", - "candidateAccountIndexFence"); - private static final Set RESERVATION_FIELDS = - Set.of( - "reservationId", - "ownerBindingRef", - "bindingGeneration", - "transitionId", - "partitionId", - "lifecycle", - "reservationFence", - "issuerCoverageOperationId", - "issuerCoverageOperationFence", - "coverageFence", - "inventorySnapshotRevision"); - - private CanonicalGameplayOriginalNewCandidateCodec() {} - - static byte[] encode(CanonicalGameplayOriginalNewCandidate candidate) { - Objects.requireNonNull(candidate, "candidate"); - try { - requireCounterLimit(candidate.bindingIdentity().regionEpoch(), "regionEpoch", false); - requireCounterLimit( - candidate.bindingIdentity().issuerAuthGeneration(), "issuerAuthGeneration", false); - requireCounterLimit( - candidate.bindingIdentity().issuerIndexLayoutVersion(), - "issuerIndexLayoutVersion", - false); - requireCounterLimit( - candidate.bindingIdentity().issuerIndexPartitionCount(), - "issuerIndexPartitionCount", - false); - requireCounterLimit( - candidate.bindingIdentity().issuerIndexPartitionCapacity(), - "issuerIndexPartitionCapacity", - false); - requireCounterLimit(candidate.transition().bindingGeneration(), "bindingGeneration", false); - requireCounterLimit( - candidate.reservation().bindingGeneration(), "reservation.bindingGeneration", false); - requireCounterLimit(candidate.reservation().partitionId(), "partitionId", true); - requireCounterLimit( - candidate.reservation().issuerCoverageOperationFence(), - "issuerCoverageOperationFence", - false); - requireCounterLimit(candidate.reservation().coverageFence(), "coverageFence", false); - requireCounterLimit( - candidate.reservation().inventorySnapshotRevision(), "inventorySnapshotRevision", false); - - ObjectNode root = JSON.createObjectNode(); - root.put("purpose", CanonicalGameplayOriginalNewCandidate.PURPOSE); - root.put("bindingDecisionId", candidate.bindingDecisionId().toString()); - root.set("leaseEvidence", parseCanonicalLeaseNode(candidate.leaseEvidence())); - root.set("binding", bindingNode(candidate.bindingIdentity())); - root.set("target", targetNode(candidate.targetEvidence())); - root.set("transition", transitionNode(candidate.transition())); - root.set("reservation", reservationNode(candidate.reservation())); - byte[] canonical = Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(root)); - if (canonical.length == 0 || canonical.length > MAX_CANDIDATE_BYTES) { - throw invalid("Original NEW candidate exceeds its 128 KiB resource bound"); - } - return canonical; - } catch (IOException failure) { - throw new IllegalArgumentException("Could not encode original NEW candidate", failure); - } - } - - static CanonicalGameplayOriginalNewCandidate decode(byte[] encoded) { - Objects.requireNonNull(encoded, "encoded"); - if (encoded.length == 0 || encoded.length > MAX_CANDIDATE_BYTES) { - throw invalid("Original NEW candidate is empty or exceeds its resource bound"); - } - String json = decodeUtf8(encoded); - try { - ObjectNode root = requireObject(JSON.readTree(json), "candidate"); - requireFields(root, ROOT_FIELDS, "candidate"); - if (!text(root, "purpose").equals(CanonicalGameplayOriginalNewCandidate.PURPOSE)) { - throw invalid("Candidate purpose is unsupported"); - } - - AccountGameplayAdmissionLeaseEvidence leaseEvidence = - parseLeaseEvidence(root.get("leaseEvidence")); - CanonicalGameplayBindingIdentity binding = parseBinding(root.get("binding")); - CanonicalPlayableTarget target = parseTarget(root.get("target")); - CanonicalGameplayOriginalNewCandidate.TransitionSource transition = - parseTransition(root.get("transition")); - CanonicalGameplayOriginalNewCandidate.ReservationSource reservation = - parseReservation(root.get("reservation")); - UUID decisionId = uuid(root, "bindingDecisionId"); - - var decoded = - new CanonicalGameplayOriginalNewCandidate( - decisionId, leaseEvidence, binding, target, transition, reservation); - validateDecodedSources(decoded); - if (!Arrays.equals(encode(decoded), encoded)) { - throw invalid("Original NEW candidate bytes are not canonical"); - } - return decoded; - } catch (IOException failure) { - throw new IllegalArgumentException("Malformed original NEW candidate", failure); - } - } - - static boolean matchesOriginalDecision( - CanonicalGameplayOriginalNewCandidate candidate, - CanonicalGameplayAdmissionDecision decision) { - return decision != null - && decision.status() == CanonicalGameplayAdmissionDecision.Status.PROVISIONAL - && candidate.bindingDecisionId().equals(decision.bindingDecisionId()) - && candidate.leaseEvidence().hasSameIdentity(decision.leaseEvidence()) - && candidate.bindingIdentity().equals(decision.candidate()) - && candidate.transition().bindingGeneration().equals(decision.bindingGeneration()) - && decision.expectedOldBindingGeneration() == null - && decision.resumeEpisodeId() == null - && candidate.targetEvidence().equals(decision.targetEvidence()) - && isPublicProductionNewLease(decision.leaseEvidence()); - } - - static boolean matchesProvisionalSources( - CanonicalGameplayOriginalNewCandidate candidate, - CanonicalGameplayBindingProvisionalCasEvidence evidence) { - if (evidence == null) return false; - try { - requireCandidateSourceShape(evidence); - CanonicalGameplayBindingTransitionSnapshot transition = evidence.transition(); - CanonicalGameplayBindingInventoryEntry entry = evidence.candidate(); - CanonicalIssuerPartitionReservation reservation = evidence.candidateReservation(); - return candidate.bindingIdentity().equals(entry.identity()) - && candidate.transition().transitionId().equals(transition.transitionId()) - && candidate.transition().bindingRef().equals(transition.bindingRef()) - && candidate.transition().bindingGeneration().equals(transition.bindingGeneration()) - && candidate.transition().issuerReservationId().equals(transition.issuerReservationId()) - && candidate.transition().reservationFence().equals(transition.reservationFence()) - && candidate - .transition() - .candidateAccountIndexFence() - .equals(transition.candidateAccountIndexFence()) - && candidate.transition().bindingRef().equals(entry.bindingRef()) - && candidate.transition().bindingGeneration().equals(entry.bindingGeneration()) - && candidate.transition().candidateAccountIndexFence().equals(entry.accountIndexFence()) - && candidate.reservation().equals(reservationSource(reservation)); - } catch (RuntimeException invalidSource) { - return false; - } - } - - static void requireOriginalNewSources( - CanonicalGameplayBindingProvisionalCasEvidence evidence, - CanonicalGameplayAdmissionDecision decision) { - requireCandidateSourceShape(evidence); - if (!isPublicProductionNewLease(decision.leaseEvidence())) { - throw invalid("Only the selected public-production original NEW lease is supported"); - } - CanonicalGameplayBindingTransitionSnapshot transition = evidence.transition(); - CanonicalGameplayBindingInventoryEntry candidate = evidence.candidate(); - CanonicalIssuerPartitionReservation reservation = evidence.candidateReservation(); - if (!transition.transitionId().equals(decision.bindingDecisionId()) - || !candidate.identity().equals(decision.candidate()) - || !candidate.bindingGeneration().equals(decision.bindingGeneration()) - || decision.expectedOldBindingGeneration() != null - || decision.resumeEpisodeId() != null - || !candidate.identity().equals(reservation.owner()) - || !candidate.bindingGeneration().equals(reservation.bindingGeneration()) - || !transition.transitionId().equals(reservation.transitionId()) - || !transition.reservationFence().equals(reservation.reservationFence()) - || !transition.issuerReservationId().equals(reservation.reservationId())) { - throw invalid("Decision, candidate, transition, and reservation identities differ"); - } - } - - private static void requireCandidateSourceShape( - CanonicalGameplayBindingProvisionalCasEvidence evidence) { - Objects.requireNonNull(evidence, "provisionalEvidence"); - CanonicalGameplayBindingTransitionSnapshot transition = evidence.transition(); - CanonicalGameplayBindingInventoryEntry candidate = evidence.candidate(); - CanonicalIssuerPartitionReservation reservation = evidence.candidateReservation(); - if (evidence.expectedPrior() != null - || evidence.expectedPriorReservation() != null - || (transition.status() != CanonicalGameplayBindingTransitionSnapshot.Status.PREPARED - && transition.status() != CanonicalGameplayBindingTransitionSnapshot.Status.PROVISIONAL) - || transition.expectedPriorBindingRef() != null - || transition.expectedPriorBindingGeneration() != null - || !transition.transitionId().equals(candidate.transitionId()) - || !transition.bindingRef().equals(candidate.bindingRef()) - || !transition.bindingGeneration().equals(candidate.bindingGeneration()) - || !transition.candidate().equals(candidate.identity()) - || !transition.issuerReservationId().equals(candidate.issuerReservationId()) - || !transition.candidateAccountIndexFence().equals(candidate.accountIndexFence()) - || !reservation.owner().equals(candidate.identity()) - || !reservation.bindingGeneration().equals(candidate.bindingGeneration()) - || !reservation.transitionId().equals(transition.transitionId()) - || !reservation.reservationId().equals(transition.issuerReservationId()) - || !reservation.reservationFence().equals(transition.reservationFence()) - || reservation.lifecycle() != CanonicalIssuerPartitionReservation.Lifecycle.RESERVED) { - throw invalid("Source is not an exact no-prior PREPARED or PROVISIONAL NEW candidate"); - } - } - - private static boolean isPublicProductionNewLease( - AccountGameplayAdmissionLeaseEvidence evidence) { - return evidence != null - && evidence.leaseKind() == AccountGameplayAdmissionLeaseEvidence.LeaseKind.NEW_BINDING - && "PUBLIC_PRODUCTION".equals(evidence.carrier().get("mode")) - && !evidence.carrier().containsKey("expectedOldBindingGeneration") - && !evidence.carrier().containsKey("resumeEpisodeId"); - } - - private static void validateDecodedSources(CanonicalGameplayOriginalNewCandidate candidate) { - var binding = candidate.bindingIdentity(); - var transition = candidate.transition(); - var reservation = candidate.reservation(); - if (!candidate.bindingDecisionId().equals(transition.transitionId()) - || !binding.bindingRef().equals(transition.bindingRef()) - || !binding.bindingRef().equals(reservation.ownerBindingRef()) - || !transition.bindingGeneration().equals(bindingGeneration(candidate.leaseEvidence())) - || !transition.bindingGeneration().equals(reservation.bindingGeneration()) - || !transition.transitionId().equals(reservation.transitionId()) - || !transition.issuerReservationId().equals(reservation.reservationId()) - || !transition.reservationFence().equals(reservation.reservationFence()) - || !reservation - .partitionId() - .equals(binding.bindingRef().partitionId(binding.issuerIndexPartitionCount()))) { - throw invalid("Candidate source identities, generation, or fences do not agree"); - } - if (!isPublicProductionNewLease(candidate.leaseEvidence())) { - throw invalid("Candidate does not retain the selected public-production NEW lease"); - } - try { - // Reuse the existing decision's cross-source checks. This temporary shape check is not - // returned as an original decision and establishes neither provenance nor readback. - new CanonicalGameplayAdmissionDecision( - candidate.bindingDecisionId(), - candidate.leaseEvidence(), - binding, - transition.bindingGeneration(), - null, - candidate.targetEvidence()); - } catch (RuntimeException mismatch) { - throw invalid("Candidate target differs from its complete lease binding", mismatch); - } - } - - private static BigInteger bindingGeneration(AccountGameplayAdmissionLeaseEvidence lease) { - Object scope = lease.carrier().get("bindingScope"); - if (!(scope instanceof java.util.Map map) - || !(map.get("bindingGeneration") instanceof String generation)) { - throw invalid("Lease has no binding generation"); - } - return positiveDecimal(generation, "bindingGeneration"); - } - - static CanonicalGameplayOriginalNewCandidate.ReservationSource reservationSource( - CanonicalIssuerPartitionReservation reservation) { - return new CanonicalGameplayOriginalNewCandidate.ReservationSource( - reservation.reservationId(), - reservation.owner().bindingRef(), - reservation.bindingGeneration(), - reservation.transitionId(), - reservation.partitionId(), - reservation.reservationFence(), - reservation.issuerCoverageOperationId(), - reservation.issuerCoverageOperationFence(), - reservation.coverageFence(), - reservation.inventorySnapshotRevision()); - } - - private static ObjectNode bindingNode(CanonicalGameplayBindingIdentity binding) { - ObjectNode node = JSON.createObjectNode(); - node.put("accountId", binding.accountId().toString()); - node.put("tenantId", binding.tenantId().toString()); - node.put("playableStateNamespaceId", binding.playableStateNamespaceId().toString()); - node.put("characterId", binding.characterId().toString()); - node.put("playableStateScope", binding.playableStateScope()); - node.put("gameInstanceId", binding.gameInstanceId().toString()); - node.put("runtimeGameInstanceId", Long.toString(binding.runtimeGameInstanceId())); - node.put("sessionId", binding.sessionId()); - node.put("regionId", binding.regionId().toString()); - node.put("regionEpoch", binding.regionEpoch().toString()); - node.put("issuerId", binding.issuerId()); - node.put("issuerAuthGeneration", binding.issuerAuthGeneration().toString()); - node.put("issuerIndexLayoutVersion", binding.issuerIndexLayoutVersion().toString()); - node.put("issuerIndexPartitionCount", binding.issuerIndexPartitionCount().toString()); - node.put("issuerIndexPartitionCapacity", binding.issuerIndexPartitionCapacity().toString()); - return node; - } - - private static ObjectNode targetNode(CanonicalPlayableTarget target) { - ObjectNode node = JSON.createObjectNode(); - node.put("targetNamespace", target.targetNamespace()); - node.put("tenantSlug", target.tenantSlug()); - node.put("canonicalTenantId", target.canonicalTenantId().toString()); - node.put("worldSlug", target.worldSlug()); - node.put("worldDisplayName", target.worldDisplayName()); - node.put("realmId", target.realmId().toString()); - node.put("realmSlug", target.realmSlug()); - node.put("realmDisplayName", target.realmDisplayName()); - node.put("gameSessionTenantId", Long.toString(target.gameSessionTenantId())); - node.put("gameInstanceId", Long.toString(target.gameInstanceId())); - node.put("playableStateNamespaceId", target.playableStateNamespaceId().toString()); - node.put("playableStateScope", target.playableStateScope()); - node.put("canonicalGameInstanceId", target.canonicalGameInstanceId().toString()); - node.put("canonicalVersionId", target.canonicalVersionId().toString()); - node.put("runtimeVersionId", Long.toString(target.runtimeVersionId())); - node.put("catalogRevision", Long.toString(target.catalogRevision())); - node.put("pointerVersion", Long.toString(target.pointerVersion())); - node.put("admissionPointerSnapshotDigest", target.admissionPointerSnapshotDigest()); - node.put("activeWorldEpoch", Long.toString(target.activeWorldEpoch())); - node.put("initialAdmissionRequestId", target.initialAdmissionRequestId()); - node.put("initialAdmissionRequestDigest", target.initialAdmissionRequestDigest()); - node.put("initialAdmissionOriginKind", target.initialAdmissionOriginKind().name()); - if (target.expectedPriorPointerVersion() != null) { - node.put("expectedPriorPointerVersion", Long.toString(target.expectedPriorPointerVersion())); - } - node.put("holdId", target.holdId().toString()); - node.put("holdFence", target.holdFence().toString()); - node.put("holdBindingDigest", target.holdBindingDigest()); - node.put("auditEventId", Long.toString(target.auditEventId())); - node.put("ownerProofDigest", target.ownerProofDigest()); - node.put("ownerProofOutcome", target.ownerProofOutcome().name()); - node.put("positiveDurableAbort", target.positiveDurableAbort()); - node.put("ownerProofTerminalAt", target.ownerProofTerminalAt().toString()); - node.put("characterCreationPolicy", target.characterCreationPolicy()); - return node; - } - - private static ObjectNode transitionNode( - CanonicalGameplayOriginalNewCandidate.TransitionSource transition) { - ObjectNode node = JSON.createObjectNode(); - node.put("transitionId", transition.transitionId().toString()); - node.put("bindingRef", base64(transition.bindingRef().bytes())); - node.put("bindingGeneration", transition.bindingGeneration().toString()); - node.put("issuerReservationId", transition.issuerReservationId().toString()); - node.put("reservationFence", transition.reservationFence().toString()); - node.put("candidateAccountIndexFence", transition.candidateAccountIndexFence().toString()); - return node; - } - - private static ObjectNode reservationNode( - CanonicalGameplayOriginalNewCandidate.ReservationSource reservation) { - ObjectNode node = JSON.createObjectNode(); - node.put("reservationId", reservation.reservationId().toString()); - node.put("ownerBindingRef", base64(reservation.ownerBindingRef().bytes())); - node.put("bindingGeneration", reservation.bindingGeneration().toString()); - node.put("transitionId", reservation.transitionId().toString()); - node.put("partitionId", reservation.partitionId().toString()); - node.put("lifecycle", CanonicalIssuerPartitionReservation.Lifecycle.RESERVED.name()); - node.put("reservationFence", reservation.reservationFence().toString()); - node.put("issuerCoverageOperationId", reservation.issuerCoverageOperationId().toString()); - node.put("issuerCoverageOperationFence", reservation.issuerCoverageOperationFence().toString()); - node.put("coverageFence", reservation.coverageFence().toString()); - node.put("inventorySnapshotRevision", reservation.inventorySnapshotRevision().toString()); - return node; - } - - private static JsonNode parseCanonicalLeaseNode(AccountGameplayAdmissionLeaseEvidence evidence) - throws IOException { - return JSON.readTree(evidence.canonicalJson()); - } - - private static AccountGameplayAdmissionLeaseEvidence parseLeaseEvidence(JsonNode node) - throws IOException { - ObjectNode object = requireObject(node, "leaseEvidence"); - byte[] canonical = Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(object)); - if (canonical.length > AccountGameplayAdmissionLeaseEvidence.MAX_EVIDENCE_BYTES) { - throw invalid("Complete Account lease evidence exceeds its local bound"); - } - return AccountGameplayAdmissionLeaseEvidence.parseCanonical( - new String(canonical, StandardCharsets.UTF_8)); - } - - private static CanonicalGameplayBindingIdentity parseBinding(JsonNode source) throws IOException { - ObjectNode node = requireObject(source, "binding"); - requireFields(node, BINDING_FIELDS, "binding"); - return new CanonicalGameplayBindingIdentity( - uuid(node, "accountId"), - uuid(node, "tenantId"), - uuid(node, "playableStateNamespaceId"), - uuid(node, "characterId"), - text(node, "playableStateScope"), - uuid(node, "gameInstanceId"), - positiveLong(node, "runtimeGameInstanceId"), - text(node, "sessionId"), - uuid(node, "regionId"), - positive(node, "regionEpoch"), - text(node, "issuerId"), - positive(node, "issuerAuthGeneration"), - positive(node, "issuerIndexLayoutVersion"), - positive(node, "issuerIndexPartitionCount"), - positive(node, "issuerIndexPartitionCapacity")); - } - - private static CanonicalPlayableTarget parseTarget(JsonNode source) throws IOException { - ObjectNode node = requireObject(source, "target"); - CanonicalInitialAdmissionRequest.OriginKind originKind = - enumValue( - CanonicalInitialAdmissionRequest.OriginKind.class, - text(node, "initialAdmissionOriginKind"), - "initialAdmissionOriginKind"); - Set expectedFields = new HashSet<>(TARGET_FIELDS); - if (originKind == CanonicalInitialAdmissionRequest.OriginKind.EXPECT_CLOSED) { - expectedFields.add("expectedPriorPointerVersion"); - } - requireFields(node, expectedFields, "target"); - Long expectedPriorPointerVersion = - originKind == CanonicalInitialAdmissionRequest.OriginKind.NO_PRIOR_POINTER - ? null - : positiveLong(node, "expectedPriorPointerVersion"); - return new CanonicalPlayableTarget( - text(node, "targetNamespace"), - text(node, "tenantSlug"), - uuid(node, "canonicalTenantId"), - text(node, "worldSlug"), - text(node, "worldDisplayName"), - uuid(node, "realmId"), - text(node, "realmSlug"), - text(node, "realmDisplayName"), - positiveLong(node, "gameSessionTenantId"), - positiveLong(node, "gameInstanceId"), - uuid(node, "playableStateNamespaceId"), - text(node, "playableStateScope"), - uuid(node, "canonicalGameInstanceId"), - uuid(node, "canonicalVersionId"), - positiveLong(node, "runtimeVersionId"), - positiveLong(node, "catalogRevision"), - positiveLong(node, "pointerVersion"), - text(node, "admissionPointerSnapshotDigest"), - positiveLong(node, "activeWorldEpoch"), - text(node, "initialAdmissionRequestId"), - text(node, "initialAdmissionRequestDigest"), - originKind, - expectedPriorPointerVersion, - uuid(node, "holdId"), - uuid(node, "holdFence"), - text(node, "holdBindingDigest"), - positiveLong(node, "auditEventId"), - text(node, "ownerProofDigest"), - enumValue( - CanonicalInitialAdmissionOwnerProof.Outcome.class, - text(node, "ownerProofOutcome"), - "ownerProofOutcome"), - bool(node, "positiveDurableAbort"), - instant(node, "ownerProofTerminalAt"), - text(node, "characterCreationPolicy")); - } - - private static CanonicalGameplayOriginalNewCandidate.TransitionSource parseTransition( - JsonNode source) throws IOException { - ObjectNode node = requireObject(source, "transition"); - requireFields(node, TRANSITION_FIELDS, "transition"); - return new CanonicalGameplayOriginalNewCandidate.TransitionSource( - uuid(node, "transitionId"), - CanonicalGameplayBindingRef.fromExactBytes(base64(node, "bindingRef")), - positive(node, "bindingGeneration"), - uuid(node, "issuerReservationId"), - uuid(node, "reservationFence"), - uuid(node, "candidateAccountIndexFence")); - } - - private static CanonicalGameplayOriginalNewCandidate.ReservationSource parseReservation( - JsonNode source) throws IOException { - ObjectNode node = requireObject(source, "reservation"); - requireFields(node, RESERVATION_FIELDS, "reservation"); - if (!text(node, "lifecycle") - .equals(CanonicalIssuerPartitionReservation.Lifecycle.RESERVED.name())) { - throw invalid("Original NEW candidate reservation must remain RESERVED"); - } - return new CanonicalGameplayOriginalNewCandidate.ReservationSource( - uuid(node, "reservationId"), - CanonicalGameplayBindingRef.fromExactBytes(base64(node, "ownerBindingRef")), - positive(node, "bindingGeneration"), - uuid(node, "transitionId"), - nonNegative(node, "partitionId"), - uuid(node, "reservationFence"), - uuid(node, "issuerCoverageOperationId"), - positive(node, "issuerCoverageOperationFence"), - positive(node, "coverageFence"), - positive(node, "inventorySnapshotRevision")); - } - - private static ObjectNode requireObject(JsonNode node, String name) { - if (!(node instanceof ObjectNode object)) throw invalid(name + " must be an object"); - return object; - } - - private static void requireFields(ObjectNode node, Set expected, String name) { - Set fields = new HashSet<>(); - node.fieldNames().forEachRemaining(fields::add); - if (!fields.equals(expected)) throw invalid(name + " has missing or unknown fields"); - } - - private static String text(JsonNode node, String field) { - JsonNode value = node.get(field); - if (value == null || !value.isTextual() || value.textValue().isEmpty()) { - throw invalid(field + " must be non-empty text"); - } - return value.textValue(); - } - - private static boolean bool(JsonNode node, String field) { - JsonNode value = node.get(field); - if (value == null || !value.isBoolean()) throw invalid(field + " must be a JSON boolean"); - return value.booleanValue(); - } - - private static UUID uuid(JsonNode node, String field) { - String text = text(node, field); - try { - UUID value = UUID.fromString(text); - if (!value.toString().equals(text) || value.equals(new UUID(0L, 0L))) { - throw invalid(field + " must be a canonical non-nil UUID"); - } - return value; - } catch (IllegalArgumentException malformed) { - throw invalid(field + " must be a canonical non-nil UUID", malformed); - } - } - - private static BigInteger positive(JsonNode node, String field) { - return positiveDecimal(text(node, field), field); - } - - private static BigInteger nonNegative(JsonNode node, String field) { - String value = text(node, field); - if (!NON_NEGATIVE_DECIMAL.matcher(value).matches()) { - throw invalid(field + " must be a bounded canonical non-negative decimal string"); - } - return new BigInteger(value); - } - - private static BigInteger positiveDecimal(String value, String field) { - if (!POSITIVE_DECIMAL.matcher(value).matches()) { - throw invalid(field + " must be a bounded canonical positive decimal string"); - } - return new BigInteger(value); - } - - private static long positiveLong(JsonNode node, String field) { - String value = text(node, field); - if (!POSITIVE_DECIMAL.matcher(value).matches()) { - throw invalid(field + " must be a positive decimal string within the long range"); - } - try { - return Long.parseLong(value); - } catch (NumberFormatException malformed) { - throw invalid(field + " exceeds the supported long range", malformed); - } - } - - private static Instant instant(JsonNode node, String field) { - String value = text(node, field); - try { - Instant parsed = Instant.parse(value); - if (!parsed.toString().equals(value)) throw invalid(field + " is not canonical UTC time"); - return parsed; - } catch (RuntimeException malformed) { - throw invalid(field + " is not canonical UTC time", malformed); - } - } - - private static > E enumValue(Class enumType, String value, String field) { - try { - return Enum.valueOf(enumType, value); - } catch (IllegalArgumentException malformed) { - throw invalid(field + " is unsupported", malformed); - } - } - - private static byte[] base64(JsonNode node, String field) { - String value = text(node, field); - try { - byte[] decoded = Base64.getDecoder().decode(value); - if (!base64(decoded).equals(value)) throw invalid(field + " is not canonical padded Base64"); - return decoded; - } catch (IllegalArgumentException malformed) { - throw invalid(field + " is not canonical padded Base64", malformed); - } - } - - private static String base64(byte[] bytes) { - return Base64.getEncoder().encodeToString(bytes); - } - - private static void requireCounterLimit(BigInteger value, String name, boolean zeroAllowed) { - Objects.requireNonNull(value, name); - int digits = value.toString().length(); - if (digits > MAX_COUNTER_DIGITS - || value.signum() < 0 - || (!zeroAllowed && value.signum() == 0)) { - throw invalid(name + " exceeds its canonical integer bounds"); - } - } - - private static String decodeUtf8(byte[] encoded) { - try { - return StandardCharsets.UTF_8 - .newDecoder() - .onMalformedInput(CodingErrorAction.REPORT) - .onUnmappableCharacter(CodingErrorAction.REPORT) - .decode(ByteBuffer.wrap(encoded)) - .toString(); - } catch (CharacterCodingException malformed) { - throw invalid("Original NEW candidate is not valid UTF-8", malformed); - } - } - - private static IllegalArgumentException invalid(String message) { - return new IllegalArgumentException(message); - } - - private static IllegalArgumentException invalid(String message, Throwable cause) { - return new IllegalArgumentException(message, cause); - } -} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCandidateRedisOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCandidateRedisOwner.java deleted file mode 100644 index a618773a8b..0000000000 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCandidateRedisOwner.java +++ /dev/null @@ -1,547 +0,0 @@ -package net.firedevops.firemud.gamesession.repository; - -import io.lettuce.core.RedisClient; -import io.lettuce.core.RedisFuture; -import io.lettuce.core.ScriptOutputType; -import io.lettuce.core.api.StatefulRedisConnection; -import io.lettuce.core.api.async.RedisAsyncCommands; -import io.lettuce.core.codec.ByteArrayCodec; -import java.io.ByteArrayOutputStream; -import java.io.DataOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.nio.charset.StandardCharsets; -import java.security.MessageDigest; -import java.util.Arrays; -import java.util.HexFormat; -import java.util.List; -import java.util.Objects; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; -import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; -import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor; -import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingIdentity; -import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingProvisionalCasEvidence; -import net.firedevops.firemud.gamesession.service.CanonicalGameplayOriginalNewCandidateRedisScriptContribution; -import org.springframework.transaction.support.TransactionSynchronizationManager; - -/** - * Manual, unregistered owner for one original public-production NEW candidate installation. The - * result and physical readback remain explicitly non-admitting. - */ -public final class CanonicalGameplayOriginalNewCandidateRedisOwner { - private static final String PRINCIPAL = "gamesession_coord_app"; - private static final int MAX_SCRIPT_BYTES = 32 * 1024; - private static final int MAX_CANDIDATE_BYTES = 512 * 1024; - private static final long COMMAND_TIMEOUT_MILLIS = 5_000; - private static final List EXPECTED_KEYS = - List.of( - new RedisScriptDescriptor.KeySpec( - "session", "session:game:", RedisScriptDescriptor.HashTagDeclaration.REQUIRED), - new RedisScriptDescriptor.KeySpec( - "characterIndex", - "session:game:index:character:", - RedisScriptDescriptor.HashTagDeclaration.REQUIRED), - new RedisScriptDescriptor.KeySpec( - "accountTenantIndex", - "session:game:index:account-tenant:", - RedisScriptDescriptor.HashTagDeclaration.REQUIRED), - new RedisScriptDescriptor.KeySpec( - "tenantIndex", - "session:game:index:tenant:", - RedisScriptDescriptor.HashTagDeclaration.REQUIRED)); - private static final List EXPECTED_ARGUMENTS = - List.of( - new RedisScriptDescriptor.ArgumentSpec("purpose"), - new RedisScriptDescriptor.ArgumentSpec("tenantId"), - new RedisScriptDescriptor.ArgumentSpec("accountId"), - new RedisScriptDescriptor.ArgumentSpec("playableStateNamespaceId"), - new RedisScriptDescriptor.ArgumentSpec("characterId"), - new RedisScriptDescriptor.ArgumentSpec("gameInstanceId"), - new RedisScriptDescriptor.ArgumentSpec("sessionId"), - new RedisScriptDescriptor.ArgumentSpec("bindingGeneration"), - new RedisScriptDescriptor.ArgumentSpec("tenantGameplayTag"), - new RedisScriptDescriptor.ArgumentSpec("candidateBytes")); - private static final List EXPECTED_OUTCOMES = - List.of( - outcome( - "CANDIDATE_CREATED", - RedisScriptDescriptor.OutcomeCategory.SUCCESS, - RedisScriptDescriptor.MutationEffect.MUTATING), - outcome( - "EXISTING_STATE_REFUSED", - RedisScriptDescriptor.OutcomeCategory.STALE, - RedisScriptDescriptor.MutationEffect.NON_MUTATING), - outcome( - "INVALID_ARGUMENTS", - RedisScriptDescriptor.OutcomeCategory.VALIDATION_FAILURE, - RedisScriptDescriptor.MutationEffect.NON_MUTATING)); - - private final RedisClient redisClient; - private final RedisScriptCatalog catalog; - private final CanonicalGameplayBindingInventoryRepository inventory; - private final CanonicalGameplayTenantGameplayTagRepository tenantTags; - - CanonicalGameplayOriginalNewCandidateRedisOwner( - RedisClient redisClient, - RedisScriptCatalog catalog, - CanonicalGameplayBindingInventoryRepository inventory, - CanonicalGameplayTenantGameplayTagRepository tenantTags) { - this.redisClient = Objects.requireNonNull(redisClient, "Configured Redis client required"); - this.catalog = Objects.requireNonNull(catalog, "Manual Redis script catalog required"); - this.inventory = Objects.requireNonNull(inventory, "Binding inventory repository required"); - this.tenantTags = Objects.requireNonNull(tenantTags, "Persisted tenant-tag owner required"); - } - - /** - * Uses the one SQL-issued create permission or performs only current physical readback. Exact - * readback is then accepted through the existing source/Account/runtime-guarded provisional CAS. - */ - public Installation installOnce( - net.firedevops.firemud.gamesession.binding.CanonicalGameplayAdmissionDecision - originalDecision) { - Objects.requireNonNull(originalDecision, "original Account decision"); - requireNoAmbientTransaction(); - CanonicalGameplayBindingInventoryRepository.OriginalNewCandidateInstallationClaim claim = - inventory.claimOriginalNewCandidateInstallation(originalDecision); - return installClaimOnce(claim); - } - - /** Package seam for the actual SQL-issued single-use claim; no caller can construct a claim. */ - Installation installClaimOnce( - CanonicalGameplayBindingInventoryRepository.OriginalNewCandidateInstallationClaim claim) { - Objects.requireNonNull(claim, "SQL-issued original NEW claim"); - requireNoAmbientTransaction(); - var originalDecision = claim.originalDecision(); - CanonicalGameplayOriginalNewCandidate candidate = claim.candidate(); - CanonicalGameplayTenantGameplayTagRepository.Assignment assignment; - try { - requireNoAmbientTransaction(); - assignment = tenantTags.assignmentForTransition(claim.evidence().transition().transitionId()); - requireAssignment(assignment, candidate); - } catch (RuntimeException unavailable) { - throw unavailable(); - } - Keys keys = keys(assignment, candidate); - - if (claim.consumeCreatePermission()) { - CreateAttempt attempt = createOnce(claim, assignment, keys); - if (attempt == CreateAttempt.REFUSED) throw unavailable(); - // A lost reply remains uncertain until this separate exact physical read succeeds. - } - - PhysicalReadback readback = readExact(candidate, assignment, keys); - CanonicalGameplayBindingInventoryRepository.OriginalNewCandidateInstallationClaim freshClaim = - inventory.claimOriginalNewCandidateInstallation(originalDecision); - if (!freshClaim.candidate().equals(candidate)) throw unavailable(); - var provisional = inventory.markOriginalNewCandidateProvisional(freshClaim, readback); - if (provisional.status() - != net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingTransitionSnapshot - .Status.PROVISIONAL - || !provisional.transitionId().equals(candidate.transition().transitionId())) { - throw unavailable(); - } - return new Installation(candidate, assignment, keys, readback, provisional); - } - - private CreateAttempt createOnce( - CanonicalGameplayBindingInventoryRepository.OriginalNewCandidateInstallationClaim claim, - CanonicalGameplayTenantGameplayTagRepository.Assignment assignment, - Keys keys) { - requireNoAmbientTransaction(); - RedisScriptDescriptor descriptor = requireDescriptor(); - byte[] script = scriptSource(descriptor); - byte[] candidateBytes = claim.candidate().canonicalBytes(); - if (candidateBytes.length == 0 || candidateBytes.length > MAX_CANDIDATE_BYTES) { - throw unavailable(); - } - try (StatefulRedisConnection connection = - redisClient.connect(ByteArrayCodec.INSTANCE)) { - RedisAsyncCommands commands = requireCommands(connection); - requirePrincipal(await(commands.aclWhoami())); - String loadedSha = await(commands.scriptLoad(script)); - if (!digest("SHA-1", script).equals(loadedSha)) throw unavailable(); - Long result = - await( - commands.evalsha( - loadedSha, - ScriptOutputType.INTEGER, - keyBytes(keys), - ascii(CanonicalGameplayOriginalNewCandidate.PURPOSE), - ascii(assignment.tenantId().toString()), - ascii(assignment.accountId().toString()), - ascii(assignment.playableStateNamespaceId().toString()), - ascii(assignment.characterId().toString()), - ascii(assignment.gameInstanceId().toString()), - ascii(assignment.sessionId()), - ascii(claim.candidate().transition().bindingGeneration().toString()), - ascii(assignment.tenantGameplayTag()), - candidateBytes)); - return Long.valueOf(1L).equals(result) ? CreateAttempt.CREATED : CreateAttempt.REFUSED; - } catch (RuntimeException possibleLostReply) { - // DISPATCH_POSSIBLE is already durable. The caller will only attempt an exact read. - return CreateAttempt.REPLY_UNCERTAIN; - } - } - - private PhysicalReadback readExact( - CanonicalGameplayOriginalNewCandidate candidate, - CanonicalGameplayTenantGameplayTagRepository.Assignment assignment, - Keys keys) { - requireNoAmbientTransaction(); - byte[] candidateBytes = candidate.canonicalBytes(); - byte[] characterBytes = characterProjection(candidate); - byte[] sessionKey = ascii(keys.session()); - byte[] characterKey = ascii(keys.characterIndex()); - byte[] accountTenantKey = ascii(keys.accountTenantIndex()); - byte[] tenantKey = ascii(keys.tenantIndex()); - byte[] sessionMember = ascii(candidate.bindingIdentity().sessionId()); - try (StatefulRedisConnection connection = - redisClient.connect(ByteArrayCodec.INSTANCE)) { - RedisAsyncCommands commands = requireCommands(connection); - requirePrincipal(await(commands.aclWhoami())); - if (!"string".equals(await(commands.type(sessionKey))) - || !Long.valueOf(-1L).equals(await(commands.pttl(sessionKey))) - || !Arrays.equals(candidateBytes, await(commands.get(sessionKey))) - || !"string".equals(await(commands.type(characterKey))) - || !Long.valueOf(-1L).equals(await(commands.pttl(characterKey))) - || !Arrays.equals(characterBytes, await(commands.get(characterKey))) - || !persistentMember(commands, accountTenantKey, sessionMember) - || !persistentMember(commands, tenantKey, sessionMember)) { - throw unavailable(); - } - } catch (RuntimeException unavailable) { - throw unavailable(); - } - return new PhysicalReadback(candidate, assignment, keys, candidateBytes, characterBytes); - } - - private static boolean persistentMember( - RedisAsyncCommands commands, byte[] key, byte[] member) { - String type = await(commands.type(key)); - Long ttl = await(commands.pttl(key)); - return "set".equals(type) - && Long.valueOf(-1L).equals(ttl) - && Boolean.TRUE.equals(await(commands.sismember(key, member))); - } - - private RedisScriptDescriptor requireDescriptor() { - try { - RedisScriptDescriptor descriptor = - catalog.require(CanonicalGameplayOriginalNewCandidateRedisScriptContribution.SCRIPT_ID); - if (!CanonicalGameplayOriginalNewCandidateRedisScriptContribution.SCRIPT_ID.equals( - descriptor.scriptId()) - || !CanonicalGameplayOriginalNewCandidateRedisScriptContribution.RESOURCE_PATH.equals( - descriptor.resourcePath()) - || !"game-session-service".equals(descriptor.owner()) - || !PRINCIPAL.equals(descriptor.principal()) - || descriptor.role() != RedisScriptDescriptor.RedisRole.COORDINATION - || !EXPECTED_KEYS.equals(descriptor.keys()) - || !EXPECTED_ARGUMENTS.equals(descriptor.arguments()) - || descriptor.category() != RedisScriptDescriptor.ScriptCategory.SESSION_CAS - || !EXPECTED_OUTCOMES.equals(descriptor.outcomes()) - || descriptor.resetSensitivity() != RedisScriptDescriptor.ResetSensitivity.CLUSTER - || descriptor.lossClass() - != RedisScriptDescriptor.LossClass.EMPTY_REDIS_COLD_START_OR_RESET - || descriptor.compatibilityLevel() - != RedisScriptDescriptor.CompatibilityLevel.REQUIRES_CLUSTER_RESET) { - throw unavailable(); - } - return descriptor; - } catch (RuntimeException failure) { - throw unavailable(); - } - } - - private byte[] scriptSource(RedisScriptDescriptor descriptor) { - try (InputStream input = - getClass().getClassLoader().getResourceAsStream(descriptor.resourcePath())) { - if (input == null) throw unavailable(); - byte[] bytes = input.readNBytes(MAX_SCRIPT_BYTES + 1); - if (bytes.length == 0 - || bytes.length > MAX_SCRIPT_BYTES - || !digest("SHA-256", bytes).equals(descriptor.sha256())) { - throw unavailable(); - } - return bytes; - } catch (IOException | RuntimeException failure) { - throw unavailable(); - } - } - - private static Keys keys( - CanonicalGameplayTenantGameplayTagRepository.Assignment assignment, - CanonicalGameplayOriginalNewCandidate candidate) { - var binding = candidate.bindingIdentity().bindingRef(); - return new Keys( - CanonicalGameplaySessionRedisKeys.session(assignment, binding), - CanonicalGameplaySessionRedisKeys.characterIndex(assignment, binding), - CanonicalGameplaySessionRedisKeys.accountTenantIndex(assignment, binding), - CanonicalGameplaySessionRedisKeys.tenantIndex(assignment, binding)); - } - - private static byte[] characterProjection(CanonicalGameplayOriginalNewCandidate candidate) { - var binding = candidate.bindingIdentity(); - return ("{\"sessionId\":\"" - + binding.sessionId() - + "\",\"gameInstanceId\":\"" - + binding.gameInstanceId() - + "\",\"bindingGeneration\":\"" - + candidate.transition().bindingGeneration() - + "\"}") - .getBytes(StandardCharsets.US_ASCII); - } - - private static void requireAssignment( - CanonicalGameplayTenantGameplayTagRepository.Assignment assignment, - CanonicalGameplayOriginalNewCandidate candidate) { - CanonicalGameplayBindingIdentity binding = candidate.bindingIdentity(); - if (!assignment.isBindingTransition() - || !candidate.transition().transitionId().equals(assignment.transitionId()) - || !binding.tenantId().equals(assignment.tenantId()) - || !binding.accountId().equals(assignment.accountId()) - || !binding.playableStateNamespaceId().equals(assignment.playableStateNamespaceId()) - || !binding.characterId().equals(assignment.characterId()) - || !binding.gameInstanceId().equals(assignment.gameInstanceId()) - || !binding.sessionId().equals(assignment.sessionId())) { - throw unavailable(); - } - CanonicalGameplayTenantGameplayTagRepository.requireCanonicalTag( - assignment.tenantGameplayTag()); - } - - private static byte[][] keyBytes(Keys keys) { - return new byte[][] { - ascii(keys.session()), - ascii(keys.characterIndex()), - ascii(keys.accountTenantIndex()), - ascii(keys.tenantIndex()) - }; - } - - private static RedisAsyncCommands requireCommands( - StatefulRedisConnection connection) { - RedisAsyncCommands commands = connection.async(); - if (commands == null) throw unavailable(); - return commands; - } - - private static T await(RedisFuture future) { - try { - T result = future.get(COMMAND_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS); - if (result == null) throw unavailable(); - return result; - } catch (InterruptedException interrupted) { - Thread.currentThread().interrupt(); - throw unavailable(); - } catch (ExecutionException | TimeoutException failure) { - throw unavailable(); - } - } - - private static void requirePrincipal(String principal) { - if (!PRINCIPAL.equals(principal)) throw unavailable(); - } - - private static void requireNoAmbientTransaction() { - if (TransactionSynchronizationManager.isActualTransactionActive() - || TransactionSynchronizationManager.isSynchronizationActive()) { - throw new IllegalStateException( - "Original NEW Redis work cannot run inside an ambient SQL transaction or synchronization"); - } - } - - private static byte[] ascii(String value) { - return value.getBytes(StandardCharsets.US_ASCII); - } - - private static String digest(String algorithm, byte[] bytes) { - try { - return HexFormat.of().formatHex(MessageDigest.getInstance(algorithm).digest(bytes)); - } catch (java.security.NoSuchAlgorithmException impossible) { - throw new IllegalStateException("JVM digest algorithm is unavailable", impossible); - } - } - - private static RedisScriptDescriptor.OutcomeSpec outcome( - String code, - RedisScriptDescriptor.OutcomeCategory category, - RedisScriptDescriptor.MutationEffect effect) { - return new RedisScriptDescriptor.OutcomeSpec(code, category, effect); - } - - private static IllegalStateException unavailable() { - return new IllegalStateException("Original NEW candidate install/readback is unavailable"); - } - - private enum CreateAttempt { - CREATED, - REPLY_UNCERTAIN, - REFUSED - } - - private record Keys( - String session, String characterIndex, String accountTenantIndex, String tenantIndex) {} - - /** Private-constructor physical proof from a separate exact read of all four scoped keys. */ - public static final class PhysicalReadback { - private final String transitionId; - private final CanonicalGameplayOriginalNewCandidate candidate; - private final CanonicalGameplayTenantGameplayTagRepository.Assignment assignment; - private final Keys keys; - private final byte[] candidateBytes; - private final byte[] characterBytes; - private final String digest; - - private PhysicalReadback( - CanonicalGameplayOriginalNewCandidate candidate, - CanonicalGameplayTenantGameplayTagRepository.Assignment assignment, - Keys keys, - byte[] candidateBytes, - byte[] characterBytes) { - this.transitionId = candidate.transition().transitionId().toString(); - this.candidate = candidate; - this.assignment = assignment; - this.keys = keys; - this.candidateBytes = candidateBytes.clone(); - this.characterBytes = characterBytes.clone(); - this.digest = - exactReadbackDigest( - keys, candidateBytes, characterBytes, candidate.bindingIdentity().sessionId()); - } - - String digest() { - return digest; - } - - boolean matches( - CanonicalGameplayOriginalNewCandidate expected, - CanonicalGameplayBindingProvisionalCasEvidence evidence) { - try { - requireAssignment(assignment, expected); - Keys expectedKeys = keys(assignment, expected); - return candidate.equals(expected) - && transitionId.equals(evidence.transition().transitionId().toString()) - && expected.transition().transitionId().equals(evidence.transition().transitionId()) - && expected.matchesProvisionalSources(evidence) - && keys.equals(expectedKeys) - && Arrays.equals(candidateBytes, expected.canonicalBytes()) - && Arrays.equals(characterBytes, characterProjection(expected)) - && digest.equals( - exactReadbackDigest( - keys, candidateBytes, characterBytes, expected.bindingIdentity().sessionId())); - } catch (RuntimeException invalidSource) { - return false; - } - } - - @Override - public String toString() { - return "PhysicalReadback[transitionId=" + transitionId + ", nonAdmitting=true]"; - } - } - - /** - * Owner result handed to Main for later exact candidate comparison and final-CAS preimage use. - */ - public static final class Installation { - private final CanonicalGameplayOriginalNewCandidate candidate; - private final CanonicalGameplayTenantGameplayTagRepository.Assignment assignment; - private final Keys keys; - private final PhysicalReadback physicalReadback; - private final net.firedevops.firemud.gamesession.binding - .CanonicalGameplayBindingTransitionSnapshot - provisional; - - private Installation( - CanonicalGameplayOriginalNewCandidate candidate, - CanonicalGameplayTenantGameplayTagRepository.Assignment assignment, - Keys keys, - PhysicalReadback physicalReadback, - net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingTransitionSnapshot - provisional) { - this.candidate = candidate; - this.assignment = assignment; - this.keys = keys; - this.physicalReadback = physicalReadback; - this.provisional = provisional; - } - - public CanonicalGameplayOriginalNewCandidate candidate() { - return candidate; - } - - public byte[] exactCandidateBytes() { - return candidate.canonicalBytes(); - } - - public String sessionKey() { - return keys.session(); - } - - public String characterIndexKey() { - return keys.characterIndex(); - } - - public String accountTenantIndexKey() { - return keys.accountTenantIndex(); - } - - public String tenantIndexKey() { - return keys.tenantIndex(); - } - - public CanonicalGameplayTenantGameplayTagRepository.Assignment assignment() { - return assignment; - } - - public PhysicalReadback physicalReadback() { - return physicalReadback; - } - - public net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingTransitionSnapshot - provisionalTransition() { - return provisional; - } - - public boolean isNonAdmittingCandidate() { - return true; - } - - @Override - public String toString() { - return "Installation[transitionId=" - + candidate.transition().transitionId() - + ", purpose=" - + CanonicalGameplayOriginalNewCandidate.PURPOSE - + ", nonAdmitting=true]"; - } - } - - private static String exactReadbackDigest( - Keys keys, byte[] candidateBytes, byte[] characterBytes, String sessionId) { - try { - ByteArrayOutputStream buffer = new ByteArrayOutputStream(); - try (DataOutputStream output = new DataOutputStream(buffer)) { - output.write("original-new-candidate-readback/v1".getBytes(StandardCharsets.US_ASCII)); - writeFrame(output, keys.session().getBytes(StandardCharsets.US_ASCII)); - writeFrame(output, candidateBytes); - writeFrame(output, keys.characterIndex().getBytes(StandardCharsets.US_ASCII)); - writeFrame(output, characterBytes); - writeFrame(output, keys.accountTenantIndex().getBytes(StandardCharsets.US_ASCII)); - writeFrame(output, sessionId.getBytes(StandardCharsets.US_ASCII)); - writeFrame(output, keys.tenantIndex().getBytes(StandardCharsets.US_ASCII)); - writeFrame(output, sessionId.getBytes(StandardCharsets.US_ASCII)); - } - return "sha256:" + digest("SHA-256", buffer.toByteArray()); - } catch (IOException impossible) { - throw new IllegalStateException("Cannot encode exact physical readback", impossible); - } - } - - private static void writeFrame(DataOutputStream output, byte[] bytes) throws IOException { - output.writeInt(bytes.length); - output.write(bytes); - } -} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCandidateRedisOwnerFactory.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCandidateRedisOwnerFactory.java deleted file mode 100644 index 1b446680f8..0000000000 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCandidateRedisOwnerFactory.java +++ /dev/null @@ -1,22 +0,0 @@ -package net.firedevops.firemud.gamesession.repository; - -import io.lettuce.core.RedisClient; -import java.util.Objects; -import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; - -/** Explicit manual construction for the unregistered original NEW candidate Redis owner. */ -public final class CanonicalGameplayOriginalNewCandidateRedisOwnerFactory { - private CanonicalGameplayOriginalNewCandidateRedisOwnerFactory() {} - - public static CanonicalGameplayOriginalNewCandidateRedisOwner create( - RedisClient redisClient, - RedisScriptCatalog scriptCatalog, - CanonicalGameplayBindingInventoryRepository inventoryRepository, - CanonicalGameplayTenantGameplayTagRepository tenantGameplayTags) { - return new CanonicalGameplayOriginalNewCandidateRedisOwner( - Objects.requireNonNull(redisClient, "redisClient"), - Objects.requireNonNull(scriptCatalog, "scriptCatalog"), - Objects.requireNonNull(inventoryRepository, "inventoryRepository"), - Objects.requireNonNull(tenantGameplayTags, "tenantGameplayTags")); - } -} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayOriginalNewCandidateRedisScriptContribution.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayOriginalNewCandidateRedisScriptContribution.java deleted file mode 100644 index ffe959cb4d..0000000000 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayOriginalNewCandidateRedisScriptContribution.java +++ /dev/null @@ -1,52 +0,0 @@ -package net.firedevops.firemud.gamesession.service; - -import java.io.IOException; -import java.io.InputStream; -import java.util.Collection; -import java.util.List; -import net.firedevops.firemud.common.redis.contracts.RedisScriptContribution; -import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor; -import tools.jackson.core.StreamReadFeature; -import tools.jackson.databind.DeserializationFeature; -import tools.jackson.databind.json.JsonMapper; - -/** Passive descriptor for the manual first-install-only non-admitting original NEW candidate. */ -public final class CanonicalGameplayOriginalNewCandidateRedisScriptContribution - implements RedisScriptContribution { - public static final String SCRIPT_ID = "game-session.original-new-candidate-install.v1"; - public static final String RESOURCE_PATH = - "redis/lua/game-session-original-new-candidate-install.lua"; - private static final String DESCRIPTOR_PATH = - "/redis/scripts/game-session-original-new-candidate-install.json"; - private static final JsonMapper JSON = - JsonMapper.builder() - .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) - .enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) - .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) - .build(); - - @Override - public String ownerId() { - return "game-session-service"; - } - - @Override - public Collection descriptors() { - try (InputStream input = getClass().getResourceAsStream(DESCRIPTOR_PATH)) { - if (input == null) throw unavailable(); - byte[] bytes = input.readNBytes(16 * 1024 + 1); - if (bytes.length == 0 || bytes.length > 16 * 1024) throw unavailable(); - RedisScriptDescriptor descriptor = JSON.readValue(bytes, RedisScriptDescriptor.class); - if (!ownerId().equals(descriptor.owner()) || !SCRIPT_ID.equals(descriptor.scriptId())) { - throw unavailable(); - } - return List.of(descriptor); - } catch (IOException | RuntimeException failure) { - throw unavailable(); - } - } - - private static IllegalStateException unavailable() { - return new IllegalStateException("Original NEW candidate Redis descriptor is unavailable"); - } -} diff --git a/services/game-session-service/src/main/resources/META-INF/services/net.firedevops.firemud.common.redis.contracts.RedisScriptContribution b/services/game-session-service/src/main/resources/META-INF/services/net.firedevops.firemud.common.redis.contracts.RedisScriptContribution index 59d900160f..c9317c80ea 100644 --- a/services/game-session-service/src/main/resources/META-INF/services/net.firedevops.firemud.common.redis.contracts.RedisScriptContribution +++ b/services/game-session-service/src/main/resources/META-INF/services/net.firedevops.firemud.common.redis.contracts.RedisScriptContribution @@ -1,4 +1,3 @@ net.firedevops.firemud.gamesession.service.InitialGameplayLoginRedisScriptContribution net.firedevops.firemud.gamesession.service.CanonicalGameplayAccountMemberRepairRedisScriptContribution net.firedevops.firemud.gamesession.service.CanonicalGameplayAccountClosedBarrierRedisScriptContribution -net.firedevops.firemud.gamesession.service.CanonicalGameplayOriginalNewCandidateRedisScriptContribution diff --git a/services/game-session-service/src/main/resources/db/migration/V1048__canonical_original_new_candidate_installation.sql b/services/game-session-service/src/main/resources/db/migration/V1048__canonical_original_new_candidate_installation.sql deleted file mode 100644 index 5154004f9d..0000000000 --- a/services/game-session-service/src/main/resources/db/migration/V1048__canonical_original_new_candidate_installation.sql +++ /dev/null @@ -1,106 +0,0 @@ --- The first NEW session value is a distinct non-admitting candidate. Its exact bytes and --- dispatch/readback lifecycle live on the transition row already captured by account-control --- cohort snapshots. No second ledger or authenticated-session columns are introduced. - -ALTER TABLE game_session_canonical_binding_transition - ADD COLUMN original_new_candidate_bytes bytea, - ADD COLUMN original_new_candidate_digest character varying(71), - ADD COLUMN original_new_candidate_state character varying(32), - ADD COLUMN original_new_candidate_readback_digest character varying(71); - -ALTER TABLE game_session_canonical_binding_transition - ADD CONSTRAINT chk_gs_original_new_candidate_installation CHECK ( - ((original_new_candidate_bytes IS NULL - AND original_new_candidate_digest IS NULL - AND original_new_candidate_state IS NULL - AND original_new_candidate_readback_digest IS NULL) - OR (original_new_candidate_bytes IS NOT NULL - AND octet_length(original_new_candidate_bytes) BETWEEN 1 AND 524288 - AND original_new_candidate_digest IS NOT NULL - AND original_new_candidate_digest ~ '^sha256:[0-9a-f]{64}$' - AND original_new_candidate_state IS NOT NULL - AND original_new_candidate_state IN ('DISPATCH_POSSIBLE', 'READBACK_CONFIRMED') - AND ((original_new_candidate_state = 'DISPATCH_POSSIBLE' - AND original_new_candidate_readback_digest IS NULL) - OR (original_new_candidate_state = 'READBACK_CONFIRMED' - AND original_new_candidate_readback_digest IS NOT NULL - AND original_new_candidate_readback_digest ~ '^sha256:[0-9a-f]{64}$')))) - AND (original_new_candidate_bytes IS NULL - OR (expected_prior_binding_ref IS NULL - AND expected_prior_binding_generation IS NULL - AND status IN ('PREPARED', 'PROVISIONAL', 'COMMITTED', 'ABORTED', 'AMBIGUOUS'))) - ); - --- The first write freezes the exact candidate before any Redis attempt. The only later change --- records a positive owner readback digest. These columns are never reset or retargeted. --- [jooq ignore start] -CREATE FUNCTION guard_gs_original_new_candidate_installation() RETURNS trigger AS $$ -BEGIN - IF TG_OP = 'TRUNCATE' THEN - IF EXISTS (SELECT 1 FROM game_session_canonical_binding_transition - WHERE original_new_candidate_bytes IS NOT NULL) THEN - RAISE EXCEPTION 'Original NEW candidate transition retention is held' - USING ERRCODE = '23514', CONSTRAINT = 'gs_original_new_candidate_retained'; - END IF; - RETURN NULL; - END IF; - IF TG_OP = 'DELETE' THEN - IF OLD.original_new_candidate_bytes IS NOT NULL THEN - RAISE EXCEPTION 'Original NEW candidate transition retention is held' - USING ERRCODE = '23514', CONSTRAINT = 'gs_original_new_candidate_retained'; - END IF; - RETURN OLD; - END IF; - IF ROW(NEW.original_new_candidate_bytes, NEW.original_new_candidate_digest) - IS DISTINCT FROM ROW(OLD.original_new_candidate_bytes, OLD.original_new_candidate_digest) THEN - IF OLD.original_new_candidate_bytes IS NOT NULL - OR OLD.original_new_candidate_digest IS NOT NULL - OR NEW.original_new_candidate_bytes IS NULL - OR NEW.original_new_candidate_digest IS NULL - OR NEW.original_new_candidate_state IS DISTINCT FROM 'DISPATCH_POSSIBLE' - OR NEW.original_new_candidate_readback_digest IS NOT NULL - OR NEW.expected_prior_binding_ref IS NOT NULL - OR NEW.expected_prior_binding_generation IS NOT NULL - OR NEW.status NOT IN ('PREPARED', 'PROVISIONAL') THEN - RAISE EXCEPTION 'Original NEW candidate bytes are immutable after the first dispatch claim' - USING ERRCODE = '23514', CONSTRAINT = 'gs_original_new_candidate_immutable'; - END IF; - END IF; - IF NEW.original_new_candidate_state IS DISTINCT FROM OLD.original_new_candidate_state THEN - IF OLD.original_new_candidate_state IS NULL - AND NEW.original_new_candidate_state = 'DISPATCH_POSSIBLE' - AND OLD.original_new_candidate_bytes IS NULL - AND NEW.original_new_candidate_bytes IS NOT NULL - AND NEW.original_new_candidate_readback_digest IS NULL - AND NEW.expected_prior_binding_ref IS NULL - AND NEW.expected_prior_binding_generation IS NULL - AND NEW.status IN ('PREPARED', 'PROVISIONAL') THEN - NULL; - ELSIF OLD.original_new_candidate_state = 'DISPATCH_POSSIBLE' - AND NEW.original_new_candidate_state = 'READBACK_CONFIRMED' - AND NEW.original_new_candidate_bytes IS NOT DISTINCT FROM OLD.original_new_candidate_bytes - AND NEW.original_new_candidate_digest IS NOT DISTINCT FROM OLD.original_new_candidate_digest - AND NEW.original_new_candidate_readback_digest IS NOT NULL - AND NEW.original_new_candidate_readback_digest ~ '^sha256:[0-9a-f]{64}$' - AND NEW.status IN ('PREPARED', 'PROVISIONAL', 'COMMITTED', 'AMBIGUOUS') THEN - NULL; - ELSE - RAISE EXCEPTION 'Original NEW candidate dispatch/readback state is not monotone' - USING ERRCODE = '23514', CONSTRAINT = 'gs_original_new_candidate_state_monotone'; - END IF; - ELSIF NEW.original_new_candidate_readback_digest IS DISTINCT FROM OLD.original_new_candidate_readback_digest THEN - RAISE EXCEPTION 'Original NEW candidate readback digest is immutable' - USING ERRCODE = '23514', CONSTRAINT = 'gs_original_new_candidate_readback_immutable'; - END IF; - RETURN NEW; -END; -$$ LANGUAGE plpgsql; - -CREATE TRIGGER gs_original_new_candidate_installation_guard - BEFORE UPDATE OR DELETE ON game_session_canonical_binding_transition - FOR EACH ROW EXECUTE FUNCTION guard_gs_original_new_candidate_installation(); - -CREATE TRIGGER gs_original_new_candidate_installation_retention - BEFORE TRUNCATE ON game_session_canonical_binding_transition - FOR EACH STATEMENT EXECUTE FUNCTION guard_gs_original_new_candidate_installation(); --- [jooq ignore stop] diff --git a/services/game-session-service/src/main/resources/redis/lua/game-session-original-new-candidate-install.lua b/services/game-session-service/src/main/resources/redis/lua/game-session-original-new-candidate-install.lua deleted file mode 100644 index d41bee4694..0000000000 --- a/services/game-session-service/src/main/resources/redis/lua/game-session-original-new-candidate-install.lua +++ /dev/null @@ -1,79 +0,0 @@ --- First publication of one exact ORIGINAL_NEW non-admitting candidate. --- KEYS: session, character index, account-tenant set, tenant set. --- This script has no replay/create mode: the SQL owner authorizes exactly one invocation. -local sessionPrefix = 'session:game:' -local characterPrefix = 'session:game:index:character:' -local accountTenantPrefix = 'session:game:index:account-tenant:' -local tenantPrefix = 'session:game:index:tenant:' -local maxCandidateBytes = 524288 -local maxIdentifierBytes = 512 -local maxGenerationBytes = 256 - -local function uuid(value) - return type(value) == 'string' and #value == 36 - and string.match(value, '^%x%x%x%x%x%x%x%x%-%x%x%x%x%-%x%x%x%x%-%x%x%x%x%-%x%x%x%x%x%x%x%x%x%x%x%x$') - and value == string.lower(value) - and value ~= '00000000-0000-0000-0000-000000000000' -end - -local function positive(value) - return type(value) == 'string' and #value > 0 and #value <= maxGenerationBytes - and string.match(value, '^[1-9][0-9]*$') -end - -local function boundedText(value) - return type(value) == 'string' and #value > 0 and #value <= maxIdentifierBytes -end - -if #KEYS ~= 4 or #ARGV ~= 10 then return -2 end -local purpose = ARGV[1] -local tenantId = ARGV[2] -local accountId = ARGV[3] -local namespaceId = ARGV[4] -local characterId = ARGV[5] -local gameInstanceId = ARGV[6] -local sessionId = ARGV[7] -local bindingGeneration = ARGV[8] -local tenantGameplayTag = ARGV[9] -local candidateBytes = ARGV[10] - -if purpose ~= 'original-new-non-admitting-candidate/v1' - or not uuid(tenantId) or not uuid(accountId) or not uuid(namespaceId) - or not uuid(characterId) or not uuid(gameInstanceId) or not uuid(sessionId) - or not positive(bindingGeneration) or not boundedText(tenantGameplayTag) - or type(candidateBytes) ~= 'string' or #candidateBytes == 0 or #candidateBytes > maxCandidateBytes then - return -2 -end - -local sessionKey = sessionPrefix .. '{' .. tenantGameplayTag .. '}:' .. gameInstanceId .. ':' .. sessionId -local characterKey = characterPrefix .. '{' .. tenantGameplayTag .. '}:' .. namespaceId .. ':' .. characterId -local accountTenantKey = accountTenantPrefix .. '{' .. tenantGameplayTag .. '}:' .. accountId -local tenantKey = tenantPrefix .. '{' .. tenantGameplayTag .. '}' -if KEYS[1] ~= sessionKey or KEYS[2] ~= characterKey - or KEYS[3] ~= accountTenantKey or KEYS[4] ~= tenantKey then return -2 end - --- Check every key before the first mutation. The session and character projection must be truly --- absent; existing exact values are still an unknown prior writer and are never adopted. -local sessionType = redis.call('TYPE', KEYS[1]).ok -local characterType = redis.call('TYPE', KEYS[2]).ok -local accountType = redis.call('TYPE', KEYS[3]).ok -local tenantType = redis.call('TYPE', KEYS[4]).ok -if sessionType ~= 'none' or characterType ~= 'none' - or (accountType ~= 'none' and accountType ~= 'set') - or (tenantType ~= 'none' and tenantType ~= 'set') then return -1 end -if redis.call('PTTL', KEYS[1]) ~= -2 or redis.call('PTTL', KEYS[2]) ~= -2 - or (accountType == 'none' and redis.call('PTTL', KEYS[3]) ~= -2) - or (accountType == 'set' and redis.call('PTTL', KEYS[3]) ~= -1) - or (tenantType == 'none' and redis.call('PTTL', KEYS[4]) ~= -2) - or (tenantType == 'set' and redis.call('PTTL', KEYS[4]) ~= -1) then return -1 end -if redis.call('SISMEMBER', KEYS[3], sessionId) ~= 0 - or redis.call('SISMEMBER', KEYS[4], sessionId) ~= 0 then return -1 end - --- These writes are additive and target only the four exact same-slot keys. -redis.call('SET', KEYS[1], candidateBytes) -redis.call('SET', KEYS[2], - '{"sessionId":"' .. sessionId .. '","gameInstanceId":"' .. gameInstanceId - .. '","bindingGeneration":"' .. bindingGeneration .. '"}') -redis.call('SADD', KEYS[3], sessionId) -redis.call('SADD', KEYS[4], sessionId) -return 1 diff --git a/services/game-session-service/src/main/resources/redis/scripts/game-session-original-new-candidate-install.json b/services/game-session-service/src/main/resources/redis/scripts/game-session-original-new-candidate-install.json deleted file mode 100644 index 5b252d9f2a..0000000000 --- a/services/game-session-service/src/main/resources/redis/scripts/game-session-original-new-candidate-install.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "scriptId": "game-session.original-new-candidate-install.v1", - "resourcePath": "redis/lua/game-session-original-new-candidate-install.lua", - "sha256": "1f2658014b73710bca61f0be80fa7994e567e2680569a96b138f7c164e773dbd", - "owner": "game-session-service", - "principal": "gamesession_coord_app", - "role": "COORDINATION", - "keys": [ - {"name": "session", "ownedPrefix": "session:game:", "hashTagDeclaration": "REQUIRED"}, - {"name": "characterIndex", "ownedPrefix": "session:game:index:character:", "hashTagDeclaration": "REQUIRED"}, - {"name": "accountTenantIndex", "ownedPrefix": "session:game:index:account-tenant:", "hashTagDeclaration": "REQUIRED"}, - {"name": "tenantIndex", "ownedPrefix": "session:game:index:tenant:", "hashTagDeclaration": "REQUIRED"} - ], - "arguments": [ - {"name": "purpose"}, - {"name": "tenantId"}, - {"name": "accountId"}, - {"name": "playableStateNamespaceId"}, - {"name": "characterId"}, - {"name": "gameInstanceId"}, - {"name": "sessionId"}, - {"name": "bindingGeneration"}, - {"name": "tenantGameplayTag"}, - {"name": "candidateBytes"} - ], - "category": "SESSION_CAS", - "outcomes": [ - {"code": "CANDIDATE_CREATED", "category": "SUCCESS", "effect": "MUTATING"}, - {"code": "EXISTING_STATE_REFUSED", "category": "STALE", "effect": "NON_MUTATING"}, - {"code": "INVALID_ARGUMENTS", "category": "VALIDATION_FAILURE", "effect": "NON_MUTATING"} - ], - "resetSensitivity": "CLUSTER", - "lossClass": "EMPTY_REDIS_COLD_START_OR_RESET", - "tailLossBehavior": "The exact candidate is not an authenticated session and cannot authorize authenticated readers, PLAY, LOOK, or gameplay admission. The SQL owner persists DISPATCH_POSSIBLE before this one CREATE invocation. Every later retry is read-only and requires exact current readback of the session value and all three indexes; absence, partial state, foreign state, expiry, reset, or lost outcome remains uncertain and is never repaired. Only a later Account-committed final six-key CAS may replace the exact candidate with a complete authenticated session.", - "compatibilityLevel": "REQUIRES_CLUSTER_RESET", - "supportedCoexistence": [ - {"callerVersion": "v1", "payloadVersion": "none"} - ], - "legacyPayloadShape": null -} diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingRuntimeTestFixtures.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingRuntimeTestFixtures.java index aa4ee98c68..3674a45168 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingRuntimeTestFixtures.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingRuntimeTestFixtures.java @@ -278,7 +278,7 @@ public static RuntimeTarget seedRunningLaunch( SHA256, 1L, SHA256, - Instant.now().truncatedTo(java.time.temporal.ChronoUnit.MICROS), + Instant.now(), catalog.characterCreationPolicy(), sourceEvidence.sourceGameRowId(), sourceEvidence.sourceGameTenantKey(), diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPartitionBuildRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPartitionBuildRepositoryIntegrationTest.java index 650a3f6d4f..2797ef2a3f 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPartitionBuildRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPartitionBuildRepositoryIntegrationTest.java @@ -2425,13 +2425,6 @@ private static List rowImages(DSLContext dsl, String tableName) { image = "CASE WHEN to_jsonb(retained_row)->'admission_orphan_cleanup_id' = 'null'::jsonb" + " THEN to_jsonb(retained_row) - 'admission_orphan_cleanup_id' ELSE to_jsonb(retained_row) END"; - image = - "(" - + image - + ") - CASE WHEN to_jsonb(retained_row)->'original_new_candidate_bytes'" - + " = 'null'::jsonb THEN ARRAY['original_new_candidate_bytes'," - + " 'original_new_candidate_digest', 'original_new_candidate_state'," - + " 'original_new_candidate_readback_digest'] ELSE ARRAY[]::text[] END"; } else if (tableName.equals("game_session_canonical_binding_issuer_index_obligation")) { // V1036's null release link is absent-equivalent; an actual release UUID stays significant. image = @@ -2456,13 +2449,6 @@ private static List rowImagesWithXmin(DSLContext dsl, String tableName) image = "CASE WHEN to_jsonb(retained_row)->'admission_orphan_cleanup_id' = 'null'::jsonb" + " THEN to_jsonb(retained_row) - 'admission_orphan_cleanup_id' ELSE to_jsonb(retained_row) END"; - image = - "(" - + image - + ") - CASE WHEN to_jsonb(retained_row)->'original_new_candidate_bytes'" - + " = 'null'::jsonb THEN ARRAY['original_new_candidate_bytes'," - + " 'original_new_candidate_digest', 'original_new_candidate_state'," - + " 'original_new_candidate_readback_digest'] ELSE ARRAY[]::text[] END"; } else if (tableName.equals("game_session_canonical_binding_issuer_index_obligation")) { // V1036's null release link is absent-equivalent; an actual release UUID stays significant. image = diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCandidateRedisOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCandidateRedisOwnerIntegrationTest.java deleted file mode 100644 index 74a7c22037..0000000000 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCandidateRedisOwnerIntegrationTest.java +++ /dev/null @@ -1,659 +0,0 @@ -package net.firedevops.firemud.gamesession.repository; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import io.lettuce.core.AclSetuserArgs; -import io.lettuce.core.ClientOptions; -import io.lettuce.core.RedisClient; -import io.lettuce.core.RedisURI; -import io.lettuce.core.api.StatefulRedisConnection; -import io.lettuce.core.api.sync.RedisCommands; -import io.lettuce.core.codec.ByteArrayCodec; -import io.lettuce.core.protocol.CommandKeyword; -import io.lettuce.core.protocol.CommandType; -import java.math.BigInteger; -import java.nio.charset.StandardCharsets; -import java.nio.file.Path; -import java.time.Duration; -import java.util.ArrayList; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.UUID; -import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; -import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; -import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; -import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAdmissionDecision; -import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingIdentity; -import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingProvisionalCasEvidence; -import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingTransitionRequest; -import net.firedevops.firemud.gamesession.binding.CanonicalIssuerReservationFenceEvidence; -import net.firedevops.firemud.gamesession.service.CanonicalGameplayOriginalNewCandidateRedisScriptContribution; -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.springframework.jdbc.datasource.DriverManagerDataSource; -import org.springframework.transaction.support.TransactionSynchronizationManager; -import org.testcontainers.containers.GenericContainer; -import org.testcontainers.containers.PostgreSQLContainer; -import org.testcontainers.junit.jupiter.Container; -import org.testcontainers.junit.jupiter.Testcontainers; - -/** - * Actual PostgreSQL source plus Coordination Redis proof for the non-admitting original NEW value. - * The upstream target and Account lease are controlled fixtures; this proof does not qualify their - * authority or the separate ordinary-NEW issuer-LIVE preparation owner. - */ -@Testcontainers(disabledWithoutDocker = true) -@SuppressWarnings("resource") -class CanonicalGameplayOriginalNewCandidateRedisOwnerIntegrationTest { - private static final String PRINCIPAL = "gamesession_coord_app"; - private static final String PASSWORD = UUID.randomUUID().toString(); - private static final String KEY_PATTERN = "session:game:*"; - private static final int PORT = 6379; - private static final String MIGRATION_LOCATION = - "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize(); - private static final UUID TRANSITION_ID = UUID.randomUUID(); - private static final UUID ACCOUNT_INDEX_FENCE = UUID.randomUUID(); - private static final String ISSUER_ID = GameSessionAccountDelegationProfile.ISSUER; - - @Container - private static final GenericContainer REDIS = - new GenericContainer<>(TestContainerImages.redis()).withExposedPorts(PORT); - - @Container - private static final PostgreSQLContainer POSTGRES = - new PostgreSQLContainer<>(TestContainerImages.postgres()); - - private RedisClient administrator; - private RedisClient ownerClient; - private StatefulRedisConnection adminConnection; - private RedisCommands admin; - private TestSource source; - private CanonicalGameplayOriginalNewCandidateRedisOwner owner; - - @org.junit.jupiter.api.BeforeEach - void setUp() { - administrator = createClient(null, null); - adminConnection = administrator.connect(ByteArrayCodec.INSTANCE); - admin = adminConnection.sync(); - admin.flushdb(); - admin.aclSetuser( - PRINCIPAL, - new AclSetuserArgs() - .reset() - .on() - .addPassword(PASSWORD) - .keyPattern(KEY_PATTERN) - .addCommand(CommandType.HELLO) - .addCommand(CommandType.PING) - .addCommand(CommandType.CLIENT, CommandKeyword.SETINFO) - .addCommand(CommandType.ACL, CommandKeyword.WHOAMI) - .addCommand(CommandType.SCRIPT, CommandKeyword.LOAD) - .addCommand(CommandType.EVALSHA) - .addCommand(CommandType.TYPE) - .addCommand(CommandType.PTTL) - .addCommand(CommandType.GET) - .addCommand(CommandType.SET) - .addCommand(CommandType.SADD) - .addCommand(CommandType.SISMEMBER)); - ownerClient = createClient(PRINCIPAL, PASSWORD); - var catalog = RedisScriptCatalog.loadInstalled(getClass().getClassLoader()); - source = prepareSource(); - owner = - CanonicalGameplayOriginalNewCandidateRedisOwnerFactory.create( - ownerClient, catalog, source.repository(), source.tenantTags()); - } - - @org.junit.jupiter.api.AfterEach - void tearDown() { - if (source != null) source.close(); - if (adminConnection != null) adminConnection.close(); - if (ownerClient != null) ownerClient.shutdown(Duration.ZERO, Duration.ofSeconds(2)); - if (administrator != null) administrator.shutdown(Duration.ZERO, Duration.ofSeconds(2)); - } - - @org.junit.jupiter.api.Test - void installsExactCandidateAndReadOnlyRetryRetainsTheSameProvisionalDecision() { - var first = owner.installOnce(source.decision()); - advanceInventoryWithUnrelatedPreparedNew(); - var retry = owner.installOnce(source.decision()); - - assertThat(first.candidate().matchesOriginalDecision(source.decision())).isTrue(); - assertThat(first.candidate().canonicalBytes()).containsExactly(first.exactCandidateBytes()); - assertThat(first.isNonAdmittingCandidate()).isTrue(); - assertThat(first.provisionalTransition().status().name()).isEqualTo("PROVISIONAL"); - assertThat(retry.candidate()).isEqualTo(first.candidate()); - assertThat(retry.physicalReadback().digest()).isEqualTo(first.physicalReadback().digest()); - assertThat( - source - .repository() - .readAdmissionDecision(TRANSITION_ID, source.decision().leaseEvidence())) - .satisfies( - stored -> { - assertThat(first.candidate().matchesOriginalDecision(stored)).isTrue(); - assertThat(stored.leaseEvidence().canonicalJson()) - .isEqualTo(source.decision().leaseEvidence().canonicalJson()); - }); - - assertThat(admin.type(ascii(first.sessionKey()))).isEqualTo("string"); - assertThat(admin.get(ascii(first.sessionKey()))).containsExactly(first.exactCandidateBytes()); - assertThat(admin.type(ascii(first.characterIndexKey()))).isEqualTo("string"); - assertThat(new String(admin.get(ascii(first.characterIndexKey())), StandardCharsets.US_ASCII)) - .contains( - source.identity().sessionId(), - source.identity().gameInstanceId().toString(), - "bindingGeneration"); - assertThat( - admin.sismember( - ascii(first.accountTenantIndexKey()), ascii(source.identity().sessionId()))) - .isTrue(); - assertThat(admin.sismember(ascii(first.tenantIndexKey()), ascii(source.identity().sessionId()))) - .isTrue(); - assertThat(admin.pttl(ascii(first.sessionKey()))).isEqualTo(-1L); - } - - @org.junit.jupiter.api.Test - void missingAccountTenantOrTenantSetRefusesRetryWithoutChangingSqlOrOtherPostimages() { - List additionalSources = new ArrayList<>(); - try { - for (int missingIndex = 0; missingIndex < 2; missingIndex++) { - TestSource scenario = missingIndex == 0 ? source : prepareSource(); - if (scenario != source) additionalSources.add(scenario); - CanonicalGameplayOriginalNewCandidateRedisOwner scenarioOwner = - scenario == source - ? owner - : CanonicalGameplayOriginalNewCandidateRedisOwnerFactory.create( - ownerClient, - RedisScriptCatalog.loadInstalled(getClass().getClassLoader()), - scenario.repository(), - scenario.tenantTags()); - var installation = scenarioOwner.installOnce(scenario.decision()); - String missingKey = - missingIndex == 0 - ? installation.accountTenantIndexKey() - : installation.tenantIndexKey(); - String preservedKey = - missingIndex == 0 - ? installation.tenantIndexKey() - : installation.accountTenantIndexKey(); - byte[] sessionBytes = admin.get(ascii(installation.sessionKey())); - byte[] characterBytes = admin.get(ascii(installation.characterIndexKey())); - String sqlImageBeforeRetry = sourceSqlImage(scenario); - - assertThat(admin.del(ascii(missingKey))).isEqualTo(1L); - assertThatThrownBy(() -> scenarioOwner.installOnce(scenario.decision())) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("install/readback is unavailable"); - - assertThat(admin.type(ascii(missingKey))).isEqualTo("none"); - assertThat(admin.type(ascii(installation.sessionKey()))).isEqualTo("string"); - assertThat(admin.pttl(ascii(installation.sessionKey()))).isEqualTo(-1L); - assertThat(admin.get(ascii(installation.sessionKey()))).containsExactly(sessionBytes); - assertThat(admin.type(ascii(installation.characterIndexKey()))).isEqualTo("string"); - assertThat(admin.pttl(ascii(installation.characterIndexKey()))).isEqualTo(-1L); - assertThat(admin.get(ascii(installation.characterIndexKey()))) - .containsExactly(characterBytes); - assertThat(admin.type(ascii(preservedKey))).isEqualTo("set"); - assertThat(admin.pttl(ascii(preservedKey))).isEqualTo(-1L); - assertThat(admin.sismember(ascii(preservedKey), ascii(scenario.identity().sessionId()))) - .isTrue(); - assertThat(sourceSqlImage(scenario)).isEqualTo(sqlImageBeforeRetry); - } - } finally { - additionalSources.forEach(TestSource::close); - } - } - - @org.junit.jupiter.api.Test - void doubleSqlClaimIssuesExactlyOneSingleUseCreatePermission() { - var first = source.repository().claimOriginalNewCandidateInstallation(source.decision()); - var second = source.repository().claimOriginalNewCandidateInstallation(source.decision()); - - assertThat(first.consumeCreatePermission()).isTrue(); - assertThat(first.consumeCreatePermission()).isFalse(); - assertThat(second.consumeCreatePermission()).isFalse(); - assertThatThrownBy(() -> owner.installClaimOnce(second)) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("install/readback is unavailable"); - assertThat(admin.dbsize()).isZero(); - } - - @org.junit.jupiter.api.Test - void changedOriginalLeaseCannotReuseThePersistedCandidateOrDispatchRedis() { - var originalClaim = - source.repository().claimOriginalNewCandidateInstallation(source.decision()); - assertThat(originalClaim.state().name()).isEqualTo("DISPATCH_POSSIBLE"); - Map changedCarrier = - new LinkedHashMap<>(source.decision().leaseEvidence().carrier()); - changedCarrier.put("leaseId", UUID.randomUUID().toString()); - var changedLease = AccountGameplayAdmissionLeaseEvidence.fromCarrier(changedCarrier); - var changedDecision = - new CanonicalGameplayAdmissionDecision( - TRANSITION_ID, - changedLease, - source.identity(), - source.decision().bindingGeneration(), - null, - source.decision().targetEvidence()); - - assertThatThrownBy(() -> owner.installOnce(changedDecision)) - .isInstanceOf(RuntimeException.class); - assertThat(admin.dbsize()).isZero(); - assertThat( - source - .dsl() - .fetchSingle( - "SELECT original_new_candidate_state FROM game_session_canonical_binding_transition" - + " WHERE transition_id = ?", - TRANSITION_ID) - .get("original_new_candidate_state", String.class)) - .isEqualTo("DISPATCH_POSSIBLE"); - } - - @org.junit.jupiter.api.Test - void lostReplyRecoveryUsesOnlyExactReadbackAfterTheCreatePermissionWasClaimed() { - var claim = source.repository().claimOriginalNewCandidateInstallation(source.decision()); - assertThat(claim.consumeCreatePermission()).isTrue(); - var assignment = source.tenantTags().assignmentForTransition(TRANSITION_ID); - var binding = claim.candidate().bindingIdentity(); - String sessionKey = CanonicalGameplaySessionRedisKeys.session(assignment, binding.bindingRef()); - String characterKey = - CanonicalGameplaySessionRedisKeys.characterIndex(assignment, binding.bindingRef()); - String accountKey = - CanonicalGameplaySessionRedisKeys.accountTenantIndex(assignment, binding.bindingRef()); - String tenantKey = - CanonicalGameplaySessionRedisKeys.tenantIndex(assignment, binding.bindingRef()); - byte[] script; - try (var input = - getClass() - .getClassLoader() - .getResourceAsStream( - CanonicalGameplayOriginalNewCandidateRedisScriptContribution.RESOURCE_PATH)) { - if (input == null) throw new IllegalStateException("Candidate install script is missing"); - script = input.readAllBytes(); - } catch (java.io.IOException failure) { - throw new IllegalStateException("Cannot load candidate install script", failure); - } - String sha = admin.scriptLoad(script); - Long reply = - admin.evalsha( - sha, - io.lettuce.core.ScriptOutputType.INTEGER, - new byte[][] { - ascii(sessionKey), ascii(characterKey), ascii(accountKey), ascii(tenantKey) - }, - ascii(CanonicalGameplayOriginalNewCandidate.PURPOSE), - ascii(assignment.tenantId().toString()), - ascii(assignment.accountId().toString()), - ascii(assignment.playableStateNamespaceId().toString()), - ascii(assignment.characterId().toString()), - ascii(assignment.gameInstanceId().toString()), - ascii(assignment.sessionId()), - ascii(claim.candidate().transition().bindingGeneration().toString()), - ascii(assignment.tenantGameplayTag()), - claim.candidate().canonicalBytes()); - assertThat(reply).isEqualTo(1L); - // The owner is called as if the prior reply was lost. The SQL marker prevents a second eval. - var recovered = owner.installOnce(source.decision()); - assertThat(recovered.candidate()).isEqualTo(claim.candidate()); - assertThat(admin.get(ascii(recovered.sessionKey()))) - .containsExactly(recovered.exactCandidateBytes()); - } - - @org.junit.jupiter.api.Test - void resetAndCharacterConflictRemainUnresolvedWithoutRepair() { - var claim = source.repository().claimOriginalNewCandidateInstallation(source.decision()); - assertThat(claim.consumeCreatePermission()).isTrue(); - admin.flushdb(); - - assertThatThrownBy(() -> owner.installOnce(source.decision())) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("install/readback is unavailable"); - assertThat(admin.dbsize()).isZero(); - assertThat( - source - .dsl() - .fetchSingle( - "SELECT original_new_candidate_state FROM game_session_canonical_binding_transition" - + " WHERE transition_id = ?", - TRANSITION_ID) - .get("original_new_candidate_state", String.class)) - .isEqualTo("DISPATCH_POSSIBLE"); - - var conflictSource = prepareSource(); - try { - var assignment = conflictSource.tenantTags().assignmentForTransition(TRANSITION_ID); - String characterKey = - CanonicalGameplaySessionRedisKeys.characterIndex( - assignment, conflictSource.identity().bindingRef()); - admin.set(ascii(characterKey), ascii("foreign-generation")); - var conflictOwner = - CanonicalGameplayOriginalNewCandidateRedisOwnerFactory.create( - ownerClient, - RedisScriptCatalog.loadInstalled(getClass().getClassLoader()), - conflictSource.repository(), - conflictSource.tenantTags()); - assertThatThrownBy(() -> conflictOwner.installOnce(conflictSource.decision())) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("install/readback is unavailable"); - assertThat(admin.get(ascii(characterKey))).isEqualTo(ascii("foreign-generation")); - assertThat( - admin.type( - ascii( - CanonicalGameplaySessionRedisKeys.session( - assignment, conflictSource.identity().bindingRef())))) - .isEqualTo("none"); - } finally { - conflictSource.close(); - } - } - - @org.junit.jupiter.api.Test - void acquisitionIntentRaceRefusesBeforeAnyRedisMutationAndAmbientSqlNeverCallsRedis() { - var claimed = source.repository().claimOriginalNewCandidateInstallation(source.decision()); - assertThat(claimed.consumeCreatePermission()).isTrue(); - new CanonicalGameplayAccountAdmissionBarrierRepository(source.dsl()) - .beginFenceIntent(source.identity().accountId(), UUID.randomUUID()); - assertThatThrownBy(() -> owner.installOnce(source.decision())) - .isInstanceOf(RuntimeException.class); - assertThat(admin.dbsize()).isZero(); - - try { - TransactionSynchronizationManager.setActualTransactionActive(true); - assertThatThrownBy(() -> owner.installOnce(source.decision())) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("ambient SQL transaction or synchronization"); - } finally { - TransactionSynchronizationManager.clear(); - } - assertThat(admin.dbsize()).isZero(); - - try { - TransactionSynchronizationManager.initSynchronization(); - assertThatThrownBy(() -> owner.installOnce(source.decision())) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("ambient SQL transaction or synchronization"); - } finally { - TransactionSynchronizationManager.clearSynchronization(); - } - assertThat(admin.dbsize()).isZero(); - } - - private static String sourceSqlImage(TestSource source) { - return source - .dsl() - .fetchSingle( - "SELECT jsonb_build_array(" - + "(SELECT to_jsonb(t) FROM game_session_canonical_binding_transition t" - + " WHERE t.transition_id = ?)," - + "(SELECT to_jsonb(i) FROM game_session_canonical_gameplay_binding_inventory i" - + " WHERE i.transition_id = ?)," - + "(SELECT to_jsonb(r) FROM game_session_canonical_issuer_partition_reservation r" - + " WHERE r.transition_id = ?)," - + "(SELECT to_jsonb(a) FROM game_session_canonical_binding_account_index_obligation a" - + " WHERE a.transition_id = ?)," - + "(SELECT to_jsonb(i) FROM game_session_canonical_binding_issuer_index_obligation i" - + " WHERE i.transition_id = ?)," - + "(SELECT to_jsonb(r) FROM game_session_canonical_binding_region_bridge_obligation r" - + " WHERE r.transition_id = ?)," - + "(SELECT inventory_revision FROM game_session_canonical_binding_inventory_clock" - + " WHERE singleton_id = 1))::text", - TRANSITION_ID, - TRANSITION_ID, - TRANSITION_ID, - TRANSITION_ID, - TRANSITION_ID, - TRANSITION_ID) - .get(0, String.class); - } - - private TestSource prepareSource() { - String schema = "gs_original_new_candidate_" + UUID.randomUUID().toString().replace("-", ""); - DriverManagerDataSource dataSource = new DriverManagerDataSource(); - dataSource.setDriverClassName("org.postgresql.Driver"); - String jdbcUrl = POSTGRES.getJdbcUrl(); - dataSource.setUrl(jdbcUrl + (jdbcUrl.contains("?") ? "&" : "?") + "currentSchema=" + schema); - dataSource.setUsername(POSTGRES.getUsername()); - dataSource.setPassword(POSTGRES.getPassword()); - Flyway.configure() - .dataSource(dataSource) - .schemas(schema) - .defaultSchema(schema) - .table("flyway_schema_history") - .locations(MIGRATION_LOCATION) - .load() - .migrate(); - DSLContext dsl = DSL.using(dataSource, SQLDialect.POSTGRES); - var runtime = CanonicalGameplayBindingRuntimeTestFixtures.seedRunningLaunch(dataSource); - seedSyntheticVerifiedLegacyDisposition(dsl); - CanonicalGameplayBindingIdentity identity = - new CanonicalGameplayBindingIdentity( - UUID.randomUUID(), - runtime.canonicalTenantId(), - runtime.playableStateNamespaceId(), - UUID.randomUUID(), - runtime.playableStateScope(), - runtime.gameInstanceUuid(), - runtime.gameInstanceId(), - UUID.randomUUID().toString(), - UUID.randomUUID(), - BigInteger.valueOf(3), - ISSUER_ID, - BigInteger.ONE, - BigInteger.ONE, - BigInteger.valueOf(4), - BigInteger.valueOf(32)); - UUID transitionId = TRANSITION_ID; - CanonicalGameplayBindingInventoryRepository repository = - new CanonicalGameplayBindingInventoryRepository(dsl); - repository.prepare( - new CanonicalGameplayBindingTransitionRequest( - transitionId, - ACCOUNT_INDEX_FENCE, - identity, - new CanonicalIssuerReservationFenceEvidence( - UUID.randomUUID(), - UUID.randomUUID(), - UUID.randomUUID(), - BigInteger.ONE, - BigInteger.TWO, - BigInteger.ONE), - null, - null)); - CanonicalGameplayBindingProvisionalCasEvidence prepared = - repository.readProvisionalCasEvidence(transitionId); - var decision = - new CanonicalGameplayAdmissionDecision( - transitionId, - leaseEvidence( - identity, prepared.transition().bindingGeneration(), runtime.playableTarget()), - identity, - prepared.transition().bindingGeneration(), - null, - runtime.playableTarget()); - var tenantTags = - new CanonicalGameplayTenantGameplayTagRepository(dsl, runtime.targetNamespace(), 1); - return new TestSource(schema, dataSource, dsl, repository, tenantTags, identity, decision); - } - - private void advanceInventoryWithUnrelatedPreparedNew() { - CanonicalGameplayBindingIdentity original = source.identity(); - var unrelated = - new CanonicalGameplayBindingIdentity( - original.accountId(), - original.tenantId(), - original.playableStateNamespaceId(), - UUID.randomUUID(), - original.playableStateScope(), - original.gameInstanceId(), - original.runtimeGameInstanceId(), - UUID.randomUUID().toString(), - original.regionId(), - original.regionEpoch(), - original.issuerId(), - original.issuerAuthGeneration(), - original.issuerIndexLayoutVersion(), - original.issuerIndexPartitionCount(), - original.issuerIndexPartitionCapacity()); - source - .repository() - .prepare( - new CanonicalGameplayBindingTransitionRequest( - UUID.randomUUID(), - UUID.randomUUID(), - unrelated, - new CanonicalIssuerReservationFenceEvidence( - UUID.randomUUID(), - UUID.randomUUID(), - UUID.randomUUID(), - BigInteger.ONE, - BigInteger.TWO, - BigInteger.ONE), - null, - null)); - } - - private static void seedSyntheticVerifiedLegacyDisposition(DSLContext dsl) { - dsl.execute( - "UPDATE game_session_canonical_binding_inventory_clock" - + " SET inventory_revision = 1 WHERE singleton_id = 1"); - dsl.execute( - "UPDATE game_session_canonical_binding_legacy_disposition" - + " SET disposition_state = 'VERIFIED'," - + " cohort_id = '10101010-1010-4010-8010-101010101010'," - + " owner_operation_id = '20202020-2020-4020-8020-202020202020'," - + " legacy_writer_fence = '30303030-3030-4030-8030-303030303030'," - + " source_snapshot_revision = 1, canonical_inventory_revision = 1," - + " namespace_index_readback_revision = 1, evidence_digest = 'sha256:" - + "0000000000000000000000000000000000000000000000000000000000000000'" - + " WHERE singleton_id = 1"); - } - - private static AccountGameplayAdmissionLeaseEvidence leaseEvidence( - CanonicalGameplayBindingIdentity candidate, - BigInteger bindingGeneration, - net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget target) { - long now = System.currentTimeMillis(); - String nowSeconds = Long.toString(now / 1000L); - Map carrier = new LinkedHashMap<>(); - carrier.put("schema", AccountGameplayAdmissionLeaseEvidence.SCHEMA); - carrier.put("schemaVersion", "1"); - carrier.put("mode", "PUBLIC_PRODUCTION"); - carrier.put("leaseKind", AccountGameplayAdmissionLeaseEvidence.LeaseKind.NEW_BINDING.name()); - carrier.put("targetNamespace", target.targetNamespace()); - carrier.put( - "callerWorkload", - "spiffe://firemud/ns/" + target.targetNamespace() + "/sa/game-session-service"); - carrier.put("requestId", UUID.randomUUID().toString()); - carrier.put("leaseId", UUID.randomUUID().toString()); - carrier.put("leaseFence", "1"); - Map scope = new LinkedHashMap<>(); - scope.put("accountId", candidate.accountId().toString()); - scope.put("tenantId", candidate.tenantId().toString()); - scope.put("realmId", target.realmId().toString()); - scope.put("worldSlug", target.worldSlug()); - scope.put("realmSlug", target.realmSlug()); - scope.put("playableStateNamespaceId", target.playableStateNamespaceId().toString()); - scope.put("playableStateScope", target.playableStateScope()); - scope.put("gameInstanceId", target.canonicalGameInstanceId().toString()); - scope.put("characterId", candidate.characterId().toString()); - scope.put("sessionId", candidate.sessionId()); - scope.put("bindingGeneration", bindingGeneration.toString()); - scope.put("catalogRevision", Long.toString(target.catalogRevision())); - scope.put("pointerVersion", Long.toString(target.pointerVersion())); - scope.put("regionId", candidate.regionId().toString()); - scope.put("regionEpoch", candidate.regionEpoch().toString()); - carrier.put("bindingScope", scope); - carrier.put( - "authorityTuple", - Map.of( - "issuerAuthGeneration", candidate.issuerAuthGeneration().toString(), - "accountAuthorityGeneration", "1", - "tenantAuthorityGeneration", Map.of(candidate.tenantId().toString(), "1"), - "membershipAuthorityGeneration", Map.of(candidate.tenantId().toString(), "1"), - "privateRealmGrantVersions", List.of())); - carrier.put("issuanceFence", "1"); - carrier.put( - "membershipBaseline", - Map.of( - "membershipLifecycleState", "ACTIVE", - "membershipVersion", Map.of(candidate.tenantId().toString(), "1"), - "membershipAuthorityGeneration", "1")); - String prefix = "account:auth-authority:v1:"; - List> checkpoints = new ArrayList<>(); - for (String stream : - List.of( - "account/" + candidate.accountId(), - "issuer/firemud-account-service", - "membership/" + candidate.accountId() + "/" + candidate.tenantId(), - "tenant/" + candidate.tenantId())) { - checkpoints.add( - Map.of( - "outboxStreamKey", - prefix + stream, - "outboxSequence", - stream.startsWith("membership/") || stream.startsWith("tenant/") ? "1" : "0")); - } - carrier.put("outboxCheckpoints", checkpoints); - carrier.put( - "tokenIdentityEvidence", - Map.ofEntries( - Map.entry("accountId", candidate.accountId().toString()), - Map.entry("operationId", UUID.randomUUID().toString()), - Map.entry("issuanceRequestId", UUID.randomUUID().toString()), - Map.entry("tokenJti", UUID.randomUUID().toString()), - Map.entry("tokenSHA256", "a".repeat(64)), - Map.entry("tokenProfile", "game-session-account-delegation"), - Map.entry("tokenGeneration", "1"), - Map.entry("issuanceFence", "1"), - Map.entry("tokenIdentityFence", "1"), - Map.entry("issuedAt", nowSeconds), - Map.entry("notBefore", nowSeconds), - Map.entry("expiresAt", Long.toString(now / 1000L + 60L)))); - carrier.put("evaluatedAt", Long.toString(now)); - carrier.put( - "expiresAt", - Long.toString(now + AccountGameplayAdmissionLeaseEvidence.MAX_DURATION_MILLIS)); - return AccountGameplayAdmissionLeaseEvidence.fromCarrier(carrier); - } - - private RedisClient createClient(String username, String password) { - RedisURI.Builder builder = - RedisURI.Builder.redis(REDIS.getHost(), REDIS.getMappedPort(PORT)) - .withTimeout(Duration.ofSeconds(3)); - if (username != null) builder.withAuthentication(username, password); - RedisClient client = RedisClient.create(builder.build()); - client.setOptions(ClientOptions.builder().autoReconnect(false).build()); - return client; - } - - private static byte[] ascii(String value) { - return value.getBytes(StandardCharsets.US_ASCII); - } - - private record TestSource( - String schema, - DriverManagerDataSource dataSource, - DSLContext dsl, - CanonicalGameplayBindingInventoryRepository repository, - CanonicalGameplayTenantGameplayTagRepository tenantTags, - CanonicalGameplayBindingIdentity identity, - CanonicalGameplayAdmissionDecision decision) - implements AutoCloseable { - @Override - public void close() { - try (var connection = - java.sql.DriverManager.getConnection( - POSTGRES.getJdbcUrl(), POSTGRES.getUsername(), POSTGRES.getPassword()); - var statement = connection.createStatement()) { - statement.execute("DROP SCHEMA IF EXISTS " + schema + " CASCADE"); - } catch (Exception failure) { - throw new IllegalStateException("Cannot drop candidate proof schema", failure); - } - } - } -} diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRetainedFirstNewAbortAccountControlMigrationIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRetainedFirstNewAbortAccountControlMigrationIntegrationTest.java new file mode 100644 index 0000000000..953b38caee --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRetainedFirstNewAbortAccountControlMigrationIntegrationTest.java @@ -0,0 +1,462 @@ +package net.firedevops.firemud.gamesession.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.file.Path; +import java.time.OffsetDateTime; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.MigrationVersion; +import org.jooq.DSLContext; +import org.jooq.Field; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * Controlled V1038 predecessor storage, with installed guards and actual filesystem migrations. + * Lease, terminal Account outcome and member readback are stipulated historical SQL inputs, never + * fresh admission, issuer OPEN control, grants or evidence that a historical runtime owner ran. The + * Account owner-composition suite separately proves authenticated abort and physical cleanup. + */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class CanonicalGameplayRetainedFirstNewAbortAccountControlMigrationIntegrationTest { + private static final String PREFIX = "game_session_canonical_"; + private static final List RETAINED_TABLES = + List.of( + "binding_transition", + "gameplay_binding_inventory", + "issuer_partition_reservation", + "binding_account_index_obligation", + "binding_issuer_index_obligation", + "binding_region_bridge_obligation", + "account_member_repair_operation"); + private static final UUID ACCOUNT = UUID.randomUUID(); + private static final UUID TENANT = UUID.randomUUID(); + private static final UUID NAMESPACE = UUID.randomUUID(); + private static final UUID CHARACTER = UUID.randomUUID(); + private static final UUID TRANSITION = UUID.randomUUID(); + private static final UUID RESERVATION = UUID.randomUUID(); + private static final UUID ACCOUNT_FENCE = UUID.randomUUID(); + private static final UUID INSTANCE = UUID.randomUUID(); + private static final UUID REGION = UUID.randomUUID(); + private static final byte[] BINDING_REF = new byte[] {1, 2, 3}; + private static final String MEMBER = "accountIndexMember/v1:AQID:1:" + ACCOUNT_FENCE; + private static final String RAW_DIGEST = "a".repeat(64); + private static final String DIGEST = "sha256:" + RAW_DIGEST; + + @Container + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Test + void v1038Point1PreservesAcknowledgedAbortAndHistoryThenAllowsLaterControlCleanup() { + String schema = "gs_retained_abort_" + UUID.randomUUID().toString().replace("-", ""); + var dataSource = + new DriverManagerDataSource( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); + dataSource.setSchema(schema); + try { + Flyway predecessor = flyway(dataSource, schema, "1038"); + predecessor.migrate(); + predecessor.validate(); + DSLContext dsl = DSL.using(dataSource, SQLDialect.POSTGRES); + seedControlledAcknowledgedAbort(dsl); + // Validate the complete terminal predecessor under its original NO_ACTIVE control. All + // installed immediate and deferred guards remain enabled; no current prepare owner is used. + dsl.execute( + "UPDATE " + PREFIX + "binding_transition SET inventory_revision = inventory_revision"); + seedLaterControlledAcquisitionIntent(dsl); + + Map> originalRows = rows(dsl, false); + originalRows.values().forEach(images -> assertThat(images).hasSize(1)); + Map> immutableRows = rows(dsl, true); + assertThat( + dsl.fetchSingle("SELECT state FROM " + PREFIX + "account_coverage_control") + .get(0, String.class)) + .isEqualTo("ACQUISITION_INTENT"); + List historyBefore = history(dsl); + assertThat(historyBefore) + .anyMatch(row -> row.contains("V1000__create_saga_schema.sql")) + .anyMatch(row -> row.contains("V1001__saga_instance_table.sql")) + .anyMatch(row -> row.contains("V1002__saga_step_table.sql")); + assertThat( + dsl.fetchSingle( + "SELECT version FROM flyway_schema_history ORDER BY installed_rank DESC LIMIT 1") + .get(0, String.class)) + .isEqualTo("1038"); + + // This is the V1038 defect: a retained abort's exact original ACK must not require the + // account to remain forever at its old NO_ACTIVE epoch. The failed transaction rolls back + // every affected row, including the singleton inventory clock. + assertThatThrownBy(() -> advanceRetainedRevision(dsl)) + .isInstanceOf(org.jooq.exception.DataAccessException.class) + .rootCause() + .isInstanceOf(org.postgresql.util.PSQLException.class) + .hasMessageContaining("First-NEW Account abort requires its exact retained candidate"); + assertThat(rows(dsl, false)).isEqualTo(originalRows); + assertThat( + dsl.fetchSingle( + "SELECT inventory_revision FROM " + PREFIX + "binding_inventory_clock") + .get(0, Integer.class)) + .isEqualTo(5); + + Flyway upgraded = flyway(dataSource, schema, "1038.1"); + assertThat(upgraded.migrate().migrationsExecuted).isEqualTo(1); + upgraded.validate(); + List historyAfter = history(dsl); + assertThat(historyAfter).hasSize(historyBefore.size() + 1); + assertThat(historyAfter.subList(0, historyBefore.size())) + .containsExactlyElementsOf(historyBefore); + assertThat(historyAfter.get(historyAfter.size() - 1)) + .contains("1038.1", "V1038.1__retained_first_new_abort_cleanup_account_control.sql"); + assertThat(rows(dsl, false)).isEqualTo(originalRows); + assertThat( + dsl.fetchSingle( + "SELECT inventory_revision FROM " + PREFIX + "binding_inventory_clock") + .get(0, Integer.class)) + .isEqualTo(5); + + advanceRetainedRevision(dsl); + assertThat(rows(dsl, true)).isEqualTo(immutableRows); + for (String table : RETAINED_TABLES.subList(0, 6)) { + assertThat( + dsl.fetchSingle("SELECT inventory_revision FROM " + PREFIX + table) + .get(0, Integer.class)) + .isEqualTo(6); + } + assertThat( + dsl.fetchSingle( + "SELECT inventory_revision FROM " + PREFIX + "binding_inventory_clock") + .get(0, Integer.class)) + .isEqualTo(6); + assertThat(history(dsl)).containsExactlyElementsOf(historyAfter); + assertThat(upgraded.migrate().migrationsExecuted).isZero(); + assertThat(history(dsl)).containsExactlyElementsOf(historyAfter); + } finally { + DSL.using(dataSource, SQLDialect.POSTGRES) + .execute("DROP SCHEMA IF EXISTS " + schema + " CASCADE"); + } + } + + private static void seedControlledAcknowledgedAbort(DSLContext dsl) { + dsl.transaction( + configuration -> { + DSLContext tx = DSL.using(configuration); + tx.execute("UPDATE " + PREFIX + "binding_inventory_clock SET inventory_revision = 5"); + insert( + tx, + "account_coverage_control", + Map.of( + "account_id", + ACCOUNT, + "state", + "NO_ACTIVE_ACCOUNT_WIDE_FLOW", + "last_operation_fence", + 0)); + insert( + tx, + "account_member_repair_control", + Map.of( + "account_id", ACCOUNT, + "last_operation_fence", 1, + "last_coverage_generation", 3)); + Map candidate = new LinkedHashMap<>(); + candidate.put("binding_ref", BINDING_REF); + candidate.put("account_id", ACCOUNT); + candidate.put("tenant_id", TENANT); + candidate.put("playable_state_namespace_id", NAMESPACE); + candidate.put("character_id", CHARACTER); + candidate.put("playable_state_scope", "SHARED"); + candidate.put("game_instance_id", INSTANCE); + candidate.put("runtime_game_instance_id", 1L); + candidate.put("session_id", UUID.randomUUID().toString()); + candidate.put("binding_generation", 1); + candidate.put("region_id", REGION); + candidate.put("region_epoch", 1); + candidate.put("issuer_id", "firemud-account-service"); + candidate.put("issuer_auth_generation", 1); + candidate.put("issuer_index_layout_version", 1); + candidate.put("issuer_index_partition_count", 1); + candidate.put("issuer_index_partition_capacity", 3); + candidate.put("issuer_partition_id", 0); + candidate.put("account_index_fence", ACCOUNT_FENCE); + candidate.put("issuer_reservation_id", RESERVATION); + candidate.put("transition_id", TRANSITION); + candidate.put("lifecycle", "TERMINAL_UNRESOLVED"); + candidate.put("account_index_state", "ACKNOWLEDGED"); + candidate.put("issuer_index_state", "REPAIR_REQUIRED"); + candidate.put("inventory_revision", 5); + insert(tx, "gameplay_binding_inventory", candidate); + + Map transition = new LinkedHashMap<>(); + transition.put("transition_id", TRANSITION); + transition.put("tenant_id", TENANT); + transition.put("playable_state_namespace_id", NAMESPACE); + transition.put("character_id", CHARACTER); + transition.put("candidate_binding_ref", BINDING_REF); + transition.put("candidate_binding_generation", 1); + transition.put("candidate_account_index_fence", ACCOUNT_FENCE); + transition.put("issuer_reservation_id", RESERVATION); + transition.put("status", "ABORTED"); + transition.put("inventory_revision", 5); + transition.put("admission_request_id", UUID.randomUUID()); + transition.put("admission_lease_id", UUID.randomUUID()); + transition.put("admission_lease_fence", 1); + transition.put("admission_lease_kind", "NEW_BINDING"); + transition.put("admission_lease_digest", RAW_DIGEST); + transition.put("admission_lease_evidence", "{\"controlledHistoricalAccountAbort\":true}"); + transition.put("admission_lease_expires_at", 1); + transition.put("admission_orphan_cleanup_id", UUID.randomUUID()); + transition.put("admission_target_namespace", "test"); + transition.put("admission_target_tenant_slug", "historical-tenant"); + transition.put("admission_target_tenant_id", TENANT); + transition.put("admission_target_world_slug", "historical-world"); + transition.put("admission_target_world_display_name", "Historical world"); + transition.put("admission_target_realm_id", UUID.randomUUID()); + transition.put("admission_target_realm_slug", "historical-realm"); + transition.put("admission_target_realm_display_name", "Historical realm"); + transition.put("admission_target_game_session_tenant_id", 1L); + transition.put("admission_target_game_instance_id", 1L); + transition.put("admission_target_playable_state_namespace_id", NAMESPACE); + transition.put("admission_target_playable_state_scope", "SHARED"); + transition.put("admission_target_canonical_game_instance_id", INSTANCE); + transition.put("admission_target_canonical_version_id", UUID.randomUUID()); + transition.put("admission_target_runtime_version_id", 1L); + transition.put("admission_target_catalog_revision", 1L); + transition.put("admission_target_pointer_version", 1L); + transition.put("admission_target_pointer_snapshot_digest", RAW_DIGEST); + transition.put("admission_target_active_world_epoch", 1L); + transition.put( + "admission_target_initial_admission_request_id", "controlled-historical-request"); + transition.put("admission_target_initial_admission_request_digest", RAW_DIGEST); + transition.put("admission_target_origin_kind", "NO_PRIOR_POINTER"); + transition.put("admission_target_hold_id", UUID.randomUUID()); + transition.put("admission_target_hold_fence", UUID.randomUUID()); + transition.put("admission_target_hold_binding_digest", DIGEST); + transition.put("admission_target_audit_event_id", 1L); + transition.put("admission_target_owner_proof_digest", DIGEST); + transition.put("admission_target_owner_proof_outcome", "COMMITTED"); + transition.put("admission_target_positive_durable_abort", false); + transition.put( + "admission_target_terminal_at", OffsetDateTime.parse("2026-10-26T00:00:00Z")); + transition.put("admission_target_character_creation_policy", "{}"); + insert(tx, "binding_transition", transition); + + Map reservation = new LinkedHashMap<>(candidate); + reservation.remove("issuer_partition_id"); + reservation.remove("account_index_fence"); + reservation.remove("issuer_reservation_id"); + reservation.remove("account_index_state"); + reservation.remove("issuer_index_state"); + reservation.put("reservation_id", RESERVATION); + reservation.put("partition_id", 0); + reservation.put("lifecycle", "RELEASE_PENDING"); + reservation.put("reservation_fence", UUID.randomUUID()); + reservation.put("issuer_coverage_operation_id", UUID.randomUUID()); + reservation.put("issuer_coverage_operation_fence", 1); + reservation.put("coverage_fence", 1); + reservation.put("inventory_snapshot_revision", 1); + insert(tx, "issuer_partition_reservation", reservation); + + Map accountObligation = new LinkedHashMap<>(); + accountObligation.put("transition_id", TRANSITION); + accountObligation.put("obligation_ordinal", 0); + accountObligation.put("binding_ref", BINDING_REF); + accountObligation.put("account_id", ACCOUNT); + accountObligation.put("tenant_id", TENANT); + accountObligation.put("action", "ADD_OR_RETAIN"); + accountObligation.put("binding_generation", 1); + accountObligation.put("account_index_fence", ACCOUNT_FENCE); + accountObligation.put("execution_phase", "BEFORE_FINAL_CAS"); + accountObligation.put("status", "ACKNOWLEDGED"); + accountObligation.put("inventory_revision", 5); + accountObligation.put("projection_state", "PRESENT_AWAITING_COVERAGE"); + accountObligation.put("projection_member", MEMBER); + accountObligation.put("projection_inventory_revision", 4); + insert(tx, "binding_account_index_obligation", accountObligation); + insert( + tx, + "binding_issuer_index_obligation", + Map.of( + "transition_id", + TRANSITION, + "binding_ref", + BINDING_REF, + "binding_generation", + 1, + "reservation_id", + RESERVATION, + "status", + "REQUIRED", + "inventory_revision", + 5)); + Map region = new LinkedHashMap<>(); + for (String key : + List.of( + "transition_id", + "binding_ref", + "binding_generation", + "account_id", + "tenant_id", + "game_instance_id", + "runtime_game_instance_id", + "session_id", + "region_id", + "region_epoch", + "inventory_revision")) { + region.put(key, candidate.get(key)); + } + region.put("status", "REQUIRED"); + insert(tx, "binding_region_bridge_obligation", region); + + Map repair = new LinkedHashMap<>(); + repair.put("operation_id", UUID.randomUUID()); + repair.put("transition_id", TRANSITION); + repair.put("obligation_ordinal", 0); + repair.put("operation_fence", 1); + repair.put("coverage_fence", UUID.randomUUID()); + repair.put("inventory_snapshot_revision", 2); + repair.put("binding_ref", BINDING_REF); + repair.put("account_id", ACCOUNT); + repair.put("tenant_id", TENANT); + repair.put("binding_generation", 1); + repair.put("account_index_fence", ACCOUNT_FENCE); + repair.put("original_action", "ADD_OR_RETAIN"); + repair.put("original_execution_phase", "BEFORE_FINAL_CAS"); + repair.put("original_status", "REQUIRED"); + repair.put("original_inventory_revision", 1); + repair.put("original_projection_state", "REQUIRED"); + repair.put("desired_action", "ADD_OR_RETAIN"); + repair.put("member", MEMBER); + repair.put("account_control_state", "NO_ACTIVE_ACCOUNT_WIDE_FLOW"); + repair.put("account_control_epoch", 0); + repair.put("status", "ACKNOWLEDGED"); + repair.put("coverage_generation", 3); + repair.put("readback_state", "PRESENT"); + repair.put("readback_member", MEMBER); + repair.put("completed_inventory_revision", 4); + insert(tx, "account_member_repair_operation", repair); + }); + } + + private static void seedLaterControlledAcquisitionIntent(DSLContext dsl) { + UUID intent = UUID.randomUUID(); + UUID fence = UUID.randomUUID(); + Map operation = new LinkedHashMap<>(); + operation.put("operation_id", intent); + operation.put("request_id", UUID.randomUUID()); + operation.put("account_id", ACCOUNT); + operation.put("operation_fence", 1); + operation.put("planned_account_admission_fence", fence); + operation.put("inventory_snapshot_revision", 5); + operation.put("legacy_cohort_id", UUID.randomUUID()); + operation.put("legacy_owner_operation_id", UUID.randomUUID()); + operation.put("legacy_writer_fence", UUID.randomUUID()); + operation.put("legacy_source_snapshot_revision", 1); + operation.put("legacy_canonical_inventory_revision", 1); + operation.put("legacy_namespace_index_readback_revision", 1); + operation.put("legacy_evidence_digest", DIGEST); + operation.put("intent_state", "ACQUISITION_INTENT"); + operation.put("cohort_row_count", 0L); + operation.put("cohort_digest", DIGEST); + operation.put("barrier_target_count", 0L); + operation.put("barrier_target_digest", DIGEST); + insert(dsl, "account_admission_fence_intent", operation); + dsl.execute( + "UPDATE " + + PREFIX + + "account_coverage_control SET state = 'ACQUISITION_INTENT'," + + " last_operation_fence = 1, current_operation_fence = 1," + + " current_fence_intent_id = ?, account_admission_fence = ?, inventory_snapshot_revision = 5" + + " WHERE account_id = ?", + intent, + fence, + ACCOUNT); + } + + private static void advanceRetainedRevision(DSLContext dsl) { + dsl.transaction( + configuration -> { + DSLContext tx = DSL.using(configuration); + tx.execute("UPDATE " + PREFIX + "binding_inventory_clock SET inventory_revision = 6"); + for (String table : RETAINED_TABLES.subList(0, 6)) { + tx.execute("UPDATE " + PREFIX + table + " SET inventory_revision = 6"); + } + }); + } + + private static Map> rows(DSLContext dsl, boolean immutableOnly) { + Map> rows = new LinkedHashMap<>(); + for (String table : RETAINED_TABLES) { + String expression = "to_jsonb(retained)"; + if (immutableOnly && !table.equals("account_member_repair_operation")) { + expression += " - 'inventory_revision'"; + } + rows.put( + table, + dsl.fetch( + "SELECT (" + + expression + + ")::text AS image FROM " + + PREFIX + + table + + " retained ORDER BY 1") + .getValues("image", String.class)); + } + for (String table : + List.of( + "account_coverage_control", + "account_admission_fence_intent", + "account_member_repair_control")) { + rows.put( + table, + dsl.fetch( + "SELECT to_jsonb(retained)::text AS image FROM " + + PREFIX + + table + + " retained ORDER BY 1") + .getValues("image", String.class)); + } + return rows; + } + + private static void insert(DSLContext dsl, String table, Map values) { + Map, Object> fields = new LinkedHashMap<>(); + values.forEach((column, value) -> fields.put(DSL.field(DSL.name(column)), value)); + dsl.insertInto(DSL.table(DSL.name(PREFIX + table))).set(fields).execute(); + } + + private static List history(DSLContext dsl) { + return dsl.fetch( + "SELECT to_jsonb(history_row)::text AS image FROM flyway_schema_history history_row" + + " ORDER BY installed_rank") + .getValues("image", String.class); + } + + private static Flyway flyway(DriverManagerDataSource dataSource, String schema, String target) { + return Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations( + "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize(), + "filesystem:" + + Path.of("../common-saga/src/main/resources/db/migration/saga") + .toAbsolutePath() + .normalize()) + .target(MigrationVersion.fromVersion(target)) + .load(); + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountGameplayAdmissionLeaseClientTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountGameplayAdmissionLeaseClientTest.java index fe2c51762b..8168fe8b97 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountGameplayAdmissionLeaseClientTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountGameplayAdmissionLeaseClientTest.java @@ -21,7 +21,6 @@ import java.security.MessageDigest; import java.time.Instant; import java.util.ArrayList; -import java.util.Base64; import java.util.HexFormat; import java.util.LinkedHashMap; import java.util.List; @@ -34,17 +33,12 @@ import net.firedevops.firemud.account.v1.AccountGameplayAdmissionLeaseResponse; import net.firedevops.firemud.account.v1.AccountGameplayAdmissionLeaseServiceGrpc; import net.firedevops.firemud.account.v1.AcquireGameplayAdmissionLeaseRequest; -import net.firedevops.firemud.account.v1.ConfirmOriginalNewGameplayAdmissionRequest; import net.firedevops.firemud.account.v1.FinalizeGameplayAdmissionLeaseRequest; -import net.firedevops.firemud.account.v1.IssueOriginalNewGameplayCredentialRequest; -import net.firedevops.firemud.account.v1.OriginalNewAdmissionConfirmationResponse; import net.firedevops.firemud.account.v1.ReadGameplayAdmissionLeaseRequest; import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseGrpcCodec; import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseGrpcCodec.AcquireRequest; -import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseGrpcCodec.OriginalAckReceiptEvidence; import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseGrpcCodec.OriginalLeaseRequest; -import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseGrpcCodec.OriginalNewCredential; import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseGrpcCodec.State; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.Candidate; @@ -57,7 +51,6 @@ import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; import net.firedevops.firemud.common.grpc.GrpcRequestBytePolicy; -import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold; import net.firedevops.firemud.test.LoopbackMtlsTestPki; @@ -66,7 +59,6 @@ import org.junit.jupiter.api.Timeout; import org.junit.jupiter.api.io.TempDir; import org.springframework.transaction.support.TransactionSynchronizationManager; -import tools.jackson.databind.json.JsonMapper; /** Controlled Account peer transport proof; the returned lease is codec evidence only. */ @Timeout(60) @@ -84,7 +76,6 @@ class AccountGameplayAdmissionLeaseClientTest { private static final UUID HOLD_FENCE = UUID.fromString("66666666-6666-4666-8666-666666666666"); private static final UUID DECISION_ID = UUID.fromString("77777777-7777-4777-8777-777777777777"); private static final String HIGH = "9007199254740993"; - private static final JsonMapper JSON = JsonMapper.builder().build(); @TempDir static Path directory; private static LoopbackMtlsTestPki.Pki pki; @@ -231,145 +222,6 @@ public void abortGameplayAdmissionLease( } } - @Test - void originalNewRpcCarriesOpaqueCredentialAndConfirmsOnlyAccountReadbackAnchors() - throws Exception { - var observed = new CopyOnWriteArrayList(); - var deadlines = new CopyOnWriteArrayList(); - var issuedRequests = new CopyOnWriteArrayList(); - var confirmationRequests = - new CopyOnWriteArrayList(); - byte[] handle = new byte[32]; - java.util.Arrays.fill(handle, (byte) 0x2a); - Server server = - server( - "account-server", - new AccountGameplayAdmissionLeaseServiceGrpc - .AccountGameplayAdmissionLeaseServiceImplBase() { - @Override - public void issueOriginalNewGameplayCredential( - IssueOriginalNewGameplayCredentialRequest request, - StreamObserver observer) { - capture(observed, deadlines); - issuedRequests.add(request); - try { - var parsed = - AccountGameplayAdmissionLeaseGrpcCodec.parseIssueOriginalNewCredentialRequest( - request); - var lease = parsed.originalLeaseEvidence(); - Map carrier = lease.carrier(); - Map scope = object(carrier, "bindingScope"); - Map claims = testBoundClaims(lease); - String compactJwt = testCompactJwt(claims); - UUID lineage = UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); - UUID tokenJti = UUID.fromString("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"); - OriginalNewCredential credential = - AccountGameplayAdmissionLeaseGrpcCodec.originalNewCredential( - compactJwt, - handle, - lineage, - tokenJti, - jwtSha256(compactJwt), - Long.parseLong((String) carrier.get("issuanceFence")), - UUID.fromString((String) carrier.get("leaseId")), - lease.leaseFence().longValueExact(), - "102", - checkpointsSha256(carrier.get("outboxCheckpoints"))); - var ack = - OriginalAckReceiptEvidence.fromFields( - 1, - UUID.fromString((String) carrier.get("requestId")), - UUID.fromString((String) scope.get("accountId")), - UUID.fromString((String) carrier.get("leaseId")), - lease.leaseFence().longValueExact(), - lease.sha256(), - DECISION_ID, - 1_015_000L, - "101", - 1_014_999L, - "102"); - observer.onNext( - AccountGameplayAdmissionLeaseGrpcCodec.toIssueOriginalNewCredentialResponse( - parsed, lease, State.COMMITTED, DECISION_ID, ack, credential)); - observer.onCompleted(); - credential.close(); - } catch (RuntimeException malformed) { - observer.onError(Status.INVALID_ARGUMENT.asRuntimeException()); - } - } - - @Override - public void confirmOriginalNewGameplayAdmission( - ConfirmOriginalNewGameplayAdmissionRequest request, - StreamObserver observer) { - capture(observed, deadlines); - confirmationRequests.add(request); - var parsed = - AccountGameplayAdmissionLeaseGrpcCodec - .parseConfirmOriginalNewGameplayAdmissionRequest(request); - var lease = parsed.originalLeaseEvidence(); - observer.onNext( - AccountGameplayAdmissionLeaseGrpcCodec - .toConfirmOriginalNewGameplayAdmissionResponse( - parsed, - UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), - UUID.fromString((String) lease.carrier().get("leaseId")), - lease.leaseFence().longValueExact(), - 1_020_000L, - 1_320_000L, - "c".repeat(64))); - observer.onCompleted(); - } - }); - try (var client = client(server)) { - client.init(); - byte[] originalLease = lease().canonicalJson().getBytes(StandardCharsets.UTF_8); - OriginalNewCredential received = - client.issueOriginalNewBoundGameplayCredential(JWT, originalLease); - byte[] receivedHandle = received.opaqueRebindHandle(); - try { - assertThat(receivedHandle).containsExactly(handle); - } finally { - java.util.Arrays.fill(receivedHandle, (byte) 0); - } - assertThat(received.toString()).doesNotContain(JWT, HexFormat.of().formatHex(handle)); - var confirmation = client.confirmOriginalNewGameplayAdmission(JWT, originalLease); - - assertThat(observed).containsExactly(GAME_SESSION_PEER, GAME_SESSION_PEER); - assertThat(issuedRequests) - .singleElement() - .satisfies( - request -> { - assertThat(request.getPresentedInitialGsaCompactJwt(0)).isEqualTo(JWT); - assertThat(request.getOriginalLeaseEvidenceUtf8(0).toByteArray()) - .containsExactly(originalLease); - }); - assertThat(confirmation.lineageId()) - .isEqualTo(UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa")); - assertThat(confirmation.continuityExpiresAtMillis()).isEqualTo(1_320_000L); - assertThat(confirmationRequests) - .singleElement() - .satisfies( - request -> { - assertThat(request.getPresentedInitialGsaCompactJwt(0)).isEqualTo(JWT); - assertThat(request.getOriginalLeaseEvidenceUtf8(0).toByteArray()) - .containsExactly(originalLease); - }); - assertThat(deadlines) - .hasSize(2) - .allSatisfy( - deadline -> { - long remainingMillis = deadline.timeRemaining(TimeUnit.MILLISECONDS); - assertThat(remainingMillis).isPositive().isLessThanOrEqualTo(5_000L); - }); - received.close(); - java.util.Arrays.fill(originalLease, (byte) 0); - } finally { - java.util.Arrays.fill(handle, (byte) 0); - stop(server); - } - } - @Test void wrongAccountRoleAndNamespaceAreRejectedBeforeServerHandlerReceivesJwt() throws Exception { for (String identity : List.of("wrong-role", "foreign-namespace")) { @@ -878,64 +730,6 @@ private static AccountGameplayAdmissionLeaseEvidence lease() { return AccountGameplayAdmissionLeaseEvidence.fromCarrier(value); } - private static Map testBoundClaims(AccountGameplayAdmissionLeaseEvidence lease) { - Map carrier = lease.carrier(); - Map scope = object(carrier, "bindingScope"); - Map baseline = object(carrier, "membershipBaseline"); - long issuedAt = Instant.now().getEpochSecond(); - Map claims = new LinkedHashMap<>(); - claims.put("iss", GameSessionAccountDelegationProfile.ISSUER); - claims.put("sub", scope.get("accountId")); - claims.put("jti", "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"); - claims.put("accountId", scope.get("accountId")); - claims.put("aud", GameSessionAccountDelegationProfile.AUDIENCE); - claims.put("iat", issuedAt); - claims.put("nbf", issuedAt); - claims.put("exp", issuedAt + 120L); - claims.put("tokenGeneration", "1"); - claims.put("authorityTuple", carrier.get("authorityTuple")); - claims.put("membershipVersion", baseline.get("membershipVersion")); - claims.put("issuanceFence", carrier.get("issuanceFence")); - claims.put("tenantId", scope.get("tenantId")); - return claims; - } - - private static String testCompactJwt(Map claims) { - try { - String header = - Base64.getUrlEncoder() - .withoutPadding() - .encodeToString( - "{\"alg\":\"RS256\",\"kid\":\"controlled-test\"}" - .getBytes(StandardCharsets.UTF_8)); - String payload = - Base64.getUrlEncoder().withoutPadding().encodeToString(JSON.writeValueAsBytes(claims)); - return header + "." + payload + ".c2ln"; - } catch (Exception malformed) { - throw new IllegalStateException("Controlled JWT fixture could not be encoded", malformed); - } - } - - private static String checkpointsSha256(Object checkpoints) { - byte[] canonical = null; - try { - canonical = Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(checkpoints)); - return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(canonical)); - } catch (Exception malformed) { - throw new IllegalStateException( - "Controlled checkpoint fixture could not be hashed", malformed); - } finally { - if (canonical != null) java.util.Arrays.fill(canonical, (byte) 0); - } - } - - private static Map object(Map source, String field) { - Object value = source.get(field); - if (!(value instanceof Map object)) - throw new IllegalArgumentException("Fixture map required"); - return object; - } - private static String jwtSha256(String jwt) { try { return HexFormat.of() diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewAuthenticatedSessionTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewAuthenticatedSessionTest.java deleted file mode 100644 index 5a1918e2b6..0000000000 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewAuthenticatedSessionTest.java +++ /dev/null @@ -1,709 +0,0 @@ -package net.firedevops.firemud.gamesession.repository; - -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.ArrayNode; -import com.fasterxml.jackson.databind.node.ObjectNode; -import java.math.BigInteger; -import java.nio.charset.StandardCharsets; -import java.security.KeyPair; -import java.security.KeyPairGenerator; -import java.security.MessageDigest; -import java.security.Signature; -import java.time.Clock; -import java.time.Duration; -import java.time.Instant; -import java.time.ZoneOffset; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Base64; -import java.util.HexFormat; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.UUID; -import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; -import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseGrpcCodec; -import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; -import net.firedevops.firemud.common.security.AccountPublicJwksCache; -import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; -import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingIdentity; -import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionOwnerProof.Outcome; -import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionRequest.OriginKind; -import net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; - -class CanonicalGameplayOriginalNewAuthenticatedSessionTest { - private static final ObjectMapper JSON = new ObjectMapper(); - private static final Clock CLOCK = - Clock.fixed(Instant.parse("2026-10-27T00:00:00Z"), ZoneOffset.UTC); - private static final UUID ACCOUNT_ID = uuid("11111111-1111-4111-8111-111111111111"); - private static final UUID TENANT_ID = uuid("22222222-2222-4222-8222-222222222222"); - private static final UUID PLAYABLE_NAMESPACE_ID = uuid("33333333-3333-4333-8333-333333333333"); - private static final UUID CHARACTER_ID = uuid("44444444-4444-4444-8444-444444444444"); - private static final UUID GAME_INSTANCE_ID = uuid("55555555-5555-4555-8555-555555555555"); - private static final UUID SESSION_ID = uuid("66666666-6666-4666-8666-666666666666"); - private static final UUID REGION_ID = uuid("77777777-7777-4777-8777-777777777777"); - private static final UUID REALM_ID = uuid("88888888-8888-4888-8888-888888888888"); - private static final UUID VERSION_ID = uuid("99999999-9999-4999-8999-999999999999"); - private static final UUID REQUEST_ID = uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); - private static final UUID LEASE_ID = uuid("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"); - private static final UUID BINDING_DECISION_ID = uuid("cccccccc-cccc-4ccc-8ccc-cccccccccccc"); - private static final UUID RESERVATION_ID = uuid("dddddddd-dddd-4ddd-8ddd-dddddddddddd"); - private static final UUID RESERVATION_FENCE = uuid("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"); - private static final UUID ACCOUNT_INDEX_FENCE = uuid("ffffffff-ffff-4fff-8fff-ffffffffffff"); - private static final UUID COVERAGE_OPERATION_ID = uuid("10101010-1010-4010-8010-101010101010"); - private static final UUID LOGIN_JTI = uuid("12121212-1212-4212-8212-121212121212"); - private static final UUID LINEAGE_ID = uuid("13131313-1313-4313-8313-131313131313"); - private static final UUID BOUND_JTI = uuid("14141414-1414-4414-8414-141414141414"); - private static final UUID OTHER_ID = uuid("15151515-1515-4515-8515-151515151515"); - private static final String NAMESPACE = "test"; - private static final String GAME_SESSION_PEER = - "spiffe://firemud/ns/test/sa/game-session-service"; - private static final String HANDLE_HEX = - "00112233445566778899aabbccddeeff00112233445566778899aabbccddeeff"; - private static final byte[] HANDLE = HexFormat.of().parseHex(HANDLE_HEX); - private static final String ONE = "1"; - private static final String TOKEN_FENCE = "7"; - private static final long NOW_SECONDS = CLOCK.instant().getEpochSecond(); - private static final long SESSION_DURATION_MILLIS = 120_000L; - private static KeyPair ACCOUNT_SIGNING_KEYS; - - @BeforeAll - static void generateControlledAccountSigningKey() throws Exception { - KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); - generator.initialize(3072); - ACCOUNT_SIGNING_KEYS = generator.generateKeyPair(); - } - - @Test - void buildsNonPersistableTemplateAndAcceptsExactFinalCasReadback() throws Exception { - try (Fixture fixture = fixture(claims -> {}); - var template = template(fixture)) { - byte[] templateBytes = template.finalCasTemplateBytes(); - String templateJson = new String(templateBytes, StandardCharsets.UTF_8); - assertThat(templateJson) - .contains("__ORIGINAL_NEW_ADMISSION_AT_MS__") - .contains("__ORIGINAL_NEW_CONTINUITY_EXPIRES_AT_MS__") - .doesNotContain(fixture.compactJwt) - .doesNotContain("\"lineageId\"") - .doesNotContain("\"authTokenJti\""); - assertThatThrownBy( - () -> - CanonicalGameplayOriginalNewAuthenticatedSession.parseFinalized( - templateBytes, CLOCK)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("Canonical ORIGINAL_NEW authenticated session is invalid"); - - long admissionAt = CLOCK.millis() + 100L; - byte[] finalBytes = finalizeTemplate(templateBytes, admissionAt, SESSION_DURATION_MILLIS); - try (var finalized = template.requireFinalizedReadback(finalBytes)) { - assertThat(finalized.originalCandidate().bindingDecisionId()) - .isEqualTo(BINDING_DECISION_ID); - assertThat(finalized.admissionAtMillis()).isEqualTo(admissionAt); - assertThat(finalized.continuityBindingExpiresAtMillis()) - .isEqualTo(admissionAt + SESSION_DURATION_MILLIS); - assertThat(finalized.authTokenHash()).isEqualTo(hash(fixture.compactJwt)); - assertThat(finalized.authTokenIssuedAt()).isEqualTo(NOW_SECONDS); - assertThat(finalized.authTokenExpiresAt()).isEqualTo(NOW_SECONDS + 240L); - assertThat(finalized.tokenGeneration()).isEqualTo("1"); - assertThat(finalized.issuanceFence()).isEqualTo(TOKEN_FENCE); - assertThat(finalized.canonicalSessionDurationMillis()).isEqualTo(SESSION_DURATION_MILLIS); - byte[] returnedHandle = finalized.opaqueRebindHandle(); - try { - assertThat(returnedHandle).containsExactly(HANDLE); - } finally { - Arrays.fill(returnedHandle, (byte) 0); - } - byte[] exactBytes = finalized.canonicalBytes(); - try { - assertThat(exactBytes).containsExactly(finalBytes); - } finally { - Arrays.fill(exactBytes, (byte) 0); - } - assertThat(finalized.toString()).doesNotContain(HANDLE_HEX, fixture.compactJwt); - } finally { - Arrays.fill(templateBytes, (byte) 0); - Arrays.fill(finalBytes, (byte) 0); - } - } - } - - @Test - void accountSignatureAndBoundClaimsMustMatchTheOriginalLeaseAndCredential() throws Exception { - try (Fixture valid = fixture(claims -> {})) { - try (var template = template(valid)) { - assertThat(template.toString()).doesNotContain(valid.compactJwt, HANDLE_HEX); - } - } - - try (Fixture unscoped = - fixture( - claims -> { - claims.remove("tenantId"); - claims.put("authorityTuple", unscopedTuple()); - claims.put("membershipVersion", Map.of()); - })) { - assertVerifierDenies(unscoped); - } - - try (Fixture mismatchedTenant = - fixture(claims -> claims.put("tenantId", OTHER_ID.toString()))) { - assertVerifierDenies(mismatchedTenant); - } - - try (Fixture roles = fixture(claims -> claims.put("globalRoles", List.of()))) { - assertVerifierDenies(roles); - } - - try (Fixture expired = - fixture( - claims -> { - claims.put("exp", NOW_SECONDS - 1L); - claims.put("nbf", NOW_SECONDS - 5L); - })) { - assertVerifierDenies(expired); - } - - try (Fixture futureIat = - fixture( - claims -> { - claims.put("iat", NOW_SECONDS + 6L); - claims.put("nbf", NOW_SECONDS + 6L); - claims.put("exp", NOW_SECONDS + 100L); - })) { - assertVerifierDenies(futureIat); - } - - try (Fixture wrongJti = fixture(claims -> claims.put("jti", OTHER_ID.toString()))) { - assertVerifierDenies(wrongJti); - } - - KeyPairGenerator wrongGenerator = KeyPairGenerator.getInstance("RSA"); - wrongGenerator.initialize(2048); - try (Fixture wrongSignature = fixture(claims -> {}, wrongGenerator.generateKeyPair())) { - assertVerifierDenies(wrongSignature); - } - - try (Fixture valid = fixture(claims -> {}); - var wrongHash = - AccountGameplayAdmissionLeaseGrpcCodec.originalNewCredential( - valid.compactJwt, - HANDLE, - LINEAGE_ID, - BOUND_JTI, - "f".repeat(64), - Long.parseLong(TOKEN_FENCE), - LEASE_ID, - 1L, - "42", - hash( - canonical( - valid.candidate.leaseEvidence().carrier().get("outboxCheckpoints"))))) { - assertThatThrownBy(() -> valid.verifier.verify(valid.candidate, wrongHash)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("Original NEW bound credential is invalid"); - } - - try (Fixture wrongFence = fixture(claims -> claims.put("issuanceFence", "8"))) { - assertVerifierDenies(wrongFence); - } - - try (Fixture wrongMembership = - fixture(claims -> claims.put("membershipVersion", Map.of(TENANT_ID.toString(), "10")))) { - assertVerifierDenies(wrongMembership); - } - - try (Fixture wrongTuple = - fixture( - claims -> - claims.put( - "authorityTuple", - Map.of( - "issuerAuthGeneration", - "1", - "accountAuthorityGeneration", - "1", - "tenantAuthorityGeneration", - Map.of(TENANT_ID.toString(), "3"), - "membershipAuthorityGeneration", - Map.of(TENANT_ID.toString(), "3"), - "privateRealmGrantVersions", - List.of())))) { - assertVerifierDenies(wrongTuple); - } - } - - @Test - void strictFinalReaderRejectsUnknownDuplicateTrailingMalformedAndOversizeJson() throws Exception { - try (Fixture fixture = fixture(claims -> {}); - var template = template(fixture)) { - byte[] candidate = template.finalCasTemplateBytes(); - byte[] complete = finalizeTemplate(candidate, CLOCK.millis() + 100L, SESSION_DURATION_MILLIS); - try { - assertDenied(addRootField(complete, "lineageId", "not-persisted")); - String duplicate = - new String(complete, StandardCharsets.UTF_8) - .replaceFirst("\\{", "{\"schemaVersion\":2,"); - assertDenied(duplicate.getBytes(StandardCharsets.UTF_8)); - byte[] trailing = Arrays.copyOf(complete, complete.length + 3); - trailing[complete.length] = ' '; - trailing[complete.length + 1] = '{'; - trailing[complete.length + 2] = '}'; - assertDenied(trailing); - assertDenied(new byte[] {(byte) 0xc3, (byte) 0x28}); - assertDenied( - new byte[CanonicalGameplayOriginalNewAuthenticatedSession.MAX_SESSION_BYTES + 1]); - } finally { - Arrays.fill(candidate, (byte) 0); - Arrays.fill(complete, (byte) 0); - } - } - } - - @Test - void strictFinalReaderRejectsMissingNullPlaceholderAndChangedAnchors() throws Exception { - try (Fixture fixture = fixture(claims -> {}); - var template = template(fixture)) { - byte[] templateBytes = template.finalCasTemplateBytes(); - byte[] complete = - finalizeTemplate(templateBytes, CLOCK.millis() + 100L, SESSION_DURATION_MILLIS); - try { - assertDenied(mutate(complete, root -> root.remove("rebindHandle"))); - assertDenied(mutate(complete, root -> root.putNull("membershipBaseline"))); - assertDenied(mutate(complete, root -> root.put("bindingGeneration", "2"))); - assertDenied(mutate(complete, root -> root.put("schemaVersion", 4294967298L))); - assertDenied(mutate(complete, root -> root.put("issuanceFence", "8"))); - assertDenied(mutate(complete, root -> root.put("tokenGeneration", "2"))); - assertDenied(mutate(complete, root -> root.put("continuityBindingExpiresAt", "1"))); - assertDenied(mutate(complete, root -> root.put("admissionAt", "9223372036854775807"))); - assertDenied( - mutate( - complete, - root -> ((ObjectNode) root.get("originalCandidate")).put("unexpected", "field"))); - assertDenied( - mutate( - complete, - root -> - ((ObjectNode) root.get("membershipBaseline")) - .put("membershipAuthorityGeneration", "8"))); - assertDenied( - mutate( - complete, - root -> - ((ObjectNode) root.get("authorityTuple")) - .put("accountAuthorityGeneration", "2"))); - assertDenied( - mutate( - complete, root -> ((ArrayNode) root.get("outboxCheckpoints")).add("unexpected"))); - } finally { - Arrays.fill(templateBytes, (byte) 0); - Arrays.fill(complete, (byte) 0); - } - } - } - - @Test - void finalCasReadbackAllowsOnlyAdmissionAndContinuityTimeSlotsToChange() throws Exception { - try (Fixture fixture = fixture(claims -> {}); - var template = template(fixture)) { - byte[] templateBytes = template.finalCasTemplateBytes(); - byte[] complete = - finalizeTemplate(templateBytes, CLOCK.millis() + 100L, SESSION_DURATION_MILLIS); - byte[] changed = - mutate( - complete, - root -> { - long admissionAt = Long.parseLong(root.get("admissionAt").textValue()); - root.put("canonicalSessionDurationMillis", "119999"); - root.put("continuityBindingExpiresAt", Long.toString(admissionAt + 119_999L)); - }); - try { - assertThatThrownBy(() -> template.requireFinalizedReadback(changed)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("Canonical ORIGINAL_NEW authenticated session is invalid"); - } finally { - Arrays.fill(templateBytes, (byte) 0); - Arrays.fill(complete, (byte) 0); - Arrays.fill(changed, (byte) 0); - } - } - } - - private static void assertVerifierDenies(Fixture fixture) { - assertThatThrownBy(() -> template(fixture)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("Original NEW bound credential is invalid"); - } - - private static CanonicalGameplayOriginalNewAuthenticatedSession.Template template( - Fixture fixture) { - return CanonicalGameplayOriginalNewAuthenticatedSession.template( - fixture.candidate, fixture.credential, fixture.verifier, SESSION_DURATION_MILLIS); - } - - private static void assertDenied(byte[] bytes) { - try { - assertThatThrownBy( - () -> CanonicalGameplayOriginalNewAuthenticatedSession.parseFinalized(bytes, CLOCK)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("Canonical ORIGINAL_NEW authenticated session is invalid"); - } finally { - Arrays.fill(bytes, (byte) 0); - } - } - - private static byte[] finalizeTemplate(byte[] template, long admissionAt, long duration) - throws Exception { - ObjectNode root = (ObjectNode) JSON.readTree(template); - root.put("admissionAt", Long.toString(admissionAt)); - root.put("continuityBindingExpiresAt", Long.toString(Math.addExact(admissionAt, duration))); - return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(root)); - } - - private static byte[] mutate(byte[] input, java.util.function.Consumer mutation) - throws Exception { - ObjectNode root = (ObjectNode) JSON.readTree(input); - mutation.accept(root); - return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(root)); - } - - private static byte[] addRootField(byte[] input, String name, String value) throws Exception { - return mutate(input, root -> root.put(name, value)); - } - - private static Fixture fixture(java.util.function.Consumer> mutateClaims) - throws Exception { - return fixture(mutateClaims, ACCOUNT_SIGNING_KEYS); - } - - private static Fixture fixture( - java.util.function.Consumer> mutateClaims, KeyPair signingKey) - throws Exception { - AccountGameplayAdmissionLeaseEvidence lease = lease(); - CanonicalGameplayOriginalNewCandidate candidate = candidate(lease); - Map claims = boundClaims(lease); - mutateClaims.accept(claims); - String compactJwt = sign(claims, signingKey); - String tokenHash = hash(compactJwt); - String checkpointsSha256 = hash(canonical(lease.carrier().get("outboxCheckpoints"))); - AccountGameplayAdmissionLeaseGrpcCodec.OriginalNewCredential credential = - AccountGameplayAdmissionLeaseGrpcCodec.originalNewCredential( - compactJwt, - HANDLE, - LINEAGE_ID, - BOUND_JTI, - tokenHash, - Long.parseLong(TOKEN_FENCE), - LEASE_ID, - 1L, - "42", - checkpointsSha256); - return new Fixture(candidate, credential, compactJwt, verifier()); - } - - private static CanonicalGameplayOriginalNewCandidate candidate( - AccountGameplayAdmissionLeaseEvidence lease) { - CanonicalGameplayBindingIdentity binding = - new CanonicalGameplayBindingIdentity( - ACCOUNT_ID, - TENANT_ID, - PLAYABLE_NAMESPACE_ID, - CHARACTER_ID, - "SHARED", - GAME_INSTANCE_ID, - 77L, - SESSION_ID.toString(), - REGION_ID, - BigInteger.ONE, - GameSessionAccountDelegationProfile.ISSUER, - BigInteger.ONE, - BigInteger.ONE, - BigInteger.ONE, - BigInteger.ONE); - CanonicalPlayableTarget target = - new CanonicalPlayableTarget( - NAMESPACE, - "tenant", - TENANT_ID, - "world", - "World", - REALM_ID, - "realm", - "Realm", - 42L, - 77L, - PLAYABLE_NAMESPACE_ID, - "SHARED", - GAME_INSTANCE_ID, - VERSION_ID, - 3L, - 5L, - 6L, - "a".repeat(64), - 1L, - REQUEST_ID.toString(), - "b".repeat(64), - OriginKind.NO_PRIOR_POINTER, - null, - OTHER_ID, - RESERVATION_FENCE, - "sha256:" + "c".repeat(64), - 100L, - "sha256:" + "d".repeat(64), - Outcome.COMMITTED, - false, - Instant.parse("2026-10-26T00:00:00Z"), - "PRESEEDED_ONLY"); - var bindingRef = binding.bindingRef(); - var transition = - new CanonicalGameplayOriginalNewCandidate.TransitionSource( - BINDING_DECISION_ID, - bindingRef, - BigInteger.ONE, - RESERVATION_ID, - RESERVATION_FENCE, - ACCOUNT_INDEX_FENCE); - var reservation = - new CanonicalGameplayOriginalNewCandidate.ReservationSource( - RESERVATION_ID, - bindingRef, - BigInteger.ONE, - BINDING_DECISION_ID, - BigInteger.ZERO, - RESERVATION_FENCE, - COVERAGE_OPERATION_ID, - BigInteger.ONE, - BigInteger.ONE, - BigInteger.ONE); - return new CanonicalGameplayOriginalNewCandidate( - BINDING_DECISION_ID, lease, binding, target, transition, reservation); - } - - private static AccountGameplayAdmissionLeaseEvidence lease() { - Map value = new LinkedHashMap<>(); - value.put("schema", AccountGameplayAdmissionLeaseEvidence.SCHEMA); - value.put("schemaVersion", "1"); - value.put("mode", "PUBLIC_PRODUCTION"); - value.put("targetNamespace", NAMESPACE); - value.put("callerWorkload", GAME_SESSION_PEER); - value.put("requestId", REQUEST_ID.toString()); - value.put("leaseId", LEASE_ID.toString()); - value.put("leaseFence", ONE); - value.put("leaseKind", "NEW_BINDING"); - Map scope = new LinkedHashMap<>(); - scope.put("accountId", ACCOUNT_ID.toString()); - scope.put("tenantId", TENANT_ID.toString()); - scope.put("realmId", REALM_ID.toString()); - scope.put("worldSlug", "world"); - scope.put("realmSlug", "realm"); - scope.put("playableStateNamespaceId", PLAYABLE_NAMESPACE_ID.toString()); - scope.put("playableStateScope", "SHARED"); - scope.put("gameInstanceId", GAME_INSTANCE_ID.toString()); - scope.put("characterId", CHARACTER_ID.toString()); - scope.put("sessionId", SESSION_ID.toString()); - scope.put("bindingGeneration", ONE); - scope.put("catalogRevision", "5"); - scope.put("pointerVersion", "6"); - scope.put("regionId", REGION_ID.toString()); - scope.put("regionEpoch", ONE); - value.put("bindingScope", scope); - value.put( - "authorityTuple", - Map.of( - "issuerAuthGeneration", ONE, - "accountAuthorityGeneration", ONE, - "tenantAuthorityGeneration", Map.of(TENANT_ID.toString(), "2"), - "membershipAuthorityGeneration", Map.of(TENANT_ID.toString(), "3"), - "privateRealmGrantVersions", List.of())); - value.put("issuanceFence", TOKEN_FENCE); - value.put( - "membershipBaseline", - Map.of( - "membershipLifecycleState", - "ACTIVE", - "membershipVersion", - Map.of(TENANT_ID.toString(), "9"), - "membershipAuthorityGeneration", - "3")); - value.put("outboxCheckpoints", checkpoints()); - value.put( - "tokenIdentityEvidence", - Map.ofEntries( - Map.entry("accountId", ACCOUNT_ID.toString()), - Map.entry("operationId", OTHER_ID.toString()), - Map.entry("issuanceRequestId", REQUEST_ID.toString()), - Map.entry("tokenJti", LOGIN_JTI.toString()), - Map.entry("tokenSHA256", "e".repeat(64)), - Map.entry("tokenGeneration", ONE), - Map.entry("issuanceFence", TOKEN_FENCE), - Map.entry("tokenIdentityFence", ONE), - Map.entry("tokenProfile", GameSessionAccountDelegationProfile.PROFILE), - Map.entry("issuedAt", Long.toString(NOW_SECONDS - 1)), - Map.entry("notBefore", Long.toString(NOW_SECONDS - 1)), - Map.entry("expiresAt", Long.toString(NOW_SECONDS + 299)))); - value.put("evaluatedAt", Long.toString(CLOCK.millis())); - value.put("expiresAt", Long.toString(CLOCK.millis() + 15_000L)); - return AccountGameplayAdmissionLeaseEvidence.fromCarrier(value); - } - - private static List> checkpoints() { - List> result = new ArrayList<>(); - for (String suffix : - List.of( - "account/" + ACCOUNT_ID, - "issuer/" + GameSessionAccountDelegationProfile.ISSUER, - "membership/" + ACCOUNT_ID + "/" + TENANT_ID, - "tenant/" + TENANT_ID)) { - result.add( - Map.of( - "outboxStreamKey", - "account:auth-authority:v1:" + suffix, - "outboxSequence", - suffix.startsWith("membership/") || suffix.startsWith("tenant/") ? "9" : "0")); - } - return List.copyOf(result); - } - - private static Map boundClaims(AccountGameplayAdmissionLeaseEvidence lease) { - Map claims = new LinkedHashMap<>(); - claims.put("iss", GameSessionAccountDelegationProfile.ISSUER); - claims.put("sub", ACCOUNT_ID.toString()); - claims.put("jti", BOUND_JTI.toString()); - claims.put("accountId", ACCOUNT_ID.toString()); - claims.put("aud", GameSessionAccountDelegationProfile.AUDIENCE); - claims.put("iat", NOW_SECONDS); - claims.put("nbf", NOW_SECONDS); - claims.put("exp", NOW_SECONDS + 240L); - claims.put("tokenGeneration", ONE); - claims.put("authorityTuple", lease.carrier().get("authorityTuple")); - claims.put( - "membershipVersion", - ((Map) lease.carrier().get("membershipBaseline")).get("membershipVersion")); - claims.put("issuanceFence", TOKEN_FENCE); - claims.put("tenantId", TENANT_ID.toString()); - return claims; - } - - private static Map unscopedTuple() { - return Map.of( - "issuerAuthGeneration", ONE, - "accountAuthorityGeneration", ONE, - "tenantAuthorityGeneration", Map.of(), - "membershipAuthorityGeneration", Map.of(), - "privateRealmGrantVersions", List.of()); - } - - private static String sign(Map claims, KeyPair keyPair) throws Exception { - String header = - Base64.getUrlEncoder() - .withoutPadding() - .encodeToString( - "{\"alg\":\"RS256\",\"kid\":\"original-new-test\",\"typ\":\"JWT\"}" - .getBytes(StandardCharsets.UTF_8)); - String payload = - Base64.getUrlEncoder().withoutPadding().encodeToString(JSON.writeValueAsBytes(claims)); - String signingInput = header + "." + payload; - Signature signer = Signature.getInstance("SHA256withRSA"); - signer.initSign(keyPair.getPrivate()); - signer.update(signingInput.getBytes(StandardCharsets.US_ASCII)); - return signingInput - + "." - + Base64.getUrlEncoder().withoutPadding().encodeToString(signer.sign()); - } - - private static CanonicalGameplayOriginalNewBoundCredentialVerifier verifier() throws Exception { - var pin = - new AccountPublicJwksCache.SourceIdentity( - "test", - "cluster-a", - "11111111-1111-4111-8111-111111111111", - "test", - "22222222-2222-4222-8222-222222222222", - "33333333-3333-4333-8333-333333333333", - "binding-7", - "https://kubernetes.example:6443", - "a".repeat(64)); - var publicKey = (java.security.interfaces.RSAPublicKey) ACCOUNT_SIGNING_KEYS.getPublic(); - String jwks = - JSON.writeValueAsString( - Map.of( - "keys", - List.of( - Map.of( - "kty", - "RSA", - "use", - "sig", - "alg", - "RS256", - "kid", - "original-new-test", - "n", - Base64.getUrlEncoder() - .withoutPadding() - .encodeToString(unsigned(publicKey.getModulus().toByteArray())), - "e", - Base64.getUrlEncoder() - .withoutPadding() - .encodeToString( - unsigned(publicKey.getPublicExponent().toByteArray())))))); - var cache = - new AccountPublicJwksCache( - () -> - new AccountPublicJwksCache.PublicJwksSnapshot( - pin, jwks.getBytes(StandardCharsets.UTF_8)), - pin, - CLOCK, - Duration.ofSeconds(30)); - return new CanonicalGameplayOriginalNewBoundCredentialVerifier(cache, CLOCK); - } - - private static String canonical(Object value) throws Exception { - return new String( - Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)), - StandardCharsets.UTF_8); - } - - private static String hash(String value) throws Exception { - return hash(value.getBytes(StandardCharsets.US_ASCII)); - } - - private static String hash(byte[] value) throws Exception { - return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value)); - } - - private static byte[] unsigned(byte[] bytes) { - return bytes.length > 1 && bytes[0] == 0 ? Arrays.copyOfRange(bytes, 1, bytes.length) : bytes; - } - - private static UUID uuid(String value) { - return UUID.fromString(value); - } - - private static final class Fixture implements AutoCloseable { - private final CanonicalGameplayOriginalNewCandidate candidate; - private final AccountGameplayAdmissionLeaseGrpcCodec.OriginalNewCredential credential; - private final String compactJwt; - private final CanonicalGameplayOriginalNewBoundCredentialVerifier verifier; - - private Fixture( - CanonicalGameplayOriginalNewCandidate candidate, - AccountGameplayAdmissionLeaseGrpcCodec.OriginalNewCredential credential, - String compactJwt, - CanonicalGameplayOriginalNewBoundCredentialVerifier verifier) { - this.candidate = candidate; - this.credential = credential; - this.compactJwt = compactJwt; - this.verifier = verifier; - } - - @Override - public void close() { - credential.close(); - } - } -} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCandidateTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCandidateTest.java deleted file mode 100644 index 47d96cb69f..0000000000 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCandidateTest.java +++ /dev/null @@ -1,535 +0,0 @@ -package net.firedevops.firemud.gamesession.repository; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import java.math.BigInteger; -import java.nio.charset.StandardCharsets; -import java.time.Instant; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Comparator; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.UUID; -import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; -import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; -import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAccountCoverageEvidence; -import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAdmissionDecision; -import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingIdentity; -import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingInventoryEntry; -import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingProvisionalCasEvidence; -import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingTransitionSnapshot; -import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationDisposition; -import net.firedevops.firemud.gamesession.binding.CanonicalIssuerPartitionReservation; -import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionOwnerProof; -import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionRequest; -import net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget; -import org.junit.jupiter.api.Test; - -class CanonicalGameplayOriginalNewCandidateTest { - private static final UUID ACCOUNT = id(1); - private static final UUID TENANT = id(2); - private static final UUID REALM = id(3); - private static final UUID NAMESPACE = id(4); - private static final UUID GAME_INSTANCE = id(5); - private static final UUID CHARACTER = id(6); - private static final UUID SESSION = id(7); - private static final UUID REGION = id(8); - private static final UUID VERSION = id(9); - - @Test - void retainsExactNonAdmittingCandidateAndStableRetryBytes() { - Bundle prepared = bundle(CHARACTER, BigInteger.valueOf(7), "World", false); - CanonicalGameplayOriginalNewCandidate first = - CanonicalGameplayOriginalNewCandidate.fromOriginalSources( - provisionalEvidence( - prepared.identity(), prepared.bindingGeneration(), BigInteger.valueOf(20), false), - prepared.decision()); - CanonicalGameplayOriginalNewCandidate retry = - CanonicalGameplayOriginalNewCandidate.fromOriginalSources( - provisionalEvidence( - prepared.identity(), prepared.bindingGeneration(), BigInteger.valueOf(28), true), - prepared.decision()); - - assertThat(retry.canonicalBytes()).isEqualTo(first.canonicalBytes()); - assertThat(first.exactlyMatches(first.canonicalBytes())).isTrue(); - assertThat(first.matchesOriginalDecision(prepared.decision())).isTrue(); - assertThat(first.matchesProvisionalSources(preparedEvidence(prepared))).isTrue(); - assertThat( - first.matchesProvisionalSources( - provisionalEvidence( - prepared.identity(), - prepared.bindingGeneration(), - BigInteger.valueOf(28), - true))) - .isTrue(); - - CanonicalGameplayOriginalNewCandidate decoded = - CanonicalGameplayOriginalNewCandidate.parseCanonical(first.canonicalBytes()); - assertThat(decoded).isEqualTo(first); - assertThat(decoded.canonicalJson()).isEqualTo(first.canonicalJson()); - assertThat(decoded.bindingIdentity()).isEqualTo(prepared.identity()); - assertThat(decoded.leaseEvidence().hasSameIdentity(prepared.leaseEvidence())).isTrue(); - assertThat(decoded.targetEvidence()).isEqualTo(prepared.target()); - assertThat(decoded.transition().transitionId()).isEqualTo(prepared.decision().transitionId()); - assertThat(decoded.reservation().bindingGeneration()).isEqualTo(BigInteger.valueOf(7)); - assertThat(decoded.reservation().inventorySnapshotRevision()).isEqualTo(BigInteger.valueOf(19)); - assertThat( - first.matchesProvisionalSources( - provisionalEvidence( - prepared.identity(), - prepared.bindingGeneration(), - BigInteger.valueOf(28), - true, - BigInteger.valueOf(20)))) - .isFalse(); - - String encoded = first.canonicalJson(); - assertThat(encoded) - .contains("\"purpose\":\"" + CanonicalGameplayOriginalNewCandidate.PURPOSE + "\"") - .contains("\"membershipBaseline\"") - .contains("\"authorityTuple\"") - .contains("\"outboxCheckpoints\"") - .doesNotContain( - "\"schemaVersion\":2", - "authTokenHash", - "rebindHandle", - "admissionAt", - "continuityBindingExpiresAt", - "raw-original-jwt", - "private-rebind-handle"); - assertThat(first.toString()) - .doesNotContain( - prepared.leaseEvidence().sha256(), "raw-original-jwt", "private-rebind-handle"); - } - - @Test - void rejectsWrongLeaseBindingGenerationAndTargetWhenMatchingTheOriginalDecision() { - Bundle original = bundle(CHARACTER, BigInteger.valueOf(7), "World", false); - CanonicalGameplayOriginalNewCandidate candidate = - CanonicalGameplayOriginalNewCandidate.fromOriginalSources( - preparedEvidence(original), original.decision()); - - Bundle otherLease = bundle(CHARACTER, BigInteger.valueOf(7), "World", true); - Bundle otherBinding = bundle(id(60), BigInteger.valueOf(7), "World", false); - Bundle otherGeneration = bundle(CHARACTER, BigInteger.valueOf(8), "World", false); - Bundle otherTarget = bundle(CHARACTER, BigInteger.valueOf(7), "Changed World", false); - - assertThat(candidate.matchesOriginalDecision(otherLease.decision())).isFalse(); - assertThat(candidate.matchesOriginalDecision(otherBinding.decision())).isFalse(); - assertThat(candidate.matchesOriginalDecision(otherGeneration.decision())).isFalse(); - assertThat(candidate.matchesOriginalDecision(otherTarget.decision())).isFalse(); - assertThat(candidate.matchesProvisionalSources(preparedEvidence(otherBinding))).isFalse(); - assertThat(candidate.matchesProvisionalSources(preparedEvidence(otherGeneration))).isFalse(); - - assertThatThrownBy( - () -> - CanonicalGameplayOriginalNewCandidate.fromOriginalSources( - preparedEvidence(original), otherBinding.decision())) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - CanonicalGameplayOriginalNewCandidate.fromOriginalSources( - preparedEvidence(original), otherGeneration.decision())) - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - void refusesResumeAndUnrecognizedTransitionStates() { - Bundle original = bundle(CHARACTER, BigInteger.valueOf(7), "World", false); - var resumeCarrier = - new LinkedHashMap<>( - leaseCarrier( - original.identity(), original.target(), false, original.bindingGeneration())); - resumeCarrier.put("leaseKind", "RESUME"); - resumeCarrier.put("resumeEpisodeId", id(90).toString()); - resumeCarrier.put("expectedOldBindingGeneration", "6"); - AccountGameplayAdmissionLeaseEvidence resumeLease = - AccountGameplayAdmissionLeaseEvidence.fromCarrier(resumeCarrier); - var resumeDecision = - new CanonicalGameplayAdmissionDecision( - original.decision().bindingDecisionId(), - resumeLease, - original.identity(), - BigInteger.valueOf(7), - BigInteger.valueOf(6), - original.target()); - assertThatThrownBy( - () -> - CanonicalGameplayOriginalNewCandidate.fromOriginalSources( - preparedEvidence(original), resumeDecision)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("public-production original NEW"); - - assertThatThrownBy(() -> evidenceWithStatus(original.identity(), "COMMITTED")) - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - void rejectsUnknownDuplicateMalformedOversizedNoncanonicalAndOutOfBoundInput() { - Bundle original = bundle(CHARACTER, BigInteger.valueOf(7), "World", false); - String canonical = - CanonicalGameplayOriginalNewCandidate.fromOriginalSources( - preparedEvidence(original), original.decision()) - .canonicalJson(); - - rejects( - canonical.replace( - "\"purpose\":\"" + CanonicalGameplayOriginalNewCandidate.PURPOSE + "\"", - "\"purpose\":\"" - + CanonicalGameplayOriginalNewCandidate.PURPOSE - + "\",\"extra\":\"x\"")); - rejects( - canonical.replace( - "\"purpose\":\"" + CanonicalGameplayOriginalNewCandidate.PURPOSE + "\"", - "\"purpose\":\"" - + CanonicalGameplayOriginalNewCandidate.PURPOSE - + "\",\"purpose\":\"" - + CanonicalGameplayOriginalNewCandidate.PURPOSE - + "\"")); - rejects( - canonical.replace( - "\"leaseKind\":\"NEW_BINDING\"", - "\"leaseKind\":\"NEW_BINDING\",\"leaseKind\":\"NEW_BINDING\"")); - rejects(" " + canonical); - rejects(canonical.replace("\"bindingGeneration\":\"7\"", "\"bindingGeneration\":\"07\"")); - rejects( - canonical.replace( - "\"bindingDecisionId\":\"" + id(500) + "\"", "\"bindingDecisionId\":\"not-a-uuid\"")); - rejects("{"); - - byte[] canonicalBytes = canonical.getBytes(StandardCharsets.UTF_8); - byte[] malformedUtf8 = Arrays.copyOf(canonicalBytes, canonicalBytes.length + 1); - malformedUtf8[malformedUtf8.length - 1] = (byte) 0xff; - rejects(malformedUtf8); - rejects(new byte[CanonicalGameplayOriginalNewCandidateCodec.MAX_CANDIDATE_BYTES + 1]); - rejects( - canonical.replace( - "\"bindingGeneration\":\"7\"", "\"bindingGeneration\":\"" + "9".repeat(257) + "\"")); - } - - private static void rejects(String encoded) { - rejects(encoded.getBytes(StandardCharsets.UTF_8)); - } - - private static void rejects(byte[] encoded) { - assertThatThrownBy(() -> CanonicalGameplayOriginalNewCandidate.parseCanonical(encoded)) - .isInstanceOf(IllegalArgumentException.class); - } - - private static CanonicalGameplayBindingProvisionalCasEvidence preparedEvidence(Bundle bundle) { - return provisionalEvidence( - bundle.identity(), bundle.bindingGeneration(), BigInteger.valueOf(20), false); - } - - private static CanonicalGameplayBindingProvisionalCasEvidence provisionalEvidence( - CanonicalGameplayBindingIdentity identity, - BigInteger generation, - BigInteger inventoryRevision, - boolean provisional) { - return provisionalEvidence( - identity, generation, inventoryRevision, provisional, BigInteger.valueOf(19)); - } - - private static CanonicalGameplayBindingProvisionalCasEvidence provisionalEvidence( - CanonicalGameplayBindingIdentity identity, - BigInteger generation, - BigInteger inventoryRevision, - boolean provisional, - BigInteger originalSnapshotRevision) { - UUID transitionId = id(500); - UUID reservationId = id(501); - UUID reservationFence = id(502); - UUID accountIndexFence = id(503); - CanonicalGameplayBindingInventoryEntry candidate = - new CanonicalGameplayBindingInventoryEntry( - identity, - identity.bindingRef(), - generation, - accountIndexFence, - reservationId, - transitionId, - provisional - ? CanonicalGameplayBindingInventoryEntry.Lifecycle.PROVISIONAL - : CanonicalGameplayBindingInventoryEntry.Lifecycle.CANDIDATE_PREPARED, - provisional - ? CanonicalGameplayBindingInventoryEntry.IndexState.ACKNOWLEDGED - : CanonicalGameplayBindingInventoryEntry.IndexState.REPAIR_REQUIRED, - CanonicalGameplayBindingInventoryEntry.IndexState.REPAIR_REQUIRED, - inventoryRevision); - CanonicalIssuerPartitionReservation reservation = - new CanonicalIssuerPartitionReservation( - reservationId, - identity, - generation, - transitionId, - identity.bindingRef().partitionId(identity.issuerIndexPartitionCount()), - CanonicalIssuerPartitionReservation.Lifecycle.RESERVED, - reservationFence, - id(504), - BigInteger.valueOf(2), - BigInteger.valueOf(3), - originalSnapshotRevision, - inventoryRevision); - CanonicalGameplayBindingTransitionSnapshot transition = - new CanonicalGameplayBindingTransitionSnapshot( - transitionId, - identity, - generation, - identity.bindingRef(), - inventoryRevision, - reservationId, - reservationFence, - accountIndexFence, - null, - null, - provisional - ? CanonicalGameplayBindingTransitionSnapshot.Status.PROVISIONAL - : CanonicalGameplayBindingTransitionSnapshot.Status.PREPARED, - CanonicalGameplayAccountCoverageEvidence.noActiveFlow()); - return new CanonicalGameplayBindingProvisionalCasEvidence( - transition, - candidate, - reservation, - null, - null, - new CanonicalGameplayLegacyMigrationDisposition( - id(505), - id(506), - id(507), - BigInteger.ONE, - BigInteger.TWO, - BigInteger.valueOf(3), - "sha256:" + "f".repeat(64))); - } - - private static CanonicalGameplayBindingProvisionalCasEvidence evidenceWithStatus( - CanonicalGameplayBindingIdentity identity, String status) { - UUID transitionId = id(500); - UUID reservationId = id(501); - UUID reservationFence = id(502); - UUID accountIndexFence = id(503); - var candidate = - new CanonicalGameplayBindingInventoryEntry( - identity, - identity.bindingRef(), - BigInteger.valueOf(7), - accountIndexFence, - reservationId, - transitionId, - CanonicalGameplayBindingInventoryEntry.Lifecycle.CANDIDATE_PREPARED, - CanonicalGameplayBindingInventoryEntry.IndexState.REPAIR_REQUIRED, - CanonicalGameplayBindingInventoryEntry.IndexState.REPAIR_REQUIRED, - BigInteger.valueOf(20)); - var reservation = - new CanonicalIssuerPartitionReservation( - reservationId, - identity, - BigInteger.valueOf(7), - transitionId, - identity.bindingRef().partitionId(identity.issuerIndexPartitionCount()), - CanonicalIssuerPartitionReservation.Lifecycle.RESERVED, - reservationFence, - id(504), - BigInteger.TWO, - BigInteger.valueOf(3), - BigInteger.valueOf(19), - BigInteger.valueOf(20)); - return new CanonicalGameplayBindingProvisionalCasEvidence( - new CanonicalGameplayBindingTransitionSnapshot( - transitionId, - identity, - BigInteger.valueOf(7), - identity.bindingRef(), - BigInteger.valueOf(20), - reservationId, - reservationFence, - accountIndexFence, - null, - null, - CanonicalGameplayBindingTransitionSnapshot.Status.valueOf(status), - CanonicalGameplayAccountCoverageEvidence.noActiveFlow()), - candidate, - reservation, - null, - null, - new CanonicalGameplayLegacyMigrationDisposition( - id(505), - id(506), - id(507), - BigInteger.ONE, - BigInteger.TWO, - BigInteger.valueOf(3), - "sha256:" + "f".repeat(64))); - } - - private static Bundle bundle( - UUID characterId, BigInteger generation, String worldDisplayName, boolean alternateLease) { - CanonicalGameplayBindingIdentity identity = identity(characterId); - CanonicalPlayableTarget target = target(worldDisplayName); - AccountGameplayAdmissionLeaseEvidence lease = - AccountGameplayAdmissionLeaseEvidence.fromCarrier( - leaseCarrier(identity, target, alternateLease, generation)); - var decision = - new CanonicalGameplayAdmissionDecision(id(500), lease, identity, generation, null, target); - return new Bundle(identity, generation, target, lease, decision); - } - - private static CanonicalGameplayBindingIdentity identity(UUID characterId) { - return new CanonicalGameplayBindingIdentity( - ACCOUNT, - TENANT, - NAMESPACE, - characterId, - "SHARED", - GAME_INSTANCE, - 41L, - SESSION.toString(), - REGION, - BigInteger.valueOf(5), - GameSessionAccountDelegationProfile.ISSUER, - BigInteger.ONE, - BigInteger.ONE, - BigInteger.valueOf(16), - BigInteger.valueOf(100)); - } - - private static CanonicalPlayableTarget target(String worldDisplayName) { - return new CanonicalPlayableTarget( - "test", - "tenant", - TENANT, - "world", - worldDisplayName, - REALM, - "production", - "Production", - 22L, - 41L, - NAMESPACE, - "SHARED", - GAME_INSTANCE, - VERSION, - 7L, - 3L, - 17L, - "d".repeat(64), - 1L, - "initial-request", - "a".repeat(64), - CanonicalInitialAdmissionRequest.OriginKind.NO_PRIOR_POINTER, - null, - id(30), - id(31), - "sha256:" + "b".repeat(64), - 9L, - "sha256:" + "c".repeat(64), - CanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED, - false, - Instant.parse("2026-10-26T12:00:00Z"), - "PRESEEDED"); - } - - private static Map leaseCarrier( - CanonicalGameplayBindingIdentity identity, - CanonicalPlayableTarget target, - boolean alternateLease, - BigInteger generation) { - Map carrier = new LinkedHashMap<>(); - carrier.put("schema", AccountGameplayAdmissionLeaseEvidence.SCHEMA); - carrier.put("schemaVersion", "1"); - carrier.put("mode", "PUBLIC_PRODUCTION"); - carrier.put("targetNamespace", "test"); - carrier.put("callerWorkload", "spiffe://firemud/ns/test/sa/game-session-service"); - carrier.put("requestId", id(alternateLease ? 701 : 700).toString()); - carrier.put("leaseId", id(alternateLease ? 703 : 702).toString()); - carrier.put("leaseFence", "11"); - carrier.put("leaseKind", "NEW_BINDING"); - carrier.put( - "bindingScope", - Map.ofEntries( - Map.entry("accountId", identity.accountId().toString()), - Map.entry("tenantId", identity.tenantId().toString()), - Map.entry("realmId", REALM.toString()), - Map.entry("worldSlug", "world"), - Map.entry("realmSlug", "production"), - Map.entry("playableStateNamespaceId", identity.playableStateNamespaceId().toString()), - Map.entry("playableStateScope", identity.playableStateScope()), - Map.entry("gameInstanceId", identity.gameInstanceId().toString()), - Map.entry("characterId", identity.characterId().toString()), - Map.entry("sessionId", identity.sessionId()), - Map.entry("bindingGeneration", generation.toString()), - Map.entry("catalogRevision", Long.toString(target.catalogRevision())), - Map.entry("pointerVersion", Long.toString(target.pointerVersion())), - Map.entry("regionId", identity.regionId().toString()), - Map.entry("regionEpoch", identity.regionEpoch().toString()))); - carrier.put( - "authorityTuple", - Map.of( - "issuerAuthGeneration", "1", - "accountAuthorityGeneration", "1", - "tenantAuthorityGeneration", Map.of(TENANT.toString(), "2"), - "membershipAuthorityGeneration", Map.of(TENANT.toString(), "3"), - "privateRealmGrantVersions", List.of())); - carrier.put("issuanceFence", "9"); - carrier.put( - "membershipBaseline", - Map.of( - "membershipLifecycleState", - "ACTIVE", - "membershipVersion", - Map.of(TENANT.toString(), "4"), - "membershipAuthorityGeneration", - "3")); - List streams = - new ArrayList<>( - List.of( - "account:auth-authority:v1:account/" + ACCOUNT, - "account:auth-authority:v1:issuer/" + GameSessionAccountDelegationProfile.ISSUER, - "account:auth-authority:v1:membership/" + ACCOUNT + "/" + TENANT, - "account:auth-authority:v1:tenant/" + TENANT)); - streams.sort(Comparator.naturalOrder()); - carrier.put( - "outboxCheckpoints", - streams.stream() - .map( - stream -> - Map.of( - "outboxStreamKey", - stream, - "outboxSequence", - stream.contains("tenant/") || stream.contains("membership/") ? "4" : "0")) - .toList()); - carrier.put( - "tokenIdentityEvidence", - Map.ofEntries( - Map.entry("accountId", identity.accountId().toString()), - Map.entry("operationId", id(710).toString()), - Map.entry("issuanceRequestId", id(711).toString()), - Map.entry("tokenJti", id(712).toString()), - Map.entry("tokenSHA256", "a".repeat(64)), - Map.entry("tokenGeneration", "1"), - Map.entry("issuanceFence", "9"), - Map.entry("tokenIdentityFence", "1"), - Map.entry("tokenProfile", GameSessionAccountDelegationProfile.PROFILE), - Map.entry("issuedAt", "999"), - Map.entry("notBefore", "999"), - Map.entry("expiresAt", "1300"))); - carrier.put("evaluatedAt", "1000000"); - carrier.put("expiresAt", "1010000"); - return carrier; - } - - private static UUID id(long value) { - return new UUID(0x4000L, Long.MIN_VALUE | value); - } - - private record Bundle( - CanonicalGameplayBindingIdentity identity, - BigInteger bindingGeneration, - CanonicalPlayableTarget target, - AccountGameplayAdmissionLeaseEvidence leaseEvidence, - CanonicalGameplayAdmissionDecision decision) {} -} From 138e2245615dd8c4e098cc1259c3e43b877197a5 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 29 Oct 2026 03:21:50 +1300 Subject: [PATCH 12/26] Qualify inherited issuer proofs at readiness schema boundaries --- ...calOperationRepositoryIntegrationTest.java | 30 ++++++++++++------- ...BindingLocalRedisOwnerIntegrationTest.java | 7 +++-- ...outBootstrapRepositoryIntegrationTest.java | 2 ++ 3 files changed, 27 insertions(+), 12 deletions(-) diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalOperationRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalOperationRepositoryIntegrationTest.java index 26b1a0d997..506aa04391 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalOperationRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalOperationRepositoryIntegrationTest.java @@ -583,10 +583,10 @@ void forwardMigrationRetainsCommittedAndPendingPhysicalMutationLineage() { var anchor = initialCoverageOwner(dsl, () -> state) .completeInitialBootstrap(intent.operationId(), intent.requestId()); - var local = - new CanonicalGameplayIssuerBindingLocalOperationRepository(dsl, () -> state) - .beginOrResumeOrdinaryNew( - request("migration-request", "migration-transition", identity("migration"))); + // Current ordinary NEW requires V1046 live control, which does not exist at this cut. + // The historical receipt owner is a controlled correlation only; no local operation is minted. + UUID historicalOwnerId = UUID.randomUUID(); + assertThat(count(dsl, "game_session_canonical_issuer_binding_local_operation")).isZero(); UUID committedId = UUID.randomUUID(); UUID pendingId = UUID.randomUUID(); UUID successor = UUID.randomUUID(); @@ -603,15 +603,15 @@ void forwardMigrationRetainsCommittedAndPendingPhysicalMutationLineage() { CanonicalGameplayIssuerPartitionMutationRepository.REVISION_FIELD, successor.toString().getBytes(StandardCharsets.US_ASCII))); // Controlled pre-upgrade SQL receipts exercise retention, immutability and the pending FK. - // They do not claim a Redis mutation/readback or authorize admission; the bootstrap above is - // the actual local SQL/Redis owner, under controlled Account/incarnation collaborators. + // They do not claim an ordinary NEW producer, Redis mutation/readback or admission. The + // bootstrap above uses the actual SQL/Redis owner with controlled Account/incarnation inputs. dsl.transaction( configuration -> { DSLContext transaction = DSL.using(configuration); insertPreLineageMutation( transaction, committedId, - local.operationId(), + historicalOwnerId, "ADD_CAPACITY", initialRevision, successor, @@ -636,7 +636,7 @@ void forwardMigrationRetainsCommittedAndPendingPhysicalMutationLineage() { insertPreLineageMutation( transaction, pendingId, - local.operationId(), + historicalOwnerId, "ADD_BINDING", successor, laterSuccessor, @@ -671,6 +671,7 @@ void forwardMigrationRetainsCommittedAndPendingPhysicalMutationLineage() { .containsExactlyElementsOf(beforeHeads); assertThat(anchorImage(dsl)).isEqualTo(beforeAnchor); assertThat(proofImage(dsl)).isEqualTo(beforeProof); + assertThat(count(dsl, "game_session_canonical_issuer_binding_local_operation")).isZero(); assertThat( dsl.fetch( "SELECT DISTINCT bootstrap_operation_id FROM game_session_canonical_issuer_partition_mutation") @@ -685,8 +686,17 @@ void forwardMigrationRetainsCommittedAndPendingPhysicalMutationLineage() { assertThat(head.pendingMutationId()).isEqualTo(pendingId); assertThat(head.currentRevision()).isEqualTo(successor); var history = - CanonicalGameplayIssuerPartitionMutationRepository.readPartitionInTransaction( - transaction, anchor.bootstrapOperationId(), BigInteger.ZERO); + List.of( + CanonicalGameplayIssuerPartitionMutationRepository.readInTransaction( + transaction, + CanonicalGameplayIssuerPartitionMutation.Kind.ADD_CAPACITY, + historicalOwnerId, + BigInteger.ZERO), + CanonicalGameplayIssuerPartitionMutationRepository.readInTransaction( + transaction, + CanonicalGameplayIssuerPartitionMutation.Kind.ADD_BINDING, + historicalOwnerId, + BigInteger.ZERO)); assertThat(history).hasSize(2); assertThat(history.stream().map(CanonicalGameplayIssuerPartitionMutation::status)) .containsExactlyInAnyOrder( diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java index 33694a2d1d..e975fe751b 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java @@ -898,8 +898,11 @@ void differentPartitionProgressDoesNotFenceTargetButSamePartitionProgressDoes() var state = new CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState( intent.sourceCheckpoint(), stableIncarnation("partition-isolation")); - initialCoverageOwner(dsl, () -> state) - .completeInitialBootstrap(intent.operationId(), bootstrapRequest); + var anchor = + initialCoverageOwner(dsl, () -> state) + .completeInitialBootstrap(intent.operationId(), bootstrapRequest); + new CanonicalGameplayIssuerAdmissionControlRepository(dsl) + .installInitialOpen(anchor, () -> state); var runtime = CanonicalGameplayBindingRuntimeTestFixtures.seedRunningLaunch( schema.dataSource(), uuid("partition-isolation-tenant")); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLayoutBootstrapRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLayoutBootstrapRepositoryIntegrationTest.java index 469530fc09..8ce587168a 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLayoutBootstrapRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLayoutBootstrapRepositoryIntegrationTest.java @@ -1062,6 +1062,8 @@ void retainedPhysicalWorkDoesNotStrandSupersedingLayoutOrOrdinaryNew() { var anchor = coverage.completeInitialBootstrap(replacement.operationId(), replacement.requestId()); assertThat(anchor.bootstrapOperationId()).isEqualTo(replacement.operationId()); + new CanonicalGameplayIssuerAdmissionControlRepository(dsl) + .installInitialOpen(anchor, () -> state); var runtime = CanonicalGameplayBindingRuntimeTestFixtures.seedRunningLaunch( schema.dataSource(), TENANT_ID); From 7847e769005d20ec1cb8994dd4809a59c30ab280 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 29 Oct 2026 03:26:10 +1300 Subject: [PATCH 13/26] Preserve readiness proof through tracker reconciliation --- design/project-management/ai-observations.md | 2 ++ .../implementation-tracking/player-access-and-session.md | 8 ++------ 2 files changed, 4 insertions(+), 6 deletions(-) diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 255b9ee4a3..04d3a0bc56 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -482,3 +482,5 @@ Entry format: - `2026-10-29`: A new provider summary section blocked an otherwise attributed Hosted capture. CodeRabbit returned an inline finding plus an explicitly unverified finding under “Additional comments”; FireController rejected the unfamiliar inventory format instead of inventing an empty review. The original attempt and comparison remain held while its independent owner adds bounded decoding and recovers the same capture. Do not repost, spend another allowance or treat provider acknowledgement as zero findings; recovery is still pending at this checkpoint. - 2026-10-29: Follow-up to the retained Hosted additional-comment capture issue: FireController recovered the same original attempt after updating its summary parser; both findings were independently adjudicated without a replacement trigger or allowance reset. Existing MCP sessions did not understand the new source kind, so the release-matched worker-bound CLI supplied the evidence until host reconnection. + +- 2026-10-29: A local tracker conflict edit failed its preservation assertion, but subsequent shell lines still staged and committed the unresolved text. Canonical documentation checks failed before publication. Preserve each side explicitly, verify conflict markers are absent, and make dependent staging/commit commands fail with the edit (for example checked subprocess calls); do not assume newline-separated shell commands stop on failure. The local follow-up correction preserves both proof histories and is rechecked before pushing. 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 07010db2c7..e216cb1b45 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -8,13 +8,9 @@ This is a non-normative implementation tracker for player access and session. Ca ### Canonical NEW admission components -<<<<<<< HEAD -The current local review corrections permit ordinary NEW only after proving the complete retained supersession chain ends at exact installed control. Forward V1038.4 retains prior partition heads and mutation receipts while separating their bootstrap lineages. Local physical projection batches source reads for its target partition, retains issuer-wide capacity/accounting checks on every snapshot, and fences target-partition changes independently of unrelated partition progress. R862 freshly passes all 20 selected PostgreSQL/Redis cases, including real retained-work supersession through installation and ordinary NEW, populated forward-migration retention, unrelated-partition progress and same-partition currentness refusal. Its aggregate fails two new test-only nullable-read warnings; those are corrected locally. R863 subsequently passes all 21 selected cases and the affected enabled static, frontier, generation, formatting and documentation checks, including exact retained-abort retry comparison and ADD-mutation batch reads bounded to unretired local operations. Earlier results below retain their original source attribution. - -The receiving #3320 prerequisite contains unregistered issuer LIVE control, tenant-local issuer OPEN/cutoff owners and the separate binding-local issuer acknowledgement, together with INITIAL-only Account OPEN initialization. Ordinary binding preparation and issuer projection join current live issuer control; pending Account initializers are included in the acquisition cohort, and both barrier owners retain original dispatch and exact readback evidence without reopening uncertain or CLOSED targets. This readiness boundary does not contain original-NEW candidate installation, Account bound credential/handle issuance, the final controller CAS, committed Game Session result reader or whole-flow coordinator; those remain dependent preparation and final-admission work. Extraction receiving proof R849 passes 75 of 76 selected unit/native cases, including the full 256-cycle physical-retirement case; its aggregate remains failed because the historical Account fixture opened V1038 while invoking current issuer readiness. R855 then passes both the corrected current authenticated-owner composition and a separate populated V1038→V1038.1 migration-retention proof. Its aggregate failed only an unused private fixture overload; R856 passes affected Account static, formatting and documentation checks after removing that overload. The migration fixture uses controlled historical terminal rows, while the current composition independently proves real owner calls. Earlier component evidence below retains its original source attribution; this is focused receiving proof, not a complete service-suite or public admission result. Operational source/incarnation custody, production PKI, default registration, public admission and activation remain unproved. -======= The current local review corrections permit ordinary NEW only after proving the complete retained supersession chain ends at exact installed control. Forward V1038.4 retains prior partition heads and mutation receipts while separating their bootstrap lineages. Local physical projection batches source reads for its target partition, retains issuer-wide capacity/accounting checks on every snapshot, and fences target-partition changes independently of unrelated partition progress. R862 freshly passes all 20 selected PostgreSQL/Redis cases, including real retained-work supersession through installation and ordinary NEW, populated forward-migration retention, unrelated-partition progress and same-partition currentness refusal. Its aggregate fails two new test-only nullable-read warnings. R863 subsequently passes all 21 selected cases and the affected enabled main/integration static, migration-frontier, jOOQ generation, formatting and documentation checks after those warnings are corrected. This recovery also proves exact retained-abort retry comparison and ADD-mutation batch reads bounded to unretired local operations. The earlier failed R862 aggregate remains retained. Earlier results below retain their original source attribution. ->>>>>>> b1bd0047ce3a9ab38589bf9136548bd859a1c194 + +The receiving #3320 prerequisite contains unregistered issuer LIVE control, tenant-local issuer OPEN/cutoff owners and the separate binding-local issuer acknowledgement, together with INITIAL-only Account OPEN initialization. Ordinary binding preparation and issuer projection join current live issuer control; pending Account initializers are included in the acquisition cohort, and both barrier owners retain original dispatch and exact readback evidence without reopening uncertain or CLOSED targets. This readiness boundary does not contain original-NEW candidate installation, Account bound credential/handle issuance, the final controller CAS, committed Game Session result reader or whole-flow coordinator; those remain dependent preparation and final-admission work. Extraction receiving proof R849 passes 75 of 76 selected unit/native cases, including the full 256-cycle physical-retirement case; its aggregate remains failed because the historical Account fixture opened V1038 while invoking current issuer readiness. R855 then passes both the corrected current authenticated-owner composition and a separate populated V1038→V1038.1 migration-retention proof. Its aggregate failed only an unused private fixture overload; R856 passes affected Account static, formatting and documentation checks after removing that overload. The migration fixture uses controlled historical terminal rows, while the current composition independently proves real owner calls. Earlier component evidence below retains its original source attribution; this is focused receiving proof, not a complete service-suite or public admission result. R867 subsequently passes 23 current-parent receiving cases, including latest-schema issuer OPEN composition, controlled predecessor mutation receipt retention, shared region/Human regressions and authenticated Account abort cleanup, with affected static, frontier, generation, formatting and documentation checks. Historical receipt correlation remains controlled and claims no ordinary-NEW producer at the older schema. Operational source/incarnation custody, production PKI, default registration, public admission and activation remain unproved. The current local correction adds explicit recovery for a stale, uninstalled initial issuer-bootstrap candidate. Forward V1038.3 retains its original intent, cohort and issued work, captures the new actual inventory cut under monotonic fences, and atomically binds immutable supersession lineage to current control. A strictly newer trusted layout separates old physical work; installed anchors remain ineligible. Account CI selection and migration task inputs now cover its Game Session owner-composition dependency, and the native registration-image and lost-reply proofs use their actual SQL/Lua contracts. R827 passes 31 of 32 focused cases; its remaining failure is a test assertion against the transaction wrapper rather than the nested PostgreSQL refusal. R828 then passes that complete recovery case with affected integration static and formatting checks. Together they qualify 32 distinct current-source cases, including two actual Account abort compositions; frontier, jOOQ, affected static, formatting and documentation checks pass. The new recovery sequence uses controlled Account terminal input through the actual Game Session abort owner, separately from those two authenticated Account compositions. This is focused proof, not a full service-suite, live layout rotation, retained-key cleanup or production-authority claim. From adfaf0fbc715af828890babd1e78a29393344994 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 29 Oct 2026 04:46:53 +1300 Subject: [PATCH 14/26] docs: retain Hosted evidence capture recovery lesson --- design/project-management/ai-observations.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 04d3a0bc56..2f3fe1fae8 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -484,3 +484,7 @@ Entry format: - 2026-10-29: Follow-up to the retained Hosted additional-comment capture issue: FireController recovered the same original attempt after updating its summary parser; both findings were independently adjudicated without a replacement trigger or allowance reset. Existing MCP sessions did not understand the new source kind, so the release-matched worker-bound CLI supplied the evidence until host reconnection. - 2026-10-29: A local tracker conflict edit failed its preservation assertion, but subsequent shell lines still staged and committed the unresolved text. Canonical documentation checks failed before publication. Preserve each side explicitly, verify conflict markers are absent, and make dependent staging/commit commands fail with the edit (for example checked subprocess calls); do not assume newline-separated shell commands stop on failure. The local follow-up correction preserves both proof histories and is rechecked before pushing. + +### 2026-10-29 — Hosted completion parsing and capture diagnostics + +Gameplay #3310 Hosted7 finished at 03:51:18 NZDT but its native evidence was recorded at 04:30:37, a 39-minute 19-second capture delay. FireController identified an optional `review_info_content` marker that broke standing-result parsing and unrelated CI-bot edits that masked the useful capture diagnostic. The owner deployed parser/diagnostic regression fixes in `2f1e5da5` and recovered the original zero-finding evidence without another trigger or spent reservation. Retain optional-marker and unrelated-comment cases in completion recovery tests; provider check success alone cannot establish a zero-finding native review. From c878d2c2fe39afcc1b597e48ac8d32a9db34cd04 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 29 Oct 2026 04:53:15 +1300 Subject: [PATCH 15/26] docs: fix observation heading hierarchy --- design/project-management/ai-observations.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 2f3fe1fae8..e5ef3af7c0 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -485,6 +485,6 @@ Entry format: - 2026-10-29: A local tracker conflict edit failed its preservation assertion, but subsequent shell lines still staged and committed the unresolved text. Canonical documentation checks failed before publication. Preserve each side explicitly, verify conflict markers are absent, and make dependent staging/commit commands fail with the edit (for example checked subprocess calls); do not assume newline-separated shell commands stop on failure. The local follow-up correction preserves both proof histories and is rechecked before pushing. -### 2026-10-29 — Hosted completion parsing and capture diagnostics +## 2026-10-29 — Hosted completion parsing and capture diagnostics Gameplay #3310 Hosted7 finished at 03:51:18 NZDT but its native evidence was recorded at 04:30:37, a 39-minute 19-second capture delay. FireController identified an optional `review_info_content` marker that broke standing-result parsing and unrelated CI-bot edits that masked the useful capture diagnostic. The owner deployed parser/diagnostic regression fixes in `2f1e5da5` and recovered the original zero-finding evidence without another trigger or spent reservation. Retain optional-marker and unrelated-comment cases in completion recovery tests; provider check success alone cannot establish a zero-finding native review. From 1df41d852500e13b6a64c425fb2e022a0826e4b3 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 29 Oct 2026 05:44:12 +1300 Subject: [PATCH 16/26] test: inherit canonical retained abort migration proof from parent --- .../player-access-and-session.md | 2 +- ...ccountControlMigrationIntegrationTest.java | 462 ------------------ 2 files changed, 1 insertion(+), 463 deletions(-) delete mode 100644 services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRetainedFirstNewAbortAccountControlMigrationIntegrationTest.java 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 5a9d8d440b..97b45fb84a 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -10,7 +10,7 @@ This is a non-normative implementation tracker for player access and session. Ca The current local review corrections permit ordinary NEW only after proving the complete retained supersession chain ends at exact installed control. Forward V1038.4 retains prior partition heads and mutation receipts while separating their bootstrap lineages. Local physical projection batches source reads for its target partition, retains issuer-wide capacity/accounting checks on every snapshot, and fences target-partition changes independently of unrelated partition progress. R862 freshly passes all 20 selected PostgreSQL/Redis cases, including real retained-work supersession through installation and ordinary NEW, populated forward-migration retention, unrelated-partition progress and same-partition currentness refusal. Its aggregate fails two new test-only nullable-read warnings. R863 subsequently passes all 21 selected cases and the affected enabled main/integration static, migration-frontier, jOOQ generation, formatting and documentation checks after those warnings are corrected. This recovery also proves exact retained-abort retry comparison and ADD-mutation batch reads bounded to unretired local operations. The earlier failed R862 aggregate remains retained. Earlier results below retain their original source attribution. -The receiving #3320 prerequisite contains unregistered issuer LIVE control, tenant-local issuer OPEN/cutoff owners and the separate binding-local issuer acknowledgement, together with INITIAL-only Account OPEN initialization. Ordinary binding preparation and issuer projection join current live issuer control; pending Account initializers are included in the acquisition cohort, and both barrier owners retain original dispatch and exact readback evidence without reopening uncertain or CLOSED targets. This readiness boundary does not contain original-NEW candidate installation, Account bound credential/handle issuance, the final controller CAS, committed Game Session result reader or whole-flow coordinator; those remain dependent preparation and final-admission work. Extraction receiving proof R849 passes 75 of 76 selected unit/native cases, including the full 256-cycle physical-retirement case; its aggregate remains failed because the historical Account fixture opened V1038 while invoking current issuer readiness. R855 then passes both the corrected current authenticated-owner composition and a separate populated V1038→V1038.1 migration-retention proof. Its aggregate failed only an unused private fixture overload; R856 passes affected Account static, formatting and documentation checks after removing that overload. The migration fixture uses controlled historical terminal rows, while the current composition independently proves real owner calls. Earlier component evidence below retains its original source attribution; this is focused receiving proof, not a complete service-suite or public admission result. R867 subsequently passes 23 current-parent receiving cases, including latest-schema issuer OPEN composition, controlled predecessor mutation receipt retention, shared region/Human regressions and authenticated Account abort cleanup, with affected static, frontier, generation, formatting and documentation checks. Historical receipt correlation remains controlled and claims no ordinary-NEW producer at the older schema. Operational source/incarnation custody, production PKI, default registration, public admission and activation remain unproved. +The receiving #3320 prerequisite contains unregistered issuer LIVE control, tenant-local issuer OPEN/cutoff owners and the separate binding-local issuer acknowledgement, together with INITIAL-only Account OPEN initialization. Ordinary binding preparation and issuer projection join current live issuer control; pending Account initializers are included in the acquisition cohort, and both barrier owners retain original dispatch and exact readback evidence without reopening uncertain or CLOSED targets. This readiness boundary does not contain original-NEW candidate installation, Account bound credential/handle issuance, the final controller CAS, committed Game Session result reader or whole-flow coordinator; those remain dependent preparation and final-admission work. Extraction receiving proof R849 passes 75 of 76 selected unit/native cases, including the full 256-cycle physical-retirement case; its aggregate remains failed because the historical Account fixture opened V1038 while invoking current issuer readiness. R855 then passes both the corrected current authenticated-owner composition and a separate populated V1038→V1038.1 migration-retention proof. Its aggregate failed only an unused private fixture overload; R856 passes affected Account static, formatting and documentation checks after removing that overload. The migration fixture uses controlled historical terminal rows, while the current composition independently proves real owner calls. Earlier component evidence below retains its original source attribution; this is focused receiving proof, not a complete service-suite or public admission result. R867 subsequently passes 23 current-parent receiving cases, including latest-schema issuer OPEN composition, controlled predecessor mutation receipt retention, shared region/Human regressions and authenticated Account abort cleanup, with affected static, frontier, generation, formatting and documentation checks. Historical receipt correlation remains controlled and claims no ordinary-NEW producer at the older schema. The current parent now owns the separately controlled V1038→V1038.1 retention case in the Account abort-composition test; its duplicate standalone Game Session fixture is removed here. Earlier proof retains its original source attribution. Operational source/incarnation custody, production PKI, default registration, public admission and activation remain unproved. The current local correction adds explicit recovery for a stale, uninstalled initial issuer-bootstrap candidate. Forward V1038.3 retains its original intent, cohort and issued work, captures the new actual inventory cut under monotonic fences, and atomically binds immutable supersession lineage to current control. A strictly newer trusted layout separates old physical work; installed anchors remain ineligible. Account CI selection and migration task inputs now cover its Game Session owner-composition dependency, and the native registration-image and lost-reply proofs use their actual SQL/Lua contracts. R827 passes 31 of 32 focused cases; its remaining failure is a test assertion against the transaction wrapper rather than the nested PostgreSQL refusal. R828 then passes that complete recovery case with affected integration static and formatting checks. Together they qualify 32 distinct current-source cases, including two actual Account abort compositions; frontier, jOOQ, affected static, formatting and documentation checks pass. The new recovery sequence uses controlled Account terminal input through the actual Game Session abort owner, separately from those two authenticated Account compositions. This is focused proof, not a full service-suite, live layout rotation, retained-key cleanup or production-authority claim. diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRetainedFirstNewAbortAccountControlMigrationIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRetainedFirstNewAbortAccountControlMigrationIntegrationTest.java deleted file mode 100644 index 953b38caee..0000000000 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRetainedFirstNewAbortAccountControlMigrationIntegrationTest.java +++ /dev/null @@ -1,462 +0,0 @@ -package net.firedevops.firemud.gamesession.repository; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import java.nio.file.Path; -import java.time.OffsetDateTime; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.UUID; -import net.firedevops.firemud.test.TestContainerImages; -import org.flywaydb.core.Flyway; -import org.flywaydb.core.api.MigrationVersion; -import org.jooq.DSLContext; -import org.jooq.Field; -import org.jooq.SQLDialect; -import org.jooq.impl.DSL; -import org.junit.jupiter.api.Test; -import org.springframework.jdbc.datasource.DriverManagerDataSource; -import org.testcontainers.containers.PostgreSQLContainer; -import org.testcontainers.junit.jupiter.Container; -import org.testcontainers.junit.jupiter.Testcontainers; - -/** - * Controlled V1038 predecessor storage, with installed guards and actual filesystem migrations. - * Lease, terminal Account outcome and member readback are stipulated historical SQL inputs, never - * fresh admission, issuer OPEN control, grants or evidence that a historical runtime owner ran. The - * Account owner-composition suite separately proves authenticated abort and physical cleanup. - */ -@Testcontainers(disabledWithoutDocker = true) -@SuppressWarnings("resource") -class CanonicalGameplayRetainedFirstNewAbortAccountControlMigrationIntegrationTest { - private static final String PREFIX = "game_session_canonical_"; - private static final List RETAINED_TABLES = - List.of( - "binding_transition", - "gameplay_binding_inventory", - "issuer_partition_reservation", - "binding_account_index_obligation", - "binding_issuer_index_obligation", - "binding_region_bridge_obligation", - "account_member_repair_operation"); - private static final UUID ACCOUNT = UUID.randomUUID(); - private static final UUID TENANT = UUID.randomUUID(); - private static final UUID NAMESPACE = UUID.randomUUID(); - private static final UUID CHARACTER = UUID.randomUUID(); - private static final UUID TRANSITION = UUID.randomUUID(); - private static final UUID RESERVATION = UUID.randomUUID(); - private static final UUID ACCOUNT_FENCE = UUID.randomUUID(); - private static final UUID INSTANCE = UUID.randomUUID(); - private static final UUID REGION = UUID.randomUUID(); - private static final byte[] BINDING_REF = new byte[] {1, 2, 3}; - private static final String MEMBER = "accountIndexMember/v1:AQID:1:" + ACCOUNT_FENCE; - private static final String RAW_DIGEST = "a".repeat(64); - private static final String DIGEST = "sha256:" + RAW_DIGEST; - - @Container - static PostgreSQLContainer postgres = - new PostgreSQLContainer<>(TestContainerImages.postgres()); - - @Test - void v1038Point1PreservesAcknowledgedAbortAndHistoryThenAllowsLaterControlCleanup() { - String schema = "gs_retained_abort_" + UUID.randomUUID().toString().replace("-", ""); - var dataSource = - new DriverManagerDataSource( - postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); - dataSource.setSchema(schema); - try { - Flyway predecessor = flyway(dataSource, schema, "1038"); - predecessor.migrate(); - predecessor.validate(); - DSLContext dsl = DSL.using(dataSource, SQLDialect.POSTGRES); - seedControlledAcknowledgedAbort(dsl); - // Validate the complete terminal predecessor under its original NO_ACTIVE control. All - // installed immediate and deferred guards remain enabled; no current prepare owner is used. - dsl.execute( - "UPDATE " + PREFIX + "binding_transition SET inventory_revision = inventory_revision"); - seedLaterControlledAcquisitionIntent(dsl); - - Map> originalRows = rows(dsl, false); - originalRows.values().forEach(images -> assertThat(images).hasSize(1)); - Map> immutableRows = rows(dsl, true); - assertThat( - dsl.fetchSingle("SELECT state FROM " + PREFIX + "account_coverage_control") - .get(0, String.class)) - .isEqualTo("ACQUISITION_INTENT"); - List historyBefore = history(dsl); - assertThat(historyBefore) - .anyMatch(row -> row.contains("V1000__create_saga_schema.sql")) - .anyMatch(row -> row.contains("V1001__saga_instance_table.sql")) - .anyMatch(row -> row.contains("V1002__saga_step_table.sql")); - assertThat( - dsl.fetchSingle( - "SELECT version FROM flyway_schema_history ORDER BY installed_rank DESC LIMIT 1") - .get(0, String.class)) - .isEqualTo("1038"); - - // This is the V1038 defect: a retained abort's exact original ACK must not require the - // account to remain forever at its old NO_ACTIVE epoch. The failed transaction rolls back - // every affected row, including the singleton inventory clock. - assertThatThrownBy(() -> advanceRetainedRevision(dsl)) - .isInstanceOf(org.jooq.exception.DataAccessException.class) - .rootCause() - .isInstanceOf(org.postgresql.util.PSQLException.class) - .hasMessageContaining("First-NEW Account abort requires its exact retained candidate"); - assertThat(rows(dsl, false)).isEqualTo(originalRows); - assertThat( - dsl.fetchSingle( - "SELECT inventory_revision FROM " + PREFIX + "binding_inventory_clock") - .get(0, Integer.class)) - .isEqualTo(5); - - Flyway upgraded = flyway(dataSource, schema, "1038.1"); - assertThat(upgraded.migrate().migrationsExecuted).isEqualTo(1); - upgraded.validate(); - List historyAfter = history(dsl); - assertThat(historyAfter).hasSize(historyBefore.size() + 1); - assertThat(historyAfter.subList(0, historyBefore.size())) - .containsExactlyElementsOf(historyBefore); - assertThat(historyAfter.get(historyAfter.size() - 1)) - .contains("1038.1", "V1038.1__retained_first_new_abort_cleanup_account_control.sql"); - assertThat(rows(dsl, false)).isEqualTo(originalRows); - assertThat( - dsl.fetchSingle( - "SELECT inventory_revision FROM " + PREFIX + "binding_inventory_clock") - .get(0, Integer.class)) - .isEqualTo(5); - - advanceRetainedRevision(dsl); - assertThat(rows(dsl, true)).isEqualTo(immutableRows); - for (String table : RETAINED_TABLES.subList(0, 6)) { - assertThat( - dsl.fetchSingle("SELECT inventory_revision FROM " + PREFIX + table) - .get(0, Integer.class)) - .isEqualTo(6); - } - assertThat( - dsl.fetchSingle( - "SELECT inventory_revision FROM " + PREFIX + "binding_inventory_clock") - .get(0, Integer.class)) - .isEqualTo(6); - assertThat(history(dsl)).containsExactlyElementsOf(historyAfter); - assertThat(upgraded.migrate().migrationsExecuted).isZero(); - assertThat(history(dsl)).containsExactlyElementsOf(historyAfter); - } finally { - DSL.using(dataSource, SQLDialect.POSTGRES) - .execute("DROP SCHEMA IF EXISTS " + schema + " CASCADE"); - } - } - - private static void seedControlledAcknowledgedAbort(DSLContext dsl) { - dsl.transaction( - configuration -> { - DSLContext tx = DSL.using(configuration); - tx.execute("UPDATE " + PREFIX + "binding_inventory_clock SET inventory_revision = 5"); - insert( - tx, - "account_coverage_control", - Map.of( - "account_id", - ACCOUNT, - "state", - "NO_ACTIVE_ACCOUNT_WIDE_FLOW", - "last_operation_fence", - 0)); - insert( - tx, - "account_member_repair_control", - Map.of( - "account_id", ACCOUNT, - "last_operation_fence", 1, - "last_coverage_generation", 3)); - Map candidate = new LinkedHashMap<>(); - candidate.put("binding_ref", BINDING_REF); - candidate.put("account_id", ACCOUNT); - candidate.put("tenant_id", TENANT); - candidate.put("playable_state_namespace_id", NAMESPACE); - candidate.put("character_id", CHARACTER); - candidate.put("playable_state_scope", "SHARED"); - candidate.put("game_instance_id", INSTANCE); - candidate.put("runtime_game_instance_id", 1L); - candidate.put("session_id", UUID.randomUUID().toString()); - candidate.put("binding_generation", 1); - candidate.put("region_id", REGION); - candidate.put("region_epoch", 1); - candidate.put("issuer_id", "firemud-account-service"); - candidate.put("issuer_auth_generation", 1); - candidate.put("issuer_index_layout_version", 1); - candidate.put("issuer_index_partition_count", 1); - candidate.put("issuer_index_partition_capacity", 3); - candidate.put("issuer_partition_id", 0); - candidate.put("account_index_fence", ACCOUNT_FENCE); - candidate.put("issuer_reservation_id", RESERVATION); - candidate.put("transition_id", TRANSITION); - candidate.put("lifecycle", "TERMINAL_UNRESOLVED"); - candidate.put("account_index_state", "ACKNOWLEDGED"); - candidate.put("issuer_index_state", "REPAIR_REQUIRED"); - candidate.put("inventory_revision", 5); - insert(tx, "gameplay_binding_inventory", candidate); - - Map transition = new LinkedHashMap<>(); - transition.put("transition_id", TRANSITION); - transition.put("tenant_id", TENANT); - transition.put("playable_state_namespace_id", NAMESPACE); - transition.put("character_id", CHARACTER); - transition.put("candidate_binding_ref", BINDING_REF); - transition.put("candidate_binding_generation", 1); - transition.put("candidate_account_index_fence", ACCOUNT_FENCE); - transition.put("issuer_reservation_id", RESERVATION); - transition.put("status", "ABORTED"); - transition.put("inventory_revision", 5); - transition.put("admission_request_id", UUID.randomUUID()); - transition.put("admission_lease_id", UUID.randomUUID()); - transition.put("admission_lease_fence", 1); - transition.put("admission_lease_kind", "NEW_BINDING"); - transition.put("admission_lease_digest", RAW_DIGEST); - transition.put("admission_lease_evidence", "{\"controlledHistoricalAccountAbort\":true}"); - transition.put("admission_lease_expires_at", 1); - transition.put("admission_orphan_cleanup_id", UUID.randomUUID()); - transition.put("admission_target_namespace", "test"); - transition.put("admission_target_tenant_slug", "historical-tenant"); - transition.put("admission_target_tenant_id", TENANT); - transition.put("admission_target_world_slug", "historical-world"); - transition.put("admission_target_world_display_name", "Historical world"); - transition.put("admission_target_realm_id", UUID.randomUUID()); - transition.put("admission_target_realm_slug", "historical-realm"); - transition.put("admission_target_realm_display_name", "Historical realm"); - transition.put("admission_target_game_session_tenant_id", 1L); - transition.put("admission_target_game_instance_id", 1L); - transition.put("admission_target_playable_state_namespace_id", NAMESPACE); - transition.put("admission_target_playable_state_scope", "SHARED"); - transition.put("admission_target_canonical_game_instance_id", INSTANCE); - transition.put("admission_target_canonical_version_id", UUID.randomUUID()); - transition.put("admission_target_runtime_version_id", 1L); - transition.put("admission_target_catalog_revision", 1L); - transition.put("admission_target_pointer_version", 1L); - transition.put("admission_target_pointer_snapshot_digest", RAW_DIGEST); - transition.put("admission_target_active_world_epoch", 1L); - transition.put( - "admission_target_initial_admission_request_id", "controlled-historical-request"); - transition.put("admission_target_initial_admission_request_digest", RAW_DIGEST); - transition.put("admission_target_origin_kind", "NO_PRIOR_POINTER"); - transition.put("admission_target_hold_id", UUID.randomUUID()); - transition.put("admission_target_hold_fence", UUID.randomUUID()); - transition.put("admission_target_hold_binding_digest", DIGEST); - transition.put("admission_target_audit_event_id", 1L); - transition.put("admission_target_owner_proof_digest", DIGEST); - transition.put("admission_target_owner_proof_outcome", "COMMITTED"); - transition.put("admission_target_positive_durable_abort", false); - transition.put( - "admission_target_terminal_at", OffsetDateTime.parse("2026-10-26T00:00:00Z")); - transition.put("admission_target_character_creation_policy", "{}"); - insert(tx, "binding_transition", transition); - - Map reservation = new LinkedHashMap<>(candidate); - reservation.remove("issuer_partition_id"); - reservation.remove("account_index_fence"); - reservation.remove("issuer_reservation_id"); - reservation.remove("account_index_state"); - reservation.remove("issuer_index_state"); - reservation.put("reservation_id", RESERVATION); - reservation.put("partition_id", 0); - reservation.put("lifecycle", "RELEASE_PENDING"); - reservation.put("reservation_fence", UUID.randomUUID()); - reservation.put("issuer_coverage_operation_id", UUID.randomUUID()); - reservation.put("issuer_coverage_operation_fence", 1); - reservation.put("coverage_fence", 1); - reservation.put("inventory_snapshot_revision", 1); - insert(tx, "issuer_partition_reservation", reservation); - - Map accountObligation = new LinkedHashMap<>(); - accountObligation.put("transition_id", TRANSITION); - accountObligation.put("obligation_ordinal", 0); - accountObligation.put("binding_ref", BINDING_REF); - accountObligation.put("account_id", ACCOUNT); - accountObligation.put("tenant_id", TENANT); - accountObligation.put("action", "ADD_OR_RETAIN"); - accountObligation.put("binding_generation", 1); - accountObligation.put("account_index_fence", ACCOUNT_FENCE); - accountObligation.put("execution_phase", "BEFORE_FINAL_CAS"); - accountObligation.put("status", "ACKNOWLEDGED"); - accountObligation.put("inventory_revision", 5); - accountObligation.put("projection_state", "PRESENT_AWAITING_COVERAGE"); - accountObligation.put("projection_member", MEMBER); - accountObligation.put("projection_inventory_revision", 4); - insert(tx, "binding_account_index_obligation", accountObligation); - insert( - tx, - "binding_issuer_index_obligation", - Map.of( - "transition_id", - TRANSITION, - "binding_ref", - BINDING_REF, - "binding_generation", - 1, - "reservation_id", - RESERVATION, - "status", - "REQUIRED", - "inventory_revision", - 5)); - Map region = new LinkedHashMap<>(); - for (String key : - List.of( - "transition_id", - "binding_ref", - "binding_generation", - "account_id", - "tenant_id", - "game_instance_id", - "runtime_game_instance_id", - "session_id", - "region_id", - "region_epoch", - "inventory_revision")) { - region.put(key, candidate.get(key)); - } - region.put("status", "REQUIRED"); - insert(tx, "binding_region_bridge_obligation", region); - - Map repair = new LinkedHashMap<>(); - repair.put("operation_id", UUID.randomUUID()); - repair.put("transition_id", TRANSITION); - repair.put("obligation_ordinal", 0); - repair.put("operation_fence", 1); - repair.put("coverage_fence", UUID.randomUUID()); - repair.put("inventory_snapshot_revision", 2); - repair.put("binding_ref", BINDING_REF); - repair.put("account_id", ACCOUNT); - repair.put("tenant_id", TENANT); - repair.put("binding_generation", 1); - repair.put("account_index_fence", ACCOUNT_FENCE); - repair.put("original_action", "ADD_OR_RETAIN"); - repair.put("original_execution_phase", "BEFORE_FINAL_CAS"); - repair.put("original_status", "REQUIRED"); - repair.put("original_inventory_revision", 1); - repair.put("original_projection_state", "REQUIRED"); - repair.put("desired_action", "ADD_OR_RETAIN"); - repair.put("member", MEMBER); - repair.put("account_control_state", "NO_ACTIVE_ACCOUNT_WIDE_FLOW"); - repair.put("account_control_epoch", 0); - repair.put("status", "ACKNOWLEDGED"); - repair.put("coverage_generation", 3); - repair.put("readback_state", "PRESENT"); - repair.put("readback_member", MEMBER); - repair.put("completed_inventory_revision", 4); - insert(tx, "account_member_repair_operation", repair); - }); - } - - private static void seedLaterControlledAcquisitionIntent(DSLContext dsl) { - UUID intent = UUID.randomUUID(); - UUID fence = UUID.randomUUID(); - Map operation = new LinkedHashMap<>(); - operation.put("operation_id", intent); - operation.put("request_id", UUID.randomUUID()); - operation.put("account_id", ACCOUNT); - operation.put("operation_fence", 1); - operation.put("planned_account_admission_fence", fence); - operation.put("inventory_snapshot_revision", 5); - operation.put("legacy_cohort_id", UUID.randomUUID()); - operation.put("legacy_owner_operation_id", UUID.randomUUID()); - operation.put("legacy_writer_fence", UUID.randomUUID()); - operation.put("legacy_source_snapshot_revision", 1); - operation.put("legacy_canonical_inventory_revision", 1); - operation.put("legacy_namespace_index_readback_revision", 1); - operation.put("legacy_evidence_digest", DIGEST); - operation.put("intent_state", "ACQUISITION_INTENT"); - operation.put("cohort_row_count", 0L); - operation.put("cohort_digest", DIGEST); - operation.put("barrier_target_count", 0L); - operation.put("barrier_target_digest", DIGEST); - insert(dsl, "account_admission_fence_intent", operation); - dsl.execute( - "UPDATE " - + PREFIX - + "account_coverage_control SET state = 'ACQUISITION_INTENT'," - + " last_operation_fence = 1, current_operation_fence = 1," - + " current_fence_intent_id = ?, account_admission_fence = ?, inventory_snapshot_revision = 5" - + " WHERE account_id = ?", - intent, - fence, - ACCOUNT); - } - - private static void advanceRetainedRevision(DSLContext dsl) { - dsl.transaction( - configuration -> { - DSLContext tx = DSL.using(configuration); - tx.execute("UPDATE " + PREFIX + "binding_inventory_clock SET inventory_revision = 6"); - for (String table : RETAINED_TABLES.subList(0, 6)) { - tx.execute("UPDATE " + PREFIX + table + " SET inventory_revision = 6"); - } - }); - } - - private static Map> rows(DSLContext dsl, boolean immutableOnly) { - Map> rows = new LinkedHashMap<>(); - for (String table : RETAINED_TABLES) { - String expression = "to_jsonb(retained)"; - if (immutableOnly && !table.equals("account_member_repair_operation")) { - expression += " - 'inventory_revision'"; - } - rows.put( - table, - dsl.fetch( - "SELECT (" - + expression - + ")::text AS image FROM " - + PREFIX - + table - + " retained ORDER BY 1") - .getValues("image", String.class)); - } - for (String table : - List.of( - "account_coverage_control", - "account_admission_fence_intent", - "account_member_repair_control")) { - rows.put( - table, - dsl.fetch( - "SELECT to_jsonb(retained)::text AS image FROM " - + PREFIX - + table - + " retained ORDER BY 1") - .getValues("image", String.class)); - } - return rows; - } - - private static void insert(DSLContext dsl, String table, Map values) { - Map, Object> fields = new LinkedHashMap<>(); - values.forEach((column, value) -> fields.put(DSL.field(DSL.name(column)), value)); - dsl.insertInto(DSL.table(DSL.name(PREFIX + table))).set(fields).execute(); - } - - private static List history(DSLContext dsl) { - return dsl.fetch( - "SELECT to_jsonb(history_row)::text AS image FROM flyway_schema_history history_row" - + " ORDER BY installed_rank") - .getValues("image", String.class); - } - - private static Flyway flyway(DriverManagerDataSource dataSource, String schema, String target) { - return Flyway.configure() - .dataSource(dataSource) - .schemas(schema) - .defaultSchema(schema) - .placeholders(Map.of("serviceSchema", schema)) - .locations( - "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize(), - "filesystem:" - + Path.of("../common-saga/src/main/resources/db/migration/saga") - .toAbsolutePath() - .normalize()) - .target(MigrationVersion.fromVersion(target)) - .load(); - } -} From 82ab66fdfc4bd740e7f8c9331b736921871ee0e8 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 29 Oct 2026 07:23:56 +1300 Subject: [PATCH 17/26] Validate INITIAL barrier preparation before consuming one-shot claims --- design/project-management/ai-observations.md | 5 + .../player-access-and-session.md | 6 +- ...meplayAccountInitialBarrierRedisOwner.java | 54 ++-- ...eplayIssuerAdmissionBarrierRedisOwner.java | 54 ++-- ...eplayIssuerAdmissionBarrierRepository.java | 39 ++- ...alGameplayTenantGameplayTagRepository.java | 20 ++ ...ccount-admission-barrier-initial-open.json | 1 - ...eplayAdmissionAbortCompositionFixture.java | 20 +- ...ssionBarrierRepositoryIntegrationTest.java | 278 +++++++++++++++++- ...BindingLocalRedisOwnerIntegrationTest.java | 13 +- ...suerPhysicalRetirementIntegrationTest.java | 32 ++ ...nationReceiverPostgresIntegrationTest.java | 232 ++++++++++++++- 12 files changed, 659 insertions(+), 95 deletions(-) diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index e5ef3af7c0..2995293f8b 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -488,3 +488,8 @@ Entry format: ## 2026-10-29 — Hosted completion parsing and capture diagnostics Gameplay #3310 Hosted7 finished at 03:51:18 NZDT but its native evidence was recorded at 04:30:37, a 39-minute 19-second capture delay. FireController identified an optional `review_info_content` marker that broke standing-result parsing and unrelated CI-bot edits that masked the useful capture diagnostic. The owner deployed parser/diagnostic regression fixes in `2f1e5da5` and recovered the original zero-finding evidence without another trigger or spent reservation. Retain optional-marker and unrelated-comment cases in completion recovery tests; provider check success alone cannot establish a zero-finding native review. + +- `2026-10-29`: Check owner reachability before adjudicating a schema-level review claim + - Context: #3320 CLI reported that a later issuer cutoff could strand an older CLOSED barrier because the SQL operation schema permits positive prior epochs. + - Observation: Gameplay initially accepted and escalated that claim before reading the actual owner. `beginCutoff` already requires current OPEN control and the original anchor-install operation, rejecting INSTALLED before allocation. The source claim was corrected in native review history and the unnecessary decision request withdrawn. + - Expected pattern: Verify the concrete owner guards and supported lifecycle before accepting a finding or escalating a design choice; a table admitting a representation does not establish a reachable supported transition. Preserve the original adjudication audit and correction without expanding fail-closed behavior. 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 7e6bbc7f4f..2221036a66 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -10,7 +10,7 @@ This is a non-normative implementation tracker for player access and session. Ca The current local review corrections permit ordinary NEW only after proving the complete retained supersession chain ends at exact installed control. Forward V1038.4 retains prior partition heads and mutation receipts while separating their bootstrap lineages. Local physical projection batches source reads for its target partition, retains issuer-wide capacity/accounting checks on every snapshot, and fences target-partition changes independently of unrelated partition progress. R862 freshly passes all 20 selected PostgreSQL/Redis cases, including real retained-work supersession through installation and ordinary NEW, populated forward-migration retention, unrelated-partition progress and same-partition currentness refusal. Its aggregate fails two new test-only nullable-read warnings. R863 subsequently passes all 21 selected cases and the affected enabled main/integration static, migration-frontier, jOOQ generation, formatting and documentation checks after those warnings are corrected. This recovery also proves exact retained-abort retry comparison and ADD-mutation batch reads bounded to unretired local operations. The earlier failed R862 aggregate remains retained. Earlier results below retain their original source attribution. -The receiving #3320 prerequisite contains unregistered issuer LIVE control, tenant-local issuer OPEN/cutoff owners and the separate binding-local issuer acknowledgement, together with INITIAL-only Account OPEN initialization. Ordinary binding preparation and issuer projection join current live issuer control; pending Account initializers are included in the acquisition cohort, and both barrier owners retain original dispatch and exact readback evidence without reopening uncertain or CLOSED targets. This readiness boundary does not contain original-NEW candidate installation, Account bound credential/handle issuance, the final controller CAS, committed Game Session result reader or whole-flow coordinator; those remain dependent preparation and final-admission work. Extraction receiving proof R849 passes 75 of 76 selected unit/native cases, including the full 256-cycle physical-retirement case; its aggregate remains failed because the historical Account fixture opened V1038 while invoking current issuer readiness. R855 then passes both the corrected current authenticated-owner composition and a separate populated V1038→V1038.1 migration-retention proof. Its aggregate failed only an unused private fixture overload; R856 passes affected Account static, formatting and documentation checks after removing that overload. The migration fixture uses controlled historical terminal rows, while the current composition independently proves real owner calls. Earlier component evidence below retains its original source attribution; this is focused receiving proof, not a complete service-suite or public admission result. R867 subsequently passes 23 current-parent receiving cases, including latest-schema issuer OPEN composition, controlled predecessor mutation receipt retention, shared region/Human regressions and authenticated Account abort cleanup, with affected static, frontier, generation, formatting and documentation checks. Historical receipt correlation remains controlled and claims no ordinary-NEW producer at the older schema. The current parent now owns the separately controlled V1038→V1038.1 retention case in the Account abort-composition test; its duplicate standalone Game Session fixture is removed here. Earlier proof retains its original source attribution. Operational source/incarnation custody, production PKI, default registration, public admission and activation remain unproved. +The receiving #3320 prerequisite contains unregistered issuer LIVE control, tenant-local issuer OPEN/cutoff owners and the separate binding-local issuer acknowledgement, together with INITIAL-only Account OPEN initialization. Ordinary binding preparation and issuer projection join current live issuer control; pending Account initializers are included in the acquisition cohort, and both barrier owners retain original dispatch and exact readback evidence without reopening uncertain or CLOSED targets. The INITIAL Account arm retains one original initializer per account, tenant and playable-state namespace even when the original LOGIN is abandoned before dispatch. A later LOGIN cannot retarget that retained `NEVER_DISPATCHED` initializer or allocate a replacement through this arm; absence of Redis work does not grant new initialization authority. Account-wide fenced recovery and settlement are not supplied here, so recovery of that scope remains unqualified and non-admitting. R902 freshly passes 55 selected cases: 14 Game Session units, 30 physical Game Session cases and 11 actual Account–Game Session abort/migration compositions, with affected enabled main/unit/integration static analysis, formatting and documentation checks. Prepared issuer reads no longer consume creation authority; each owner validates its local script inputs before its durable one-shot claim. Proof covers retained preclaim failure and valid retry, competing claims with one winner, lost-claim absence refusal, cutoffs before and after a claim, abandoned INITIAL retention, and PostgreSQL-observed inventory/control serialization in both arrival orders. The claims still commit before the remote attempt, so postclaim interruption remains non-admitting uncertainty without rearming or automatic recovery. This is focused component/composition proof with controlled upstream source and test PKI inputs, not a complete service-suite or production-admission result. This readiness boundary does not contain original-NEW candidate installation, Account bound credential/handle issuance, the final controller CAS, committed Game Session result reader or whole-flow coordinator; those remain dependent preparation and final-admission work. Extraction receiving proof R849 passes 75 of 76 selected unit/native cases, including the full 256-cycle physical-retirement case; its aggregate remains failed because the historical Account fixture opened V1038 while invoking current issuer readiness. R855 then passes both the corrected current authenticated-owner composition and a separate populated V1038→V1038.1 migration-retention proof. Its aggregate failed only an unused private fixture overload; R856 passes affected Account static, formatting and documentation checks after removing that overload. The migration fixture uses controlled historical terminal rows, while the current composition independently proves real owner calls. Earlier component evidence below retains its original source attribution; this is focused receiving proof, not a complete service-suite or public admission result. R867 subsequently passes 23 current-parent receiving cases, including latest-schema issuer OPEN composition, controlled predecessor mutation receipt retention, shared region/Human regressions and authenticated Account abort cleanup, with affected static, frontier, generation, formatting and documentation checks. Historical receipt correlation remains controlled and claims no ordinary-NEW producer at the older schema. The current parent now owns the separately controlled V1038→V1038.1 retention case in the Account abort-composition test; its duplicate standalone Game Session fixture is removed here. Earlier proof retains its original source attribution. Operational source/incarnation custody, production PKI, default registration, public admission and activation remain unproved. The current local correction adds explicit recovery for a stale, uninstalled initial issuer-bootstrap candidate. Forward V1038.3 retains its original intent, cohort and issued work, captures the new actual inventory cut under monotonic fences, and atomically binds immutable supersession lineage to current control. A strictly newer trusted layout separates old physical work; installed anchors remain ineligible. Account CI selection and migration task inputs now cover its Game Session owner-composition dependency, and the native registration-image and lost-reply proofs use their actual SQL/Lua contracts. R827 passes 31 of 32 focused cases; its remaining failure is a test assertion against the transaction wrapper rather than the nested PostgreSQL refusal. R828 then passes that complete recovery case with affected integration static and formatting checks. Together they qualify 32 distinct current-source cases, including two actual Account abort compositions; frontier, jOOQ, affected static, formatting and documentation checks pass. The new recovery sequence uses controlled Account terminal input through the actual Game Session abort owner, separately from those two authenticated Account compositions. This is focused proof, not a full service-suite, live layout rotation, retained-key cleanup or production-authority claim. @@ -361,11 +361,11 @@ Account connect-token issuance retains its existing bootstrap and scope authenti | Capability | Implementation | Verification | Design | Implementation anchors | Proof anchors | Secondary handoffs | Gap or decision | | --- | --- | --- | --- | --- | --- | --- | --- | | `AA-1.1` Account and profile identity | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Account runtime and data](../../architecture/microservices/account-service/runtime-and-data.md); [ADR 0042](../../architecture/decisions/adr-0042-global-account-and-tenant-scoped-game-relationships.md); [ADR 0020](../../architecture/decisions/adr-0020-scoped-domain-and-operational-identifiers.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [AccountDto.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountDto.java); [AccountMapper.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/mapper/AccountMapper.java); [AccountController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java); [ProfileController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/ProfileController.java); [AccountGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java); [RuntimeAccountIdentityGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/RuntimeAccountIdentityGrpcService.java); [AccountRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountRepository.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [openapi.yaml](../../../services/account-service/src/main/resources/openapi.yaml); [AccountIdentityProvenance.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountIdentityProvenance.java); [V1__init.sql](../../../services/account-service/src/main/resources/db/migration/V1__init.sql); [V26__global_registration_join_evidence.sql](../../../services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql); [V29__account_identity_uuid_bridge.sql](../../../services/account-service/src/main/resources/db/migration/V29__account_identity_uuid_bridge.sql) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountControllerTest.java); [PublicBootstrapRoutesProdProfileTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [RuntimeAccountIdentityGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/RuntimeAccountIdentityGrpcServiceTest.java); [AccountApplicationIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java); [AccountRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java); [ProfileControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/ProfileControllerTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Account V29 and `AccountRepository` persist/read back the non-nil Account UUID, recognized provenance, and unchanged numeric source-row identity required by ADR 0020. Registration REST/gRPC output and Account fields in the existing local exports now use that UUID; new registration audit records carry the same value, and the reverse DTO mapper is removed. `AccountDto` mapping rejects missing or contradictory UUID/provenance/source-row evidence. The focused unit/controller/gRPC suites executed 238 tests (174 AccountServiceImpl, 15 AccountController, 2 production-profile route, and 47 gRPC) with no failures, errors, or skips; the 5 PostgreSQL-backed Account application integration cases compiled but skipped because Docker is unavailable. Retained-row migration proof remains available but local PostgreSQL cases skip when Docker is disabled. Registration still creates global Account state plus its platform audit outbox row only, with no profile or tenant membership; caller-supplied tenant input is not authority. Authentication results and JWT subjects remain unchanged; profile/export profile identity fields and tenant IDs remain numeric and full portable export is not implemented. Current profile GET/PUT routes enforce exact caller-account subject binding and current tenant membership; tenant-qualified routes and membership-authority-generation validation remain gaps. Credential and email-OTP gameplay authentication remain global Account-identity operations that do not select a tenant or require current membership. `RuntimeAccountIdentityGrpcService` implements the authenticated Account-owner UUID/provenance read; its 31 focused unit cases, integration-source compilation, and formatting/documentation checks do not prove PostgreSQL execution or a live mTLS handshake, and do not enable UUID authentication or gameplay admission. Lifecycle-state retention remains tracked under AA-1.3. | -| `AA-1.2` Tenant membership, roles, and delegated access | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Authentication and authorization](../../architecture/system-architecture-authentication.md); [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md); [ADR 0042](../../architecture/decisions/adr-0042-global-account-and-tenant-scoped-game-relationships.md); [ADR 0138](../../architecture/decisions/adr-0138-expiring-playtest-grants-with-bounded-active-revocation.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [AccountJoinOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepository.java); [AccountConnectScopeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectScopeRepository.java); [ExpiredConnectScopeCleanupJob.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/ExpiredConnectScopeCleanupJob.java); [AccountAuditOutboxRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepository.java); [AccountCanonicalFirstJoinTerminalCoordinator.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinator.java); [AccountMembershipAuthorityEventProducer.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java); [AccountAuthorityGenerationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepository.java); [AccountAuthoritySourceEvidenceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidenceRepository.java); [AccountTenantAuthorityEventRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepository.java); [AccountDemoTenantEntitlementRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementRepository.java); [AccountTenantEntitlementOutboxRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantEntitlementOutboxRepository.java); [AccountActorStagingEligibilityService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountActorStagingEligibilityService.java); [AccountActorStagingEligibilityGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountActorStagingEligibilityGrpcService.java); [AccountActorStagingEligibilityRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountActorStagingEligibilityRepository.java); [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountTenantMembership.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountTenantMembership.java); [AccountRealmAccessGrant.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountRealmAccessGrant.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [V26__global_registration_join_evidence.sql](../../../services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql); [V27__retain_join_connect_scopes.sql](../../../services/account-service/src/main/resources/db/migration/V27__retain_join_connect_scopes.sql); [V30__approved_legacy_tenant_associations.sql](../../../services/account-service/src/main/resources/db/migration/V30__approved_legacy_tenant_associations.sql); [V31__subscription_authority_generation.sql](../../../services/account-service/src/main/resources/db/migration/V31__subscription_authority_generation.sql); [V32__realm_grant_currentness.sql](../../../services/account-service/src/main/resources/db/migration/V32__realm_grant_currentness.sql); [V33__fresh_tenant_identity_associations.sql](../../../services/account-service/src/main/resources/db/migration/V33__fresh_tenant_identity_associations.sql); [V34__account_membership_pair_authority.sql](../../../services/account-service/src/main/resources/db/migration/V34__account_membership_pair_authority.sql); [V35__canonical_uuid_membership_identity.sql](../../../services/account-service/src/main/resources/db/migration/V35__canonical_uuid_membership_identity.sql); [V36__account_auth_authority_generations.sql](../../../services/account-service/src/main/resources/db/migration/V36__account_auth_authority_generations.sql); [V37__canonical_first_join_scope_and_intent.sql](../../../services/account-service/src/main/resources/db/migration/V37__canonical_first_join_scope_and_intent.sql); [V38__account_first_join_authority_outbox_and_roles.sql](../../../services/account-service/src/main/resources/db/migration/V38__account_first_join_authority_outbox_and_roles.sql); [V39__canonical_first_join_terminal_receipt.sql](../../../services/account-service/src/main/resources/db/migration/V39__canonical_first_join_terminal_receipt.sql); [V40__account_authority_source_baselines.sql](../../../services/account-service/src/main/resources/db/migration/V40__account_authority_source_baselines.sql); [V53__account_protected_demo_entitlements.sql](../../../services/account-service/src/main/resources/db/migration/V53__account_protected_demo_entitlements.sql); [V73__account_tenant_authority_source_bridge.sql](../../../services/account-service/src/main/resources/db/migration/V73__account_tenant_authority_source_bridge.sql) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [AccountAuditDeliveryJobTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuditDeliveryJobTest.java); [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [ExpiredConnectScopeCleanupJobTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/ExpiredConnectScopeCleanupJobTest.java); [AccountAuditOutboxRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepositoryTest.java); [AccountJoinDigestTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountJoinDigestTest.java); [AccountAuthoritySourceEvidencePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java); [AccountDemoTenantEntitlementPersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementPersistenceIntegrationTest.java); [AccountCanonicalFirstJoinEventIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinEventIntegrationTest.java); [AccountCanonicalFirstJoinTerminalCoordinatorTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinatorTest.java); [AccountMembershipAuthorityEventProducerCanonicalJoinTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducerCanonicalJoinTest.java); [AccountAuthorityGenerationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepositoryTest.java); [AccountTenantAuthorityEventRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepositoryTest.java); [AccountActorStagingEligibilityServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountActorStagingEligibilityServiceTest.java); [AccountActorStagingEligibilityGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountActorStagingEligibilityGrpcServiceTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Membership and Account-owned realm-grant records/readers are separate. `AccountTenantAuthorityEventRepository` appends the canonical tenant authority event during demo entitlement provisioning; `AccountMembershipAuthorityEventProducer` emits the first-JOIN membership event with its billing cutoff taken from that current tenant authority event, covered by [AccountCanonicalFirstJoinEventIntegrationTest](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinEventIntegrationTest.java); no entitlement caller wires it, and current PostgreSQL proof remains pending because the integration source compiled but was unrun locally. Current connect-token issuance returns `AUTH_UNAVAILABLE` before replay-cache or fresh pointer/visibility/membership reads while the canonical producer is unavailable; target current-authority and postcondition revalidation remain unproved. Current explicit `JoinPublicProductionMembership` validates a server-issued scope and caller binding, re-reads Game Session routing/catalog/pointer evidence before the Account transaction, and binds a v1 digest to verified caller/scope inputs; it does not guarantee that the exact target/catalog/pointer remains valid through Account commit. The strict ADR 0025 commit gate remains incomplete, and no durable Game Session-owned target fence is implemented or proved; transaction duration or timing thresholds alone would not prove it. The subscription authority query's `FOR UPDATE` locks only the subscription row, not its joined billing-owner Account; JOIN also locks the caller Account and operation record. Terminal-operation replay performs remote scope/target/entitlement checks outside its lock-holding transaction. Pending JOINs continue to receive fresh remote reads, while the Account transaction retains atomic membership, operation-outcome, and audit-outbox persistence. Focused unit proof verifies terminal replay revalidation occurs after commit or rollback without rewriting the stored outcome; the PostgreSQL row-lock regression compiles but skips locally without Docker. PostgreSQL runtime proof and direct text-client end-to-end proof are unclaimed. Global-only registration no longer creates an admitting membership. Expired unreferenced connect-scope rows are swept under their existing expiry; V27's restrictive scope FK preserves every scope referenced by a PENDING or terminal JOIN and fences racing intent inserts. JOIN recovery/reconciliation after an unknown database commit outcome remains a separate #2848 gap under the Overseer decision; do not mark ADR 0025 complete. The Gateway continues to block public JOIN exposure, and Game Session text JOIN/Join & Play dispatch remains #2898. `AccountActorStagingEligibilityGrpcService` is a read-only internal eligibility check disabled by default; it does not establish that a realm is public or preseeded and grants no gameplay admission. Membership authority generation in runtime admission, issuance grant validation, cached-success freshness/postcondition revalidation, and the target five-field grant codec with cross-service producer/consumer and admission-propagation proof remain incomplete. Current non-public discovery and supported text `PLAY` require admitting membership before the applicable realm grant; connect-token issuance fails closed before these checks and does not establish target grant validation. Transactional outboxes beyond the implemented registration/JOIN audit records, monotonic versioning, rate limits, tenant-scoped roles, and delegated management remain target gaps; see the [canonical Redis grant codec](../../architecture/system-architecture-redis.md#canonical-grant-authority-stream-scope-codec) and [identifier glossary](../../architecture/system-architecture-identifier-glossary.md#non-public-grant-identity). | +| `AA-1.2` Tenant membership, roles, and delegated access | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Authentication and authorization](../../architecture/system-architecture-authentication.md); [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md); [ADR 0042](../../architecture/decisions/adr-0042-global-account-and-tenant-scoped-game-relationships.md); [ADR 0138](../../architecture/decisions/adr-0138-expiring-playtest-grants-with-bounded-active-revocation.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [AccountJoinOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepository.java); [AccountConnectScopeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectScopeRepository.java); [ExpiredConnectScopeCleanupJob.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/ExpiredConnectScopeCleanupJob.java); [AccountAuditOutboxRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepository.java); [AccountCanonicalFirstJoinTerminalCoordinator.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinator.java); [AccountMembershipAuthorityEventProducer.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java); [AccountAuthorityGenerationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepository.java); [AccountAuthoritySourceEvidenceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidenceRepository.java); [AccountTenantAuthorityEventRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepository.java); [AccountDemoTenantEntitlementRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementRepository.java); [AccountTenantEntitlementOutboxRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantEntitlementOutboxRepository.java); [AccountActorStagingEligibilityService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountActorStagingEligibilityService.java); [AccountActorStagingEligibilityGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountActorStagingEligibilityGrpcService.java); [AccountActorStagingEligibilityRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountActorStagingEligibilityRepository.java); [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountTenantMembership.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountTenantMembership.java); [AccountRealmAccessGrant.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountRealmAccessGrant.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [V26__global_registration_join_evidence.sql](../../../services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql); [V27__retain_join_connect_scopes.sql](../../../services/account-service/src/main/resources/db/migration/V27__retain_join_connect_scopes.sql); [V30__approved_legacy_tenant_associations.sql](../../../services/account-service/src/main/resources/db/migration/V30__approved_legacy_tenant_associations.sql); [V31__subscription_authority_generation.sql](../../../services/account-service/src/main/resources/db/migration/V31__subscription_authority_generation.sql); [V32__realm_grant_currentness.sql](../../../services/account-service/src/main/resources/db/migration/V32__realm_grant_currentness.sql); [V33__fresh_tenant_identity_associations.sql](../../../services/account-service/src/main/resources/db/migration/V33__fresh_tenant_identity_associations.sql); [V34__account_membership_pair_authority.sql](../../../services/account-service/src/main/resources/db/migration/V34__account_membership_pair_authority.sql); [V35__canonical_uuid_membership_identity.sql](../../../services/account-service/src/main/resources/db/migration/V35__canonical_uuid_membership_identity.sql); [V36__account_auth_authority_generations.sql](../../../services/account-service/src/main/resources/db/migration/V36__account_auth_authority_generations.sql); [V37__canonical_first_join_scope_and_intent.sql](../../../services/account-service/src/main/resources/db/migration/V37__canonical_first_join_scope_and_intent.sql); [V38__account_first_join_authority_outbox_and_roles.sql](../../../services/account-service/src/main/resources/db/migration/V38__account_first_join_authority_outbox_and_roles.sql); [V39__canonical_first_join_terminal_receipt.sql](../../../services/account-service/src/main/resources/db/migration/V39__canonical_first_join_terminal_receipt.sql); [V40__account_authority_source_baselines.sql](../../../services/account-service/src/main/resources/db/migration/V40__account_authority_source_baselines.sql); [V53__account_protected_demo_entitlements.sql](../../../services/account-service/src/main/resources/db/migration/V53__account_protected_demo_entitlements.sql); [V73__account_tenant_authority_source_bridge.sql](../../../services/account-service/src/main/resources/db/migration/V73__account_tenant_authority_source_bridge.sql); [CanonicalGameplayAccountInitialBarrierInitializerRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierInitializerRepository.java); [CanonicalGameplayAccountInitialBarrierRedisOwner.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierRedisOwner.java); [V1047__canonical_initial_account_admission_barrier.sql](../../../services/game-session-service/src/main/resources/db/migration/V1047__canonical_initial_account_admission_barrier.sql) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [AccountAuditDeliveryJobTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuditDeliveryJobTest.java); [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [ExpiredConnectScopeCleanupJobTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/ExpiredConnectScopeCleanupJobTest.java); [AccountAuditOutboxRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepositoryTest.java); [AccountJoinDigestTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountJoinDigestTest.java); [AccountAuthoritySourceEvidencePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java); [AccountDemoTenantEntitlementPersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementPersistenceIntegrationTest.java); [AccountCanonicalFirstJoinEventIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinEventIntegrationTest.java); [AccountCanonicalFirstJoinTerminalCoordinatorTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinatorTest.java); [AccountMembershipAuthorityEventProducerCanonicalJoinTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducerCanonicalJoinTest.java); [AccountAuthorityGenerationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepositoryTest.java); [AccountTenantAuthorityEventRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepositoryTest.java); [AccountActorStagingEligibilityServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountActorStagingEligibilityServiceTest.java); [AccountActorStagingEligibilityGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountActorStagingEligibilityGrpcServiceTest.java); [CanonicalGameplayProtectedIncarnationReceiverPostgresIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayProtectedIncarnationReceiverPostgresIntegrationTest.java); [CanonicalGameplayAccountInitialBarrierRedisScriptIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierRedisScriptIntegrationTest.java); [readiness receiving proof](#canonical-new-admission-components) records R849 partial execution, R855/R856 recovery, R867 and current R902 focused results with their separate limits | [Realm Routing](./realm-routing-and-playable-state.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Membership and Account-owned realm-grant records/readers are separate. `AccountTenantAuthorityEventRepository` appends the canonical tenant authority event during demo entitlement provisioning; `AccountMembershipAuthorityEventProducer` emits the first-JOIN membership event with its billing cutoff taken from that current tenant authority event, covered by [AccountCanonicalFirstJoinEventIntegrationTest](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinEventIntegrationTest.java); no entitlement caller wires it, and current PostgreSQL proof remains pending because the integration source compiled but was unrun locally. Current connect-token issuance returns `AUTH_UNAVAILABLE` before replay-cache or fresh pointer/visibility/membership reads while the canonical producer is unavailable; target current-authority and postcondition revalidation remain unproved. Current explicit `JoinPublicProductionMembership` validates a server-issued scope and caller binding, re-reads Game Session routing/catalog/pointer evidence before the Account transaction, and binds a v1 digest to verified caller/scope inputs; it does not guarantee that the exact target/catalog/pointer remains valid through Account commit. The strict ADR 0025 commit gate remains incomplete, and no durable Game Session-owned target fence is implemented or proved; transaction duration or timing thresholds alone would not prove it. The subscription authority query's `FOR UPDATE` locks only the subscription row, not its joined billing-owner Account; JOIN also locks the caller Account and operation record. Terminal-operation replay performs remote scope/target/entitlement checks outside its lock-holding transaction. Pending JOINs continue to receive fresh remote reads, while the Account transaction retains atomic membership, operation-outcome, and audit-outbox persistence. Focused unit proof verifies terminal replay revalidation occurs after commit or rollback without rewriting the stored outcome; the PostgreSQL row-lock regression compiles but skips locally without Docker. PostgreSQL runtime proof and direct text-client end-to-end proof are unclaimed. Global-only registration no longer creates an admitting membership. Expired unreferenced connect-scope rows are swept under their existing expiry; V27's restrictive scope FK preserves every scope referenced by a PENDING or terminal JOIN and fences racing intent inserts. JOIN recovery/reconciliation after an unknown database commit outcome remains a separate #2848 gap under the Overseer decision; do not mark ADR 0025 complete. The Gateway continues to block public JOIN exposure, and Game Session text JOIN/Join & Play dispatch remains #2898. `AccountActorStagingEligibilityGrpcService` is a read-only internal eligibility check disabled by default; it does not establish that a realm is public or preseeded and grants no gameplay admission. Membership authority generation in runtime admission, issuance grant validation, cached-success freshness/postcondition revalidation, and the target five-field grant codec with cross-service producer/consumer and admission-propagation proof remain incomplete. Current non-public discovery and supported text `PLAY` require admitting membership before the applicable realm grant; connect-token issuance fails closed before these checks and does not establish target grant validation. Transactional outboxes beyond the implemented registration/JOIN audit records, monotonic versioning, rate limits, tenant-scoped roles, and delegated management remain target gaps; see the [canonical Redis grant codec](../../architecture/system-architecture-redis.md#canonical-grant-authority-stream-scope-codec) and [identifier glossary](../../architecture/system-architecture-identifier-glossary.md#non-public-grant-identity). The unregistered INITIAL Account prerequisite preserves one original target and does not supply abandoned-target or account-wide fenced recovery, fresh Account authority, final admission or runtime activation; see the [readiness scope and proof](#canonical-new-admission-components). | | `AA-1.3` Authentication, recovery, security policy, and account data rights | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Security](../../architecture/system-architecture-security.md); [Account runtime and data](../../architecture/microservices/account-service/runtime-and-data.md); [Moderation Policies](../../architecture/microservices/logging-admin-service/moderation-policies.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0034](../../architecture/decisions/adr-0034-layered-abuse-controls-without-attacker-triggered-account-locks.md); [ADR 0035](../../architecture/decisions/adr-0035-single-record-issued-token-registry.md); [ADR 0141](../../architecture/decisions/adr-0141-fixed-safety-restriction-categories-and-independent-lifecycles.md); [ADR 0142](../../architecture/decisions/adr-0142-bounded-moderation-appeal-cases.md); [ADR 0047](../../architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md); [Account API Contracts](../../architecture/microservices/account-service/api-contracts.md#operator-authorization-references); [Logging & Admin API Contracts](../../architecture/microservices/logging-admin-service/api-contracts.md); [Game Session API Contracts](../../architecture/microservices/game-session-service/api-contracts.md) | [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java); [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [SessionServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/SessionServiceImpl.java); [JwksController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/JwksController.java); [AccountAuthorityGenerationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepository.java); [AccountAuthoritySourceEvidenceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidenceRepository.java); [AccountJwtSignerDesiredStateRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtSignerDesiredStateRepository.java); [AccountJwtReadinessProbeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtReadinessProbeRepository.java); [AccountControlUiIssuanceService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceService.java); [AccountStartSessionOperatorAuthorizationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationService.java); [AccountJwtSignerMaterializationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationService.java); [application-prod.yml](../../../services/account-service/src/main/resources/application-prod.yml); [V36__account_auth_authority_generations.sql](../../../services/account-service/src/main/resources/db/migration/V36__account_auth_authority_generations.sql); [V40__account_authority_source_baselines.sql](../../../services/account-service/src/main/resources/db/migration/V40__account_authority_source_baselines.sql); [V77 reset receipts](../../../services/account-service/src/main/resources/db/migration/V77__account_password_reset_operation_receipts.sql); [V89 pending reset intent](../../../services/account-service/src/main/resources/db/migration/V89__account_password_reset_pending_draft_source_changes.sql); [V99__account_jwt_signer_desired_state.sql](../../../services/account-service/src/main/resources/db/migration/V99__account_jwt_signer_desired_state.sql); [V123__account_jwt_readiness_per_pod_closure.sql](../../../services/account-service/src/main/resources/db/migration/V123__account_jwt_readiness_per_pod_closure.sql); [V125__account_jwt_signer_promotion_receipt_binding.sql](../../../services/account-service/src/main/resources/db/migration/V125__account_jwt_signer_promotion_receipt_binding.sql); [V126](../../../services/account-service/src/main/resources/db/migration/V126__start_session_operator_authorization.sql); [V126.1](../../../services/account-service/src/main/resources/db/migration/V126.1__start_session_operator_response_envelope_erasure.sql); [V126.2](../../../services/account-service/src/main/resources/db/migration/V126.2__account_control_ui_registry_cleanup_deadline.sql); [V126.3](../../../services/account-service/src/main/resources/db/migration/V126.3__start_session_response_envelope_bounds.sql); [AccountPlatformRestrictionOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationRepository.java); [V137__account_platform_restriction_revision_receipts.sql](../../../services/account-service/src/main/resources/db/migration/V137__account_platform_restriction_revision_receipts.sql); [V137.1__account_platform_restriction_lifecycle_consistency.sql](../../../services/account-service/src/main/resources/db/migration/V137.1__account_platform_restriction_lifecycle_consistency.sql); [AccountPlatformRestrictionMutationRequest.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountPlatformRestrictionMutationRequest.java); [AccountSecurityStateAuthorityEventV1Codec.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1Codec.java); [AccountAuthoritySourceEventReadback.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadback.java); [AccountPasswordResetOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepository.java); [AccountPasswordResetDraftSourceChangeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPasswordResetDraftSourceChangeRepository.java); [PasswordResetTokenRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/PasswordResetTokenRepository.java); [V140](../../../services/account-service/src/main/resources/db/migration/V140__account_gameplay_admission_lease_operations.sql); [V141](../../../services/account-service/src/main/resources/db/migration/V141__account_admission_unknown_decision_abort.sql); [V142](../../../services/account-service/src/main/resources/db/migration/V142__account_admission_durable_commit_confirmation.sql); [V143](../../../services/account-service/src/main/resources/db/migration/V143__account_global_pending_admission_fences.sql); [V144](../../../services/account-service/src/main/resources/db/migration/V144__account_admission_original_ack_receipt.sql); [V145](../../../services/account-service/src/main/resources/db/migration/V145__retire_experimental_admission_confirmation_writes.sql); [V146](../../../services/account-service/src/main/resources/db/migration/V146__account_original_ack_pg18_fresh_insert.sql); [AccountGameplayAdmissionLeaseRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeaseRepository.java); [AccountGameplayAdmissionOriginalCommitExecutor.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalCommitExecutor.java); [AccountGameplayAdmissionOriginalAckReceiptRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptRepository.java); [AccountGameplayAdmissionOriginalAckReceiptCommitExecutor.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptCommitExecutor.java); [V158](../../../services/account-service/src/main/resources/db/migration/V158__account_start_session_authority_captures.sql); [V159](../../../services/account-service/src/main/resources/db/migration/V159__start_session_world_participation.sql); [V160](../../../services/account-service/src/main/resources/db/migration/V160__start_session_world_original_attempt_evidence.sql); [AccountStartSessionAuthorityCaptureRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCaptureRepository.java); [AccountStartSessionWorldParticipationRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationRepository.java); [AccountStartSessionWorldOriginalAttemptEvidenceRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidenceRepository.java); [V160.1](../../../services/account-service/src/main/resources/db/migration/V160.1__start_session_operator_bundle_source_fence.sql); [AccountStartSessionWorldParticipationAcquisitionService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationAcquisitionService.java); [AccountStartSessionWorldParticipationHistoricalReadService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationHistoricalReadService.java); [AccountStartSessionWorldParticipationSettlementService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationSettlementService.java); [Logging StartSessionAuthorizationCoordinator.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinator.java); [Logging StartSessionOperatorAuthorizationClient.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClient.java); [Logging StartSessionPreAuthorizationReservationRepository.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/repository/StartSessionPreAuthorizationReservationRepository.java); [Game Session StartSessionOperatorRedemptionClient.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClient.java); [GameSessionStartSessionOperatorAttemptRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepository.java); [GameSessionCanonicalLaunchPreparationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationService.java); [CanonicalGameInstanceLaunchAssociationRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameInstanceLaunchAssociationRepository.java); [V1003 original StartSession protections](../../../services/account-service/src/main/resources/db/migration/V1003__original_start_session_source_protections.sql); [V1004 activation settlement lifecycle integrity](../../../services/account-service/src/main/resources/db/migration/V1004__activation_settlement_lifecycle_integrity.sql); [V1004.1 monotonic lifecycle counters](../../../services/account-service/src/main/resources/db/migration/V1004.1__activation_settlement_monotonic_lifecycle_counters.sql); [V1004.2 retained lifecycle and canonical UUID integrity](../../../services/account-service/src/main/resources/db/migration/V1004.2__activation_settlement_retained_lifecycle_integrity.sql); [V1004.3 canonical activation acquisition carriers](../../../services/account-service/src/main/resources/db/migration/V1004.3__activation_acquisition_canonical_carriers.sql); [AccountStartSessionActivationProtectionRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionRepository.java); [V1006 World activation terminal digest alignment](../../../services/account-service/src/main/resources/db/migration/V1006__world_activation_terminal_digest_alignment.sql); [V1007 selected source reservations](../../../services/account-service/src/main/resources/db/migration/V1007__selected_owner_intake_source_reservations.sql); [AccountSelectedOwnerIntakeSourceReservationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationService.java); [V1008 selected-owner intake final authorizations](../../../services/account-service/src/main/resources/db/migration/V1008__selected_owner_intake_final_authorizations.sql); [V1009 selected-owner intake terminal settlement](../../../services/account-service/src/main/resources/db/migration/V1009__selected_owner_intake_terminal_settlement.sql); [V1010 Entity selected-owner intake terminal settlement](../../../services/account-service/src/main/resources/db/migration/V1010__entity_selected_owner_intake_terminal_settlement.sql); [AccountSelectedOwnerIntakeSettlementService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementService.java); [AccountSelectedOwnerIntakeAuthorizationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationService.java); [AccountSelectedOwnerIntakeWorldClosureAuthorizationReadService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeWorldClosureAuthorizationReadService.java); [AccountSelectedOwnerIntakeSettlementReceipt.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/AccountSelectedOwnerIntakeSettlementReceipt.java); [AccountStartSessionAdmissionProtectionAcquisitionService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionService.java); [AccountStartSessionAdmissionProtectionSettlementService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionSettlementService.java); [AccountStartSessionAdmissionProtectionGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionGrpcService.java); [AccountStartSessionAdmissionProtectionRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionRepository.java) | [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [JwksControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/JwksControllerTest.java); [AuthTokenInterceptorTest.java](../../../services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/AuthTokenInterceptorTest.java); [AccountAuthorityGenerationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepositoryTest.java); [AccountAuthoritySourceEvidencePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java); [PasswordResetAuthorityProducerPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/PasswordResetAuthorityProducerPostgresIntegrationTest.java); [AccountPasswordResetOperationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepositoryTest.java); [AccountJwtSignerStoragePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountJwtSignerStoragePostgresIntegrationTest.java); [AccountJwtReadinessStoragePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessStoragePostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java); [AccountControlUiIssuancePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuancePostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorizationConfigurationTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountStartSessionOperatorAuthorizationConfigurationTest.java); [AccountJwtJwksTrustedSourceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksTrustedSourceTest.java); [AccountStartSessionOperatorAuthorizationServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationServiceTest.java); [StartSessionOperatorAuthorizationGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/StartSessionOperatorAuthorizationGrpcServiceTest.java); [AccountJwtSignerMaterializationServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationServiceTest.java); [AccountPlatformRestrictionOperationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationPostgresIntegrationTest.java); [AccountPlatformRestrictionOperationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationRepositoryTest.java); [AccountAuthoritySourceEventReadbackTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadbackTest.java); [AccountSecurityStateAuthorityEventV1CodecTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1CodecTest.java); [AccountGenerationProjectionRestrictionDispatchTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountGenerationProjectionRestrictionDispatchTest.java); [RuntimeMembershipAuthorityEvidenceValidatorRestrictionDispatchTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimeMembershipAuthorityEvidenceValidatorRestrictionDispatchTest.java); [AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java); [AccountStartSessionWorldParticipationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationPostgresIntegrationTest.java); [AccountStartSessionWorldOriginalAttemptEvidencePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidencePostgresIntegrationTest.java); [AccountStartSessionAuthorityCapturePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCapturePostgresIntegrationTest.java); [HostedTermsDisclosureHandoffPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/HostedTermsDisclosureHandoffPostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorityBundleTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorityBundleTest.java); [Logging StartSessionOperatorAuthorizationClientTest.java](../../../services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClientTest.java); [Logging StartSessionAuthorizationCoordinatorTest.java](../../../services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinatorTest.java); [Logging reservation PostgreSQL test](../../../services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/StartSessionPreAuthorizationReservationPostgresIntegrationTest.java); [Game Session StartSessionOperatorRedemptionClientTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClientTest.java); [Game Session operator-attempt storage test](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepositoryIntegrationTest.java); [Game Session canonical launch preparation test](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationServiceIntegrationTest.java); [Admission protection PostgreSQL suite](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java); [Activation protection PostgreSQL suite](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionPostgresIntegrationTest.java); [AccountSelectedOwnerIntakeSourceReservationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationPostgresIntegrationTest.java); [SelectedOwnerSourceDisclosurePostgresIntegrationTest.java](../../../services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedOwnerSourceDisclosurePostgresIntegrationTest.java); [AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java); [AccountSelectedOwnerIntakeSettlementServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementServiceTest.java); [SelectedOwnerIntakeSettlementGrpcCodecTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSettlementGrpcCodecTest.java); [AccountStartSessionAdmissionProtectionAcquisitionPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionPostgresIntegrationTest.java); [AccountStartSessionAdmissionProtectionRepositoryPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionRepositoryPostgresIntegrationTest.java); [AccountStartSessionAdmissionProtectionServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionServiceTest.java); [AccountStartSessionAdmissionProtectionGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionGrpcServiceTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md); [Platform Operations](./platform-operations-and-delivery.md) | Public password-reset, username-recovery, and email-verification initiation use normalized email selectors and return the same neutral HTTP success for known and unknown addresses, including when known-account post-commit SMTP errors are caught and logged; unknown addresses create no token or delivery attempt. However, SMTP delivery remains synchronous after commit and is a timing oracle; durable asynchronous delivery is absent, and focused service tests prove exception containment only, not timing resistance or durable delivery. Public verification accepts no numeric account selector. The login-factor `PUT` now fails closed with `501 NOT_IMPLEMENTED` because Account has no recent ordinary reauthentication evidence mechanism; implementing that Account-owned proof and enabling the mutation remain open under ADR 0045. The current Account restriction slice adds a closed restriction event variant, V137 immutable revision/current-result receipts, exact SQL source-head dispatch, and protective-category lifecycle sync; the owner mutation stays default-denied because no authoritative policy/intent and authenticated-caller proof receiver exists. V137.1 adds forward final-state protective-category consistency guards while preserving published V137 and retained V126.x bytes. The staged Java writer rejects protective restrictions on pending-deletion and deleted accounts before side effects; supported deletion/recovery producer sequencing remains a gap. V81 (source V88) `NONRESTRICTED` birth results remain historical predecessor evidence, not current absence; physical forward migration, contradiction rollback, concurrency, and readback proof remain pending, so no authorized admission or end-to-end enforcement is claimed. Separate complete bounded moderation appeal handoff, `/auth/logout` and `/auth/logout-all` revocation authority, TOTP, trusted source context, Account-owned graduated login throttles, and fail-closed limiter-outage behavior remain absent. Current token issuance still writes scope-duplicated account/tenant keys and downstream validators do not enforce the one-record issued-token registry from ADR 0035. `AUTH_ACCOUNT_LOCKED` remains reserved, while the current Game Session command limiter performs a Redis operation per command contrary to ADR 0034. Current `AccountServiceImpl.deleteAccount` fails closed by rejecting any retained JOIN operation first, then nonterminal subscriptions, and otherwise throwing `ACCOUNT_DELETE_UNAVAILABLE` before any repository deletion; retained-data lifecycle and deletion reconciliation remain unimplemented. Password-reset token consumption and exact source-fenced completion are implemented for Accounts with valid current source evidence; reset-driven revocation, other recovery workflows, and passing physical PostgreSQL proof remain incomplete. Export and JWKS foundations are live. Account signer lifecycle, current readiness, and validator-inventory storage remain passive V99–V125 evidence preparation; focused physical PostgreSQL 18 signer/readiness suites confirm bounded storage proof only with synthetic inventory/resource inputs, not live Kubernetes currentness, readiness activation, or signer activation; signer runtime/currentness remains inactive. V126/V126.1 separately add Account-owned StartSession authorization and signer-materialization source preparation: StartSession composition remains off by default, materializer trust remains off by default and denies every RPC when absent, and missing bootstrap-coordinator composition denies enrollment and promotion. These source adapters do not register a runtime issuer or promotion/consumer coordinator, establish operator lifecycle ownership under AA-1.3, or establish activation. The current AA-1.3 owner-source cut also includes V126.2 cleanup-deadline storage and V126.3 response-envelope size-guard migration. At exact source head `44bbd2a9fff1e1561816e16fd0deb9cc274ae251`, the Control-UI issuance PostgreSQL suite passed 5/5, including retained-V126.2 row preservation and denial; direct PostgreSQL proof that a newly recorded cleanup deadline cannot be changed remains a tracked gap. Bounded cleanup and late revocation remain incomplete. StartSession recovery accepts a 128 KiB authority bundle and 144 KiB binding/response within the 160 KiB envelope ceiling; the exact-head authorization repository suite passed 15/15 and covers fresh-install, ambiguous legacy-guard rejection, the 160 KiB storage edge, and retained maximum-size V126.2 ciphertext through V126.3 migration. This is bounded fixture proof and does not establish complete mTLS flow or runtime activation. Current receiving original-ACK PostgreSQL proof remains pending. The Account admission-protection acquisition, settlement, gRPC and repository sources are manually composed, but remain unregistered. Focused proof is recorded by the acquisition PostgreSQL, repository PostgreSQL, service unit and gRPC service unit suites linked above; this does not establish runtime registration, the downstream final-admission path, production authority or PKI, operational custody, or Entity placement and delivery. The World protected-activation consumer is also unregistered. The historical R9 report above records 13 Account PostgreSQL cases and four composed World/Account/Game Session cases, including exact authenticated World terminal settlement, with its missing tested-snapshot and original XML attribution stated explicitly. The separately source-bound receiving proof above qualifies only its named scope. These controlled upstream inputs establish no broader proof; runtime registration, genuine upstream authority, admission, Entity placement and delivery remain unproved. V1003 storage remains passive and V1004 lifecycle integrity checks do not authenticate World. V1004.1 and V1004.2 provide storage checks for nondecreasing lifecycle counters, retained PREPARING evidence, and canonical activation-request UUID spelling. V1004.3 requires canonical Base64 spellings for the tuple, projection, launch-read, and PREPARING lifecycle carriers at acquisition; its focused physical PostgreSQL and retained-row upgrade proof passes in the 25-case Account gate, including all 16 whitespace variants. These are controlled Account integrity checks; authenticated World production and runtime activation remain unproved. | | `AA-1.4` Commerce, subscriptions, purchases, donations, and platform fees | `partial` | `audited` | [Subscription management](../../architecture/microservices/account-service/subscription-management.md); [Stripe integration](../../architecture/microservices/account-service/stripe-integration.md); [Account runtime/data](../../architecture/microservices/account-service/runtime-and-data.md); [ADR 0143](../../architecture/decisions/adr-0143-stripe-v1-hosting-billing-and-deferred-creator-monetization.md) | [PaymentServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImpl.java); [PurchaseWorkflowServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PurchaseWorkflowServiceImpl.java); [PaymentTransaction.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/PaymentTransaction.java); [Subscription.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Subscription.java); [payment_service.proto](../../../protos/account/v1/payment_service.proto); [V2__payment_tables.sql](../../../services/account-service/src/main/resources/db/migration/V2__payment_tables.sql); [application.yml](../../../services/account-service/src/main/resources/application.yml) | [PaymentServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImplTest.java); [PaymentGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentGrpcServiceTest.java); [PurchaseWorkflowServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PurchaseWorkflowServiceImplTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Incomplete subscription creation now fails closed before mutation instead of persisting a caller-selected locally active entitlement row. The target caller-bound billing-owner, stable request/digest, instrument, outbox, provider lifecycle/reconciliation, billing-safe owner transfer/deletion guards, and complete subscription-to-entitlement follow-through remain absent. Before first subscription creation can be enabled, Account must define the authoritative initial billing-owner source and consent/assignment workflow with a version/generation fence; no such source is selected, and caller-supplied account ID, tenant role, Creator Party, or payment-instrument ownership must not be inferred as that authority. The generic `CreatePaymentIntent`, `CreateDonation`, and `RefundPayment` RPCs fail closed with `FAILED_PRECONDITION` before `PaymentService` or provider invocation; the generic service/provider substrate remains unsupported. Creator/player purchases, donations, fees/shares, payouts, and settlement are deferred and not supported by current code. | | `AA-1.5` Entitlements, quotas, and hosting eligibility | `partial` | `drift-found` | [Subscription management](../../architecture/microservices/account-service/subscription-management.md); [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Versioning and runtime](../../architecture/system-architecture-versioning-runtime.md); [ADR 0028](../../architecture/decisions/adr-0028-differentiated-entitlement-freshness.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [RuntimeEntitlementsDto.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/RuntimeEntitlementsDto.java); [Subscription.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Subscription.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [application.yml](../../../services/account-service/src/main/resources/application.yml) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [PublicBootstrapRoutesProdProfileTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Game Authoring](./game-authoring-publishing-and-activation.md) | The producer returns retryable `ENTITLEMENT_UNAVAILABLE` for zero or multiple tenant subscription rows and projects status only from exactly one explicit row; gRPC carries the unavailable outcome in its error field and HTTP bootstrap routes map it to 503. Focused Account proofs cover zero rows, conflicting active/canceled rows, gRPC classification, and connect-token retry after recovery without caching an unavailable receipt. Explicit free/trial row creation and authoritative current-row selection/constraint/history remain absent. The runtime response still lacks committed status and the full explicit entitlement/freshness evidence; its row-ID-derived version/sequence and newly stamped evaluation time, quotas, real sequencing/source freshness, caching/events, strict new-commitment enforcement, five-minute continuity, and instance lifecycle enforcement remain open. The target handoff between fresh connect-token reissuance and eligible exact-binding entitlement-only reconnect continuity is unresolved: token expiry can block that continuity before Account's resume lease, and no fallback reissuance path is authorized pending owner decision. Current `past_due` handling remains gameplay-available and public-join-eligible only when the sole explicit row is `past_due`. | -| `AA-2.1` Gameplay login, character selection, and session binding | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0021](../../architecture/decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md); [JWT and Token Contracts](../../architecture/system-architecture-jwt-and-token-contracts.md#game-session-original-attempt-coordination); [Gateway Architecture](../../architecture/system-architecture-gateway.md#gameplay-websocket-route) | [SessionAuthenticationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionAuthenticationService.java); [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [CanonicalGameplayMigrationDriverMain.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMain.java); [CanonicalGameplayMigrationDriverProtocol.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocol.java); [CanonicalGameplayMigrationDriverLauncher.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverLauncher.java); [game-session-service build](../../../services/game-session-service/build.gradle.kts); [AccountGameplayCanonicalLoginOwner.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayCanonicalLoginOwner.java); [AccountGameplayDelegationIssuanceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuanceRepository.java); [V147__account_gameplay_delegation_issuance.sql](../../../services/account-service/src/main/resources/db/migration/V147__account_gameplay_delegation_issuance.sql); [V157.1__account_gameplay_token_fence_truncate_guard.sql](../../../services/account-service/src/main/resources/db/migration/V157.1__account_gameplay_token_fence_truncate_guard.sql); [CanonicalGameplayRosterSelectionService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionService.java); [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [GatewayFirstPartyConnectContextEnvelope.java](../../../services/common-security/src/main/java/net/firedevops/firemud/common/security/GatewayFirstPartyConnectContextEnvelope.java); [FirstPartyConnectContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContext.java); [FirstPartyConnectContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextService.java); [FirstPartyConnectContextRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextRegistry.java); [FirstPartyConnectContextResolution.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextResolution.java); [RedisFirstPartyConnectContextRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisFirstPartyConnectContextRegistry.java); [GameSessionWebSocketHandshakeInterceptor.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptor.java); [GameSessionWebSocketHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandler.java); [SessionRoutingNormalizationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationService.java); [InitialGameplayLoginOwner.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialGameplayLoginOwner.java); [CanonicalGameplayLoginAccountClient.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalGameplayLoginAccountClient.java); [CanonicalGameplayLoginResult.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalGameplayLoginResult.java); [GameplayHandshakeFilter.java](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/filter/GameplayHandshakeFilter.java); [GameplayRouteReadinessHealthIndicator.java](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/health/GameplayRouteReadinessHealthIndicator.java); [FirstPartyConnectContextConfig.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/FirstPartyConnectContextConfig.java); [FirstPartyConnectContextProperties.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/FirstPartyConnectContextProperties.java); [CanonicalPlayerRouteReadService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalPlayerRouteReadService.java); [SessionContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContext.java); [RedisSessionContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java); [ActiveTransportSessionRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/ActiveTransportSessionRegistry.java); [InMemoryActiveTransportSessionRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/InMemoryActiveTransportSessionRegistry.java); [CommunicationRecipientDeliveryService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CommunicationRecipientDeliveryService.java); [PlayerOutputDeliveryService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/PlayerOutputDeliveryService.java) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [CanonicalGameplayMigrationDriverMainTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMainTest.java); [CanonicalGameplayMigrationDriverProtocolTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocolTest.java); [CanonicalGameplayMigrationDriverStdoutTest.java](../../../services/game-session-service/src/test/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverStdoutTest.java); [migration-driver image contract](../../../dev-tools/tests/game-session-migration-driver-image-contract.sh); [V34.3 PostgreSQL fixture](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayInitialAdmissionIntentRequestIdMigrationIntegrationTest.java); [AccountGameplayCanonicalLoginOwnerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayCanonicalLoginOwnerTest.java); [AccountGameplayDelegationIssuancePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuancePersistenceIntegrationTest.java); [CanonicalGameplayRosterSelectionServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionServiceTest.java); [GatewayFirstPartyConnectContextEnvelopeTest.java](../../../services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/GatewayFirstPartyConnectContextEnvelopeTest.java); [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [FirstPartyConnectContextServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextServiceTest.java); [FirstPartyConnectContextResolutionTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextResolutionTest.java); [RedisFirstPartyConnectContextRegistryTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisFirstPartyConnectContextRegistryTest.java); [GameSessionWebSocketHandshakeInterceptorTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptorTest.java); [GameSessionWebSocketHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerTest.java); [InitialGameplayLoginOwnerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/InitialGameplayLoginOwnerTest.java); [InitialGameplayLoginContextRedisIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextRedisIntegrationTest.java); [CanonicalGameplayLoginAccountClientTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalGameplayLoginAccountClientTest.java); [CanonicalGameplayLoginResultTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/dto/CanonicalGameplayLoginResultTest.java); [GameplayHandshakeFilterTest.java](../../../services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/filter/GameplayHandshakeFilterTest.java); [GameplayRouteReadinessHealthIndicatorTest.java](../../../services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/health/GameplayRouteReadinessHealthIndicatorTest.java); [CanonicalPlayerRouteReadServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalPlayerRouteReadServiceTest.java); [RedisSessionContextServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextServiceTest.java); [SessionContextTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionContextTest.java); [InitialGameplayLoginCoordinationJournalRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/InitialGameplayLoginCoordinationJournalRepositoryIntegrationTest.java); [InMemoryActiveTransportSessionRegistryTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InMemoryActiveTransportSessionRegistryTest.java); [CommunicationRecipientDeliveryServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CommunicationRecipientDeliveryServiceTest.java); [PlayerOutputDeliveryServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/PlayerOutputDeliveryServiceTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Player Experience](./player-experience-commands-and-communication.md) | Gameplay admission and binding remain partial. Exact-head execution scope and fixture results, including the V34.3 fixture pass, are recorded in the [consolidated proof record](#consolidated-exact-head-and-historical-proof). This verifies the tested migration fixture, not namespace-aware atomic takeover: that remains incomplete, as do issuer-index and region reconciliation and retained-binding inventory/conversion. Final immutable image build and authority, trusted bootstrap/execution, and live playable proof remain unproved. Current `/auth/connect-token` validates existing bootstrap and scope, then returns `AUTH_UNAVAILABLE` before cached-success replay, token minting, or replay/session mutation. The canonical Account producer, shared replay fence, dedicated Gateway signing keys, and deployment qualification remain unavailable. Game Session retains complete signed-context, canonical-route/private-handle, and retention sources, but public first-party bare `LOGIN`/`PLAY` deny before legacy Account, Entity, or binding effects; partial selectors never provide fallback. Generic credential LOGIN/PLAY and retained-edge rebind remain separate behavior, and earlier first-party happy-handshake/reconnect proofs are historical. Synthetic actor fallback, descriptor/template resolution, and fork-local identity proof remain gaps under [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) and the [Game Session persisted-actor boundary](../../architecture/microservices/game-session-service/runtime-and-data.md#persisted-actor-admission-boundary). Deployment/mTLS and fresh-image proof for gameplay admission remain incomplete; gameplay completion under #2967/#2898 remains open. Live no-key disposal remains fail-closed pending the protected retained binding-history/restore-continuity producer tracked with `PO-3.4` in [Platform Operations](./platform-operations-and-delivery.md#capability-status). The initial private gameplay LOGIN now has local unregistered composition source; runtime caller registration and authentication, deployed ACL/TLS and signer custody, missing-Account decoy timing parity, and singleton source-fence allocator throughput remain open (see [source-intake status](#initial-private-gameplay-login-issuance-source-intake)). The default-off roster selection source has no player-command caller; `PLAY`/`LOOK` activation and live owner-RPC execution remain unproved, so `AA-2.1` stays partial. | +| `AA-2.1` Gameplay login, character selection, and session binding | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0021](../../architecture/decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md); [JWT and Token Contracts](../../architecture/system-architecture-jwt-and-token-contracts.md#game-session-original-attempt-coordination); [Gateway Architecture](../../architecture/system-architecture-gateway.md#gameplay-websocket-route) | [SessionAuthenticationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionAuthenticationService.java); [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [CanonicalGameplayMigrationDriverMain.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMain.java); [CanonicalGameplayMigrationDriverProtocol.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocol.java); [CanonicalGameplayMigrationDriverLauncher.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverLauncher.java); [game-session-service build](../../../services/game-session-service/build.gradle.kts); [AccountGameplayCanonicalLoginOwner.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayCanonicalLoginOwner.java); [AccountGameplayDelegationIssuanceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuanceRepository.java); [V147__account_gameplay_delegation_issuance.sql](../../../services/account-service/src/main/resources/db/migration/V147__account_gameplay_delegation_issuance.sql); [V157.1__account_gameplay_token_fence_truncate_guard.sql](../../../services/account-service/src/main/resources/db/migration/V157.1__account_gameplay_token_fence_truncate_guard.sql); [CanonicalGameplayRosterSelectionService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionService.java); [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [GatewayFirstPartyConnectContextEnvelope.java](../../../services/common-security/src/main/java/net/firedevops/firemud/common/security/GatewayFirstPartyConnectContextEnvelope.java); [FirstPartyConnectContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContext.java); [FirstPartyConnectContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextService.java); [FirstPartyConnectContextRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextRegistry.java); [FirstPartyConnectContextResolution.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextResolution.java); [RedisFirstPartyConnectContextRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisFirstPartyConnectContextRegistry.java); [GameSessionWebSocketHandshakeInterceptor.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptor.java); [GameSessionWebSocketHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandler.java); [SessionRoutingNormalizationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationService.java); [InitialGameplayLoginOwner.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialGameplayLoginOwner.java); [CanonicalGameplayLoginAccountClient.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalGameplayLoginAccountClient.java); [CanonicalGameplayLoginResult.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalGameplayLoginResult.java); [GameplayHandshakeFilter.java](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/filter/GameplayHandshakeFilter.java); [GameplayRouteReadinessHealthIndicator.java](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/health/GameplayRouteReadinessHealthIndicator.java); [FirstPartyConnectContextConfig.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/FirstPartyConnectContextConfig.java); [FirstPartyConnectContextProperties.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/FirstPartyConnectContextProperties.java); [CanonicalPlayerRouteReadService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalPlayerRouteReadService.java); [SessionContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContext.java); [RedisSessionContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java); [ActiveTransportSessionRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/ActiveTransportSessionRegistry.java); [InMemoryActiveTransportSessionRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/InMemoryActiveTransportSessionRegistry.java); [CommunicationRecipientDeliveryService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CommunicationRecipientDeliveryService.java); [PlayerOutputDeliveryService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/PlayerOutputDeliveryService.java); [CanonicalGameplayIssuerAdmissionControlRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionControlRepository.java); [CanonicalGameplayIssuerAdmissionBarrierRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepository.java); [CanonicalGameplayIssuerBindingLocalAcknowledgementRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalAcknowledgementRepository.java); [V1045__canonical_issuer_binding_local_acknowledgement.sql](../../../services/game-session-service/src/main/resources/db/migration/V1045__canonical_issuer_binding_local_acknowledgement.sql); [V1046__canonical_issuer_live_admission_control.sql](../../../services/game-session-service/src/main/resources/db/migration/V1046__canonical_issuer_live_admission_control.sql) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [CanonicalGameplayMigrationDriverMainTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMainTest.java); [CanonicalGameplayMigrationDriverProtocolTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocolTest.java); [CanonicalGameplayMigrationDriverStdoutTest.java](../../../services/game-session-service/src/test/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverStdoutTest.java); [migration-driver image contract](../../../dev-tools/tests/game-session-migration-driver-image-contract.sh); [V34.3 PostgreSQL fixture](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayInitialAdmissionIntentRequestIdMigrationIntegrationTest.java); [AccountGameplayCanonicalLoginOwnerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayCanonicalLoginOwnerTest.java); [AccountGameplayDelegationIssuancePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuancePersistenceIntegrationTest.java); [CanonicalGameplayRosterSelectionServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionServiceTest.java); [GatewayFirstPartyConnectContextEnvelopeTest.java](../../../services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/GatewayFirstPartyConnectContextEnvelopeTest.java); [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [FirstPartyConnectContextServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextServiceTest.java); [FirstPartyConnectContextResolutionTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextResolutionTest.java); [RedisFirstPartyConnectContextRegistryTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisFirstPartyConnectContextRegistryTest.java); [GameSessionWebSocketHandshakeInterceptorTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptorTest.java); [GameSessionWebSocketHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerTest.java); [InitialGameplayLoginOwnerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/InitialGameplayLoginOwnerTest.java); [InitialGameplayLoginContextRedisIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextRedisIntegrationTest.java); [CanonicalGameplayLoginAccountClientTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalGameplayLoginAccountClientTest.java); [CanonicalGameplayLoginResultTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/dto/CanonicalGameplayLoginResultTest.java); [GameplayHandshakeFilterTest.java](../../../services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/filter/GameplayHandshakeFilterTest.java); [GameplayRouteReadinessHealthIndicatorTest.java](../../../services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/health/GameplayRouteReadinessHealthIndicatorTest.java); [CanonicalPlayerRouteReadServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalPlayerRouteReadServiceTest.java); [RedisSessionContextServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextServiceTest.java); [SessionContextTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionContextTest.java); [InitialGameplayLoginCoordinationJournalRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/InitialGameplayLoginCoordinationJournalRepositoryIntegrationTest.java); [InMemoryActiveTransportSessionRegistryTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InMemoryActiveTransportSessionRegistryTest.java); [CommunicationRecipientDeliveryServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CommunicationRecipientDeliveryServiceTest.java); [PlayerOutputDeliveryServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/PlayerOutputDeliveryServiceTest.java); [CanonicalGameplayIssuerAdmissionBarrierRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepositoryIntegrationTest.java); [CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java); [readiness receiving proof](#canonical-new-admission-components) records R849 partial execution, R855/R856 recovery, R867 and current R902 focused results with their separate limits | [Realm Routing](./realm-routing-and-playable-state.md); [Player Experience](./player-experience-commands-and-communication.md) | Gameplay admission and binding remain partial. Exact-head execution scope and fixture results, including the V34.3 fixture pass, are recorded in the [consolidated proof record](#consolidated-exact-head-and-historical-proof). This verifies the tested migration fixture, not namespace-aware atomic takeover: that remains incomplete, as do issuer-index and region reconciliation and retained-binding inventory/conversion. Final immutable image build and authority, trusted bootstrap/execution, and live playable proof remain unproved. Current `/auth/connect-token` validates existing bootstrap and scope, then returns `AUTH_UNAVAILABLE` before cached-success replay, token minting, or replay/session mutation. The canonical Account producer, shared replay fence, dedicated Gateway signing keys, and deployment qualification remain unavailable. Game Session retains complete signed-context, canonical-route/private-handle, and retention sources, but public first-party bare `LOGIN`/`PLAY` deny before legacy Account, Entity, or binding effects; partial selectors never provide fallback. Generic credential LOGIN/PLAY and retained-edge rebind remain separate behavior, and earlier first-party happy-handshake/reconnect proofs are historical. Synthetic actor fallback, descriptor/template resolution, and fork-local identity proof remain gaps under [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) and the [Game Session persisted-actor boundary](../../architecture/microservices/game-session-service/runtime-and-data.md#persisted-actor-admission-boundary). Deployment/mTLS and fresh-image proof for gameplay admission remain incomplete; gameplay completion under #2967/#2898 remains open. Live no-key disposal remains fail-closed pending the protected retained binding-history/restore-continuity producer tracked with `PO-3.4` in [Platform Operations](./platform-operations-and-delivery.md#capability-status). The initial private gameplay LOGIN now has local unregistered composition source; runtime caller registration and authentication, deployed ACL/TLS and signer custody, missing-Account decoy timing parity, and singleton source-fence allocator throughput remain open (see [source-intake status](#initial-private-gameplay-login-issuance-source-intake)). The default-off roster selection source has no player-command caller; `PLAY`/`LOOK` activation and live owner-RPC execution remain unproved, so `AA-2.1` stays partial. Issuer LIVE/OPEN/cutoff and INITIAL Account components are manually composed prerequisites, not complete original NEW or playable admission; custody, default registration, final admission and activation remain unqualified as recorded in the [readiness scope and proof](#canonical-new-admission-components). | | `AA-2.2` Reconnect, resume eligibility, and cross-device continuity | `partial` | `drift-found` | [Reconnection](../../architecture/system-architecture-reconnection.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [Redis architecture](../../architecture/system-architecture-redis.md); [ADR 0019](../../architecture/decisions/adr-0019-separate-active-session-resume-and-transcript-lifetimes.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md); [ADR 0133](../../architecture/decisions/adr-0133-fresh-edge-reconnect-without-client-input-replay.md); [ADR 0134](../../architecture/decisions/adr-0134-bounded-durable-semantic-reconnect-context.md) | [SessionAuthenticationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionAuthenticationService.java); [RedisSessionContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java); [DurableScreenBufferService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DurableScreenBufferService.java); [GameplayWebSocketBridgeHandler.java](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketBridgeHandler.java); [FirstPartyConnectContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextService.java); [EffectiveReconnectionSettingsResolver.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/EffectiveReconnectionSettingsResolver.java) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [LookWebSocketCrossServiceTest.java](../../../services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/LookWebSocketCrossServiceTest.java); [GameSessionWebSocketHandlerIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java); [Telnet cross-service test](../../../services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/TelnetGatewayGameSessionAccountCrossServiceIntegrationTest.java) | [Player Experience](./player-experience-commands-and-communication.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md); [Platform Operations](./platform-operations-and-delivery.md) | Generic resume, bounded semantic context, and edge rebind exist, but the effective disconnected-resume window is resolved without `PLAY` enforcement; namespace-aware binding/transfer, complete authenticated real-service replacement, lifecycle/presence/stalled-input outcomes, first-party post-logout replay suppression, and proof of fresh-edge `LOOK`/prompt behavior are not complete or proved. The earlier first-party post-logout replay defect is historical: current first-party `LOGIN` and `PLAY` deny before legacy effects while the genuine context consumers remain unavailable. Successful post-logout replay suppression and a complete playable flow remain unproved. Fresh edge reconnect must not replay client input/bytes/frames and must end with fresh `LOOK` plus exactly one reconnect prompt when both effective reconnect-prompt settings are enabled, or zero reconnect prompts when either is disabled. Full token refresh, membership-version and membership-authority-generation persistence, revocation, and non-edge restart continuity remain. See AA-2.1 for the finite namespace controller-index migration-driver prefix, its implementation and proof anchors, and the unproved physical PostgreSQL/Redis, final-image, and trusted-bootstrap/execution gates. | | `AA-2.3` Takeover, logout, idle expiry, and revocation | `partial` | `drift-found` | [Session behavior](../../architecture/system-architecture-session-behavior.md); [Reconnection](../../architecture/system-architecture-reconnection.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md) | [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [LogoutCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandler.java); [RedisSessionContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java); [TelnetServerHandler.java](../../../services/tcp-proxy-service/src/main/java/net/firedevops/firemud/tcpproxy/telnet/TelnetServerHandler.java); [application.yml](../../../services/game-session-service/src/main/resources/application.yml) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [LogoutCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandlerTest.java); [LookWebSocketCrossServiceTest.java](../../../services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/LookWebSocketCrossServiceTest.java) | [Player Experience](./player-experience-commands-and-communication.md); [World Runtime](./world-runtime-and-movement.md); [Gameplay Rules](./gameplay-rules-entities-and-effects.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Gameplay takeover/LOGOUT and transport idle-close handling exist; target takeover requires namespace-scoped atomic monotonic `bindingGeneration`, old-input fencing, and preservation of already-admitted work as defined by [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md), while Account control-plane logout/authority-generation workflows, full idle/session expiry convergence, and first-party post-logout replay cleanup are absent. | diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierRedisOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierRedisOwner.java index 91d57d5521..ddcc448e3b 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierRedisOwner.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierRedisOwner.java @@ -63,10 +63,6 @@ final class CanonicalGameplayAccountInitialBarrierRedisOwner { "TARGET_ALREADY_PRESENT", RedisScriptDescriptor.OutcomeCategory.STALE, RedisScriptDescriptor.MutationEffect.NON_MUTATING), - outcome( - "TYPE_TTL_OR_FIELDS_REFUSED", - RedisScriptDescriptor.OutcomeCategory.VALIDATION_FAILURE, - RedisScriptDescriptor.MutationEffect.NON_MUTATING), outcome( "INVALID_ARGUMENTS", RedisScriptDescriptor.OutcomeCategory.VALIDATION_FAILURE, @@ -122,9 +118,10 @@ CanonicalGameplayAccountInitialOpenProof initializeOnce( CanonicalGameplayProtectedIncarnationReceiver.VerifiedIncarnation before = incarnationReceiver.observeForInitialAccountBarrier(snapshot.originalRequestId()); requireObservation(snapshot, before); + PreparedWrite prepared = prepareWrite(snapshot, assignment, before); repository.recordDispatchPossible(snapshot.originalRequestId(), before); // The state transition above is durable before this one and only possible remote attempt. - tryCreateOnce(snapshot, assignment, before); + tryCreateOnce(prepared); } catch (RuntimeException possibleDispatchOrSourceFailure) { // Never create a replacement initializer or repeat a possibly dispatched write. A positive // exact readback can still finish the original receipt; absence remains explicit uncertainty. @@ -252,40 +249,45 @@ CanonicalGameplayAccountInitialOpenProof verifyCurrentOpenForTarget( return verifyCurrentOpen(snapshot.originalRequestId()); } - private void tryCreateOnce( + private PreparedWrite prepareWrite( CanonicalGameplayAccountInitialBarrierInitializerRepository.InitializerSnapshot snapshot, CanonicalGameplayTenantGameplayTagRepository.Assignment assignment, CanonicalGameplayProtectedIncarnationReceiver.VerifiedIncarnation before) { - requireNoAmbientTransaction(); RedisScriptDescriptor descriptor = requireDescriptor(); byte[] script = scriptSource(descriptor); - CanonicalGameplayAccountInitialBarrierValue.open( - snapshot.accountId(), - snapshot.tenantId(), - snapshot.playableStateNamespaceId(), - assignment.tenantGameplayTag(), - snapshot.initializerId(), - snapshot.sourceControlEpoch(), - before.incarnationDigest()); + CanonicalGameplayAccountInitialBarrierValue value = + CanonicalGameplayAccountInitialBarrierValue.open( + snapshot.accountId(), + snapshot.tenantId(), + snapshot.playableStateNamespaceId(), + assignment.tenantGameplayTag(), + snapshot.initializerId(), + snapshot.sourceControlEpoch(), + before.incarnationDigest()); String key = CanonicalGameplayAccountInitialBarrierKey.forTarget( assignment, snapshot.initializerId(), snapshot.originalRequestId()); + List arguments = FIELDS.stream().map(value.fields()::get).toList(); + // Validate every local byte conversion before the durable possible-dispatch claim. + ascii(key); + arguments.forEach(CanonicalGameplayAccountInitialBarrierRedisOwner::ascii); + return new PreparedWrite(asciiString(script), key, arguments); + } + + private void tryCreateOnce(PreparedWrite prepared) { + requireNoAmbientTransaction(); long outcome = writeOneKey( - script, - key, - ascii(CanonicalGameplayAccountInitialBarrierValue.SCHEMA), - ascii(snapshot.accountId().toString()), - ascii(snapshot.tenantId().toString()), - ascii(snapshot.playableStateNamespaceId().toString()), - ascii(assignment.tenantGameplayTag()), - ascii(snapshot.initializerId().toString()), - ascii(snapshot.sourceControlEpoch().toString()), - ascii(before.incarnationDigest()), - ascii(CanonicalGameplayAccountInitialBarrierValue.OPEN)); + ascii(prepared.script()), + prepared.key(), + prepared.arguments().stream() + .map(CanonicalGameplayAccountInitialBarrierRedisOwner::ascii) + .toArray(byte[][]::new)); if (outcome < 0 || outcome > 1) throw unavailable(); } + private record PreparedWrite(String script, String key, List arguments) {} + private CanonicalGameplayTenantGameplayTagRepository.Assignment requireInitialAssignment( UUID originalRequestId, CanonicalGameplayAccountInitialBarrierInitializerRepository.InitializerSnapshot snapshot) { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRedisOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRedisOwner.java index 6efd37cd84..4ba9708a74 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRedisOwner.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRedisOwner.java @@ -74,7 +74,6 @@ Readback initializeAndRead(UUID operationId) { PreparedInitializer prepared = repository.readPreparedInitializer(operationId); requireCurrentState(prepared.value().initializer()); repository.requireStillCurrent(prepared); - String createMode = prepared.consumeCreatePermit() ? "CREATE_ONCE" : "REPLAY_ONLY"; RedisScriptDescriptor descriptor = requireDescriptor( CanonicalGameplayIssuerAdmissionBarrierRedisScriptContribution.OPEN_SCRIPT_ID, @@ -84,21 +83,23 @@ Readback initializeAndRead(UUID operationId) { byte[] script = scriptSource(descriptor); CanonicalGameplayIssuerAdmissionBarrierValue value = prepared.value(); byte[] payload = value.exactBytes(); - long result = - writeOneKey( - script, - prepared.key(), - ascii(value.issuerId()), - ascii(value.tenantId().toString()), - ascii(value.playableStateNamespaceId().toString()), - ascii(value.tenantGameplayTag()), - ascii(value.ownerOperationId().toString()), - ascii(value.admissionEpoch().toString()), - ascii(value.initializer().exactDigest()), - ascii(value.exactDigest()), - payload, - ascii(value.state().name()), - ascii(createMode)); + byte[] key = ascii(prepared.key()); + byte[][] arguments = { + ascii(value.issuerId()), + ascii(value.tenantId().toString()), + ascii(value.playableStateNamespaceId().toString()), + ascii(value.tenantGameplayTag()), + ascii(value.ownerOperationId().toString()), + ascii(value.admissionEpoch().toString()), + ascii(value.initializer().exactDigest()), + ascii(value.exactDigest()), + payload, + ascii(value.state().name()), + ascii("REPLAY_ONLY") + }; + byte[] createOnce = ascii("CREATE_ONCE"); + if (repository.claimFirstCreatePermit(prepared)) arguments[10] = createOnce; + long result = writeOneKey(script, key, arguments); if (result < 1 || result > 2) throw unavailable(); byte[] observed = readExactPhysicalState(prepared.key(), value); requireCurrentState(value.initializer()); @@ -215,6 +216,10 @@ private byte[] readExactPhysicalState( } private long writeOneKey(byte[] script, String key, byte[]... arguments) { + return writeOneKey(script, ascii(key), arguments); + } + + private long writeOneKey(byte[] script, byte[] key, byte[]... arguments) { requireNoAmbientTransaction(); try (StatefulRedisConnection connection = redisClient.connect(ByteArrayCodec.INSTANCE)) { @@ -223,9 +228,7 @@ private long writeOneKey(byte[] script, String key, byte[]... arguments) { String sha = await(commands.scriptLoad(script)); if (!digest("SHA-1", script).equals(sha)) throw unavailable(); Long reply = - await( - commands.evalsha( - sha, ScriptOutputType.INTEGER, new byte[][] {ascii(key)}, arguments)); + await(commands.evalsha(sha, ScriptOutputType.INTEGER, new byte[][] {key}, arguments)); if (reply == null) throw unavailable(); return reply; } catch (RuntimeException failure) { @@ -462,6 +465,9 @@ private static RedisScriptDescriptor.OutcomeSpec outcome( interface ProjectionRepository { PreparedInitializer readPreparedInitializer(UUID operationId); + /** Commits the sole first-create claim; false permits only replay of an existing OPEN. */ + boolean claimFirstCreatePermit(PreparedInitializer prepared); + PreparedCutoffTarget readPreparedCutoffTarget( UUID cutoffOperationId, UUID tenantId, UUID namespaceId); @@ -479,19 +485,16 @@ static final class PreparedInitializer { private final CanonicalGameplayTenantGameplayTagRepository.Assignment assignment; private final UUID requestOperationId; private final String key; - private final java.util.concurrent.atomic.AtomicBoolean createPermit; PreparedInitializer( CanonicalGameplayIssuerAdmissionBarrierValue value, CanonicalGameplayTenantGameplayTagRepository.Assignment assignment, UUID requestOperationId, - String key, - boolean createPermit) { + String key) { this.value = Objects.requireNonNull(value, "value"); this.assignment = assignment; this.requestOperationId = Objects.requireNonNull(requestOperationId, "requestOperationId"); this.key = Objects.requireNonNull(key, "key"); - this.createPermit = new java.util.concurrent.atomic.AtomicBoolean(createPermit); if (value.state() != CanonicalGameplayIssuerAdmissionBarrierValue.State.OPEN || !CanonicalGameplayIssuerAdmissionBarrierKey.forTarget( value.issuerId(), @@ -524,11 +527,6 @@ UUID requestOperationId() { String key() { return key; } - - /** Consumes the SQL owner's first-attempt authority before any Redis command is attempted. */ - boolean consumeCreatePermit() { - return createPermit.getAndSet(false); - } } record PreparedCutoffTarget( diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepository.java index ed91c70ae9..9d83b6dca5 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepository.java @@ -135,10 +135,8 @@ final class CanonicalGameplayIssuerAdmissionBarrierRepository if (!value.initializer().matchesCurrentIssuerState(current)) { throw conflict("Original OPEN initializer no longer matches current Account issuer source"); } - boolean createPermit = - claimFirstCreatePermit(value.initializer().operationId(), value, current); CanonicalGameplayIssuerAdmissionBarrierRedisOwner.PreparedInitializer prepared = - prepared(value, source.requestAssignment(), operationId, createPermit); + prepared(value, source.requestAssignment(), operationId); requireStillCurrent(prepared); return prepared; } @@ -760,25 +758,36 @@ private static void requirePersistedInitializer( private CanonicalGameplayIssuerAdmissionBarrierRedisOwner.PreparedInitializer prepared( CanonicalGameplayIssuerAdmissionBarrierValue value, CanonicalGameplayTenantGameplayTagRepository.Assignment assignment, - UUID requestOperationId, - boolean createPermit) { + UUID requestOperationId) { return new CanonicalGameplayIssuerAdmissionBarrierRedisOwner.PreparedInitializer( value, assignment, requestOperationId, CanonicalGameplayIssuerAdmissionBarrierKey.forTarget( - ISSUER, value.tenantId(), value.playableStateNamespaceId(), value.tenantGameplayTag()), - createPermit); + ISSUER, value.tenantId(), value.playableStateNamespaceId(), value.tenantGameplayTag())); } /** * Consumes the sole durable authority to create the first Redis OPEN. The state transition is * committed before the Redis owner can attempt its command; every later call is replay-only. */ - private boolean claimFirstCreatePermit( - UUID operationId, - CanonicalGameplayIssuerAdmissionBarrierValue value, - CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState current) { + @Override + public boolean claimFirstCreatePermit( + CanonicalGameplayIssuerAdmissionBarrierRedisOwner.PreparedInitializer prepared) { + Objects.requireNonNull(prepared, "prepared"); + requireNoAmbientTransaction(); + CanonicalGameplayIssuerAdmissionBarrierValue value = prepared.value(); + UUID operationId = value.initializer().operationId(); + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState current = + readCurrentState(); + if (!value.initializer().matchesCurrentIssuerState(current)) { + throw conflict("Original OPEN initializer no longer matches current Account issuer source"); + } + CanonicalGameplayTenantGameplayTagRepository.Assignment assignment = + prepared.assignment() == null + ? null + : tenantTags.assignmentForTransition(prepared.assignment().transitionId()); + if (assignment != null) requireSameAssignment(prepared.assignment(), assignment); return dsl.transactionResult( configuration -> { DSLContext transaction = DSL.using(configuration); @@ -794,6 +803,12 @@ private boolean claimFirstCreatePermit( throw conflict( "Original initializer no longer belongs to the current OPEN live control"); } + if (assignment != null) { + requireCurrentTagMapping( + transaction, assignment.tenantId(), assignment.tenantGameplayTag()); + requireCurrentRequestTarget( + transaction, prepared.requestOperationId(), assignment, current); + } Record saved = transaction.fetchSingle( "SELECT * FROM " @@ -801,6 +816,8 @@ private boolean claimFirstCreatePermit( + " WHERE operation_id = ? AND issuer_id = ? FOR UPDATE", operationId, ISSUER); + readFrozenInitializer( + transaction, saved, prepared.assignment(), anchor, control, current); requirePersistedInitializer(saved, value); String state = saved.get("initialization_state", String.class); if ("PREPARED".equals(state)) { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayTenantGameplayTagRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayTenantGameplayTagRepository.java index 3fa08c3fc9..ee3723df96 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayTenantGameplayTagRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayTenantGameplayTagRepository.java @@ -134,6 +134,26 @@ Assignment assignmentForInitialBarrierTarget(UUID originalRequestId) { return dsl.transactionResult( configuration -> { DSLContext transaction = DSL.using(configuration); + // Match the initializer owner: inventory clock, account control, initializer/target. + Record inventoryClock = + transaction.fetchOne( + "SELECT inventory_revision FROM game_session_canonical_binding_inventory_clock" + + " WHERE singleton_id = 1 FOR UPDATE"); + if (inventoryClock == null) + throw conflict("Canonical binding inventory clock is missing"); + Record locator = + transaction.fetchOne( + "SELECT account_id FROM game_session_canonical_initial_account_barrier_initializer" + + " WHERE original_request_id = ?", + originalRequestId); + if (locator == null) throw conflict("Exact original INITIAL account target is missing"); + UUID locatedAccountId = requiredUuid(locator, "account_id"); + Record control = + transaction.fetchOne( + "SELECT account_id FROM game_session_canonical_account_coverage_control" + + " WHERE account_id = ? FOR UPDATE", + locatedAccountId); + if (control == null) throw conflict("Account coverage control row is missing"); Record row = transaction.fetchOne( "SELECT i.initializer_id, i.account_id, i.source_control_epoch," diff --git a/services/game-session-service/src/main/resources/redis/scripts/game-session-account-admission-barrier-initial-open.json b/services/game-session-service/src/main/resources/redis/scripts/game-session-account-admission-barrier-initial-open.json index 7f68d252f8..0241ec76de 100644 --- a/services/game-session-service/src/main/resources/redis/scripts/game-session-account-admission-barrier-initial-open.json +++ b/services/game-session-service/src/main/resources/redis/scripts/game-session-account-admission-barrier-initial-open.json @@ -27,7 +27,6 @@ "outcomes": [ {"code": "OPEN_CREATED", "category": "SUCCESS", "effect": "MUTATING"}, {"code": "TARGET_ALREADY_PRESENT", "category": "STALE", "effect": "NON_MUTATING"}, - {"code": "TYPE_TTL_OR_FIELDS_REFUSED", "category": "VALIDATION_FAILURE", "effect": "NON_MUTATING"}, {"code": "INVALID_ARGUMENTS", "category": "VALIDATION_FAILURE", "effect": "NON_MUTATING"} ], "resetSensitivity": "CLUSTER", diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionAbortCompositionFixture.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionAbortCompositionFixture.java index 41e807dce1..dcef312071 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionAbortCompositionFixture.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionAbortCompositionFixture.java @@ -676,15 +676,17 @@ public CanonicalGameplayIssuerBindingLocalReleaseOperation completeIssuerRelease var completed = new CanonicalGameplayIssuerBindingLocalReleaseOperationRepository(dsl, issuerSource) .completeWithReadback(operation, readback); - var historicalAcknowledgement = - new CanonicalGameplayIssuerBindingLocalAcknowledgementRepository(dsl, issuerSource) - .readHistorical(localOperation.operationId()); - if (issuerAcknowledgementBytes == null - || historicalAcknowledgement == null - || !java.util.Arrays.equals( - issuerAcknowledgementBytes, historicalAcknowledgement.exactBytes())) { - throw new IllegalStateException( - "Issuer release did not retain the exact original binding-local acknowledgement"); + if (operation.originalOperation().operationId().equals(localOperation.operationId())) { + var historicalAcknowledgement = + new CanonicalGameplayIssuerBindingLocalAcknowledgementRepository(dsl, issuerSource) + .readHistorical(localOperation.operationId()); + if (issuerAcknowledgementBytes == null + || historicalAcknowledgement == null + || !java.util.Arrays.equals( + issuerAcknowledgementBytes, historicalAcknowledgement.exactBytes())) { + throw new IllegalStateException( + "Issuer release did not retain the exact original binding-local acknowledgement"); + } } return completed; } diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepositoryIntegrationTest.java index 25920a0a9f..d115c97024 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepositoryIntegrationTest.java @@ -106,6 +106,134 @@ void tearDown() { if (administrator != null) administrator.shutdown(Duration.ZERO, Duration.ofSeconds(2)); } + @Test + void preparedReadsRetainTheSoleCreatePermitUntilTheRemoteBoundary() { + FixtureState state = fixtureState(); + UUID operationId = state.fixture().originalOperationId(); + var first = state.repository().readPreparedInitializer(operationId); + var second = state.repository().readPreparedInitializer(operationId); + assertThat(second.value().exactBytes()).containsExactly(first.value().exactBytes()); + assertThat(initializationState(state, operationId)).isEqualTo("PREPARED"); + assertThat(countReceipt(state, operationId)).isZero(); + assertThat(administratorCommands.exists(bytes(first.key()))).isZero(); + + assertThat(state.owner().initializeAndRead(operationId).scriptOutcome()).isEqualTo(1L); + assertThat(state.repository().claimFirstCreatePermit(first)).isFalse(); + assertThat(state.repository().claimFirstCreatePermit(second)).isFalse(); + assertThat(state.owner().initializeAndRead(operationId).scriptOutcome()).isEqualTo(2L); + assertThat(countReceipt(state, operationId)).isEqualTo(1L); + } + + @ParameterizedTest + @ValueSource(strings = {"DESCRIPTOR", "SOURCE", "CURRENTNESS"}) + void localPreflightFailureRetainsPreparedInitializerAndAllowsOneValidCreate(String failure) { + FixtureState state = fixtureState(); + UUID operationId = state.fixture().originalOperationId(); + var prepared = state.repository().readPreparedInitializer(operationId); + var repository = + new ForwardingProjectionRepository(state.repository()) { + @Override + public void requireStillCurrent( + CanonicalGameplayIssuerAdmissionBarrierRedisOwner.PreparedInitializer initializer) { + if ("CURRENTNESS".equals(failure)) { + throw new IllegalStateException("Controlled preclaim SQL currentness failure"); + } + super.requireStillCurrent(initializer); + } + }; + RedisScriptCatalog catalog = + RedisScriptCatalog.fromContributions( + "DESCRIPTOR".equals(failure) + ? List.of() + : List.of(new CanonicalGameplayIssuerAdmissionBarrierRedisScriptContribution())); + var failingOwner = + new CanonicalGameplayIssuerAdmissionBarrierRedisOwner( + ownerClient, + catalog, + repository, + () -> { + if ("SOURCE".equals(failure)) { + throw new IllegalStateException("Controlled preclaim current source failure"); + } + return state.sourceReader().readFreshCurrentState(); + }); + + assertThatThrownBy(() -> failingOwner.initializeAndRead(operationId)) + .isInstanceOf(IllegalStateException.class); + assertThat(initializationState(state, operationId)).isEqualTo("PREPARED"); + assertThat(countReceipt(state, operationId)).isZero(); + assertThat(administratorCommands.exists(bytes(prepared.key()))).isZero(); + assertThat(state.owner().initializeAndRead(operationId).scriptOutcome()).isEqualTo(1L); + assertThat(state.owner().initializeAndRead(operationId).scriptOutcome()).isEqualTo(2L); + assertThat(countReceipt(state, operationId)).isEqualTo(1L); + } + + @Test + void concurrentClaimsOfRetainedPreparedReadsHaveOnlyOneFirstCreateWinner() throws Exception { + FixtureState state = fixtureState(); + UUID operationId = state.fixture().originalOperationId(); + var first = state.repository().readPreparedInitializer(operationId); + var second = state.repository().readPreparedInitializer(operationId); + CountDownLatch start = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + var firstClaim = + executor.submit( + () -> { + if (!start.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("Controlled claim start timed out"); + } + return state.repository().claimFirstCreatePermit(first); + }); + var secondClaim = + executor.submit( + () -> { + if (!start.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("Controlled claim start timed out"); + } + return state.repository().claimFirstCreatePermit(second); + }); + start.countDown(); + assertThat( + List.of(firstClaim.get(10, TimeUnit.SECONDS), secondClaim.get(10, TimeUnit.SECONDS))) + .containsExactlyInAnyOrder(true, false); + assertThat(initializationState(state, operationId)).isEqualTo("INITIALIZING"); + assertThatThrownBy(() -> state.owner().initializeAndRead(operationId)) + .isInstanceOf(IllegalStateException.class); + assertThat(countReceipt(state, operationId)).isZero(); + assertThat(administratorCommands.exists(bytes(first.key()))).isZero(); + } finally { + start.countDown(); + executor.shutdownNow(); + } + } + + @Test + void lostClaimReplyLeavesMissingOpenReplayOnlyWithoutRearmingThePermit() { + FixtureState state = fixtureState(); + UUID operationId = state.fixture().originalOperationId(); + var prepared = state.repository().readPreparedInitializer(operationId); + var lostClaimReply = + new ForwardingProjectionRepository(state.repository()) { + @Override + public boolean claimFirstCreatePermit( + CanonicalGameplayIssuerAdmissionBarrierRedisOwner.PreparedInitializer initializer) { + assertThat(super.claimFirstCreatePermit(initializer)).isTrue(); + throw new IllegalStateException("Controlled loss after first-create claim committed"); + } + }; + assertThatThrownBy(() -> state.owner(lostClaimReply).initializeAndRead(operationId)) + .isInstanceOf(IllegalStateException.class); + assertThat(initializationState(state, operationId)).isEqualTo("INITIALIZING"); + assertThat(administratorCommands.exists(bytes(prepared.key()))).isZero(); + assertThat(state.repository().claimFirstCreatePermit(prepared)).isFalse(); + assertThatThrownBy(() -> state.owner().initializeAndRead(operationId)) + .isInstanceOf(IllegalStateException.class); + assertThat(initializationState(state, operationId)).isEqualTo("INITIALIZING"); + assertThat(countReceipt(state, operationId)).isZero(); + assertThat(administratorCommands.exists(bytes(prepared.key()))).isZero(); + } + @Test void firstOpenIsPersistedExactRetryIsReplayOnlyAndCutoffPreservesNewerClosedState() { FixtureState state = fixtureState(); @@ -175,6 +303,12 @@ void lostReceiptReplaysTheExistingOpenWithoutMintingAnotherCreatePermit() { return delegate.readPreparedInitializer(id); } + @Override + public boolean claimFirstCreatePermit( + CanonicalGameplayIssuerAdmissionBarrierRedisOwner.PreparedInitializer prepared) { + return delegate.claimFirstCreatePermit(prepared); + } + @Override public CanonicalGameplayIssuerAdmissionBarrierRedisOwner.PreparedCutoffTarget readPreparedCutoffTarget(UUID id, UUID tenantId, UUID namespaceId) { @@ -237,6 +371,12 @@ void missingOpenAfterUncertainFirstAttemptIsNeverRecreated() { return delegate.readPreparedInitializer(id); } + @Override + public boolean claimFirstCreatePermit( + CanonicalGameplayIssuerAdmissionBarrierRedisOwner.PreparedInitializer prepared) { + return delegate.claimFirstCreatePermit(prepared); + } + @Override public CanonicalGameplayIssuerAdmissionBarrierRedisOwner.PreparedCutoffTarget readPreparedCutoffTarget(UUID id, UUID tenantId, UUID namespaceId) { @@ -285,7 +425,7 @@ public void recordClosedReadback( } @Test - void cutoffCapturesAnInitializerWhoseCreatePermitWasClaimedButNotYetAttempted() throws Exception { + void cutoffCapturesAnInitializerPreparedBeforeItsCreatePermitIsClaimed() throws Exception { FixtureState state = fixtureState(); UUID operationId = state.fixture().originalOperationId(); UUID cutoffOperationId = UUID.randomUUID(); @@ -314,6 +454,12 @@ void cutoffCapturesAnInitializerWhoseCreatePermitWasClaimedButNotYetAttempted() return prepared; } + @Override + public boolean claimFirstCreatePermit( + CanonicalGameplayIssuerAdmissionBarrierRedisOwner.PreparedInitializer prepared) { + return delegate.claimFirstCreatePermit(prepared); + } + @Override public CanonicalGameplayIssuerAdmissionBarrierRedisOwner.PreparedCutoffTarget readPreparedCutoffTarget(UUID id, UUID tenantId, UUID namespaceId) { @@ -351,7 +497,7 @@ public void recordClosedReadback( var initializerAttempt = executor.submit(() -> state.owner(gatedRepository).initializeAndRead(operationId)); assertThat(preparedForRedis.await(10, TimeUnit.SECONDS)).isTrue(); - assertThat(initializationState(state, operationId)).isEqualTo("INITIALIZING"); + assertThat(initializationState(state, operationId)).isEqualTo("PREPARED"); state.repository().beginCutoff(cutoffOperationId, UUID.randomUUID()); allowRedisOwnerToContinue.countDown(); @@ -377,6 +523,80 @@ public void recordClosedReadback( } } + @Test + void cutoffInstalledAfterCreateClaimCannotBeOverwrittenByTheDelayedOpen() throws Exception { + FixtureState state = fixtureState(); + UUID operationId = state.fixture().originalOperationId(); + UUID cutoffOperationId = UUID.randomUUID(); + CountDownLatch claimCommitted = new CountDownLatch(1); + CountDownLatch allowRedisOwnerToContinue = new CountDownLatch(1); + AtomicReference + observedInitializer = new AtomicReference<>(); + var gatedRepository = + new ForwardingProjectionRepository(state.repository()) { + @Override + public boolean claimFirstCreatePermit( + CanonicalGameplayIssuerAdmissionBarrierRedisOwner.PreparedInitializer prepared) { + boolean claimed = super.claimFirstCreatePermit(prepared); + assertThat(claimed).isTrue(); + observedInitializer.set(prepared); + claimCommitted.countDown(); + try { + if (!allowRedisOwnerToContinue.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("Controlled postclaim gate timed out"); + } + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException( + "Controlled postclaim gate was interrupted", interrupted); + } + return claimed; + } + }; + ExecutorService executor = Executors.newSingleThreadExecutor(); + try { + var initializerAttempt = + executor.submit(() -> state.owner(gatedRepository).initializeAndRead(operationId)); + assertThat(claimCommitted.await(10, TimeUnit.SECONDS)).isTrue(); + assertThat(initializationState(state, operationId)).isEqualTo("INITIALIZING"); + var prepared = observedInitializer.get(); + assertThat(administratorCommands.exists(bytes(prepared.key()))).isZero(); + + var pending = state.repository().beginCutoff(cutoffOperationId, UUID.randomUUID()); + var targets = state.repository().readPreparedCutoffTargets(cutoffOperationId); + assertThat(targets).hasSize(1); + var target = targets.getFirst(); + assertThat(target.expectedOpenValue().exactBytes()) + .containsExactly(prepared.value().exactBytes()); + assertThat(target.closedValue().initializer().exactBytes()) + .containsExactly(prepared.value().initializer().exactBytes()); + var closed = + state + .owner() + .closeAndRead( + cutoffOperationId, + target.closedValue().tenantId(), + target.closedValue().playableStateNamespaceId()); + assertThat(closed.scriptOutcome()).isEqualTo(1L); + + allowRedisOwnerToContinue.countDown(); + assertThatThrownBy(() -> initializerAttempt.get(10, TimeUnit.SECONDS)) + .isInstanceOf(ExecutionException.class) + .hasCauseInstanceOf(IllegalStateException.class); + assertThat(administratorCommands.hget(bytes(prepared.key()), bytes("payload"))) + .containsExactly(closed.exactPhysicalPayload()); + assertThat(initializationState(state, operationId)).isEqualTo("INITIALIZING"); + assertThat(countReceipt(state, operationId)).isZero(); + var installed = state.repository().completeCutoff(cutoffOperationId); + assertThat(installed.state()) + .isEqualTo(CanonicalGameplayIssuerAdmissionControlValue.State.INSTALLED); + assertThat(installed.cohortDigest()).isEqualTo(pending.cohortDigest()); + } finally { + allowRedisOwnerToContinue.countDown(); + executor.shutdownNow(); + } + } + @Test void cutoffClosesAnAbortedOriginTargetAndRetainsItsFrozenInitializer() { FixtureState state = fixtureState(); @@ -1002,6 +1222,60 @@ private static byte[] bytes(String value) { return value.getBytes(StandardCharsets.US_ASCII); } + private static class ForwardingProjectionRepository + implements CanonicalGameplayIssuerAdmissionBarrierRedisOwner.ProjectionRepository { + private final CanonicalGameplayIssuerAdmissionBarrierRedisOwner.ProjectionRepository delegate; + + ForwardingProjectionRepository( + CanonicalGameplayIssuerAdmissionBarrierRedisOwner.ProjectionRepository delegate) { + this.delegate = delegate; + } + + @Override + public CanonicalGameplayIssuerAdmissionBarrierRedisOwner.PreparedInitializer + readPreparedInitializer(UUID operationId) { + return delegate.readPreparedInitializer(operationId); + } + + @Override + public boolean claimFirstCreatePermit( + CanonicalGameplayIssuerAdmissionBarrierRedisOwner.PreparedInitializer prepared) { + return delegate.claimFirstCreatePermit(prepared); + } + + @Override + public CanonicalGameplayIssuerAdmissionBarrierRedisOwner.PreparedCutoffTarget + readPreparedCutoffTarget(UUID operationId, UUID tenantId, UUID namespaceId) { + return delegate.readPreparedCutoffTarget(operationId, tenantId, namespaceId); + } + + @Override + public void requireStillCurrent( + CanonicalGameplayIssuerAdmissionBarrierRedisOwner.PreparedInitializer prepared) { + delegate.requireStillCurrent(prepared); + } + + @Override + public void requireStillCurrent( + CanonicalGameplayIssuerAdmissionBarrierRedisOwner.PreparedCutoffTarget prepared) { + delegate.requireStillCurrent(prepared); + } + + @Override + public void recordOpenReadback( + CanonicalGameplayIssuerAdmissionBarrierRedisOwner.PreparedInitializer prepared, + CanonicalGameplayIssuerAdmissionBarrierRedisOwner.Readback readback) { + delegate.recordOpenReadback(prepared, readback); + } + + @Override + public void recordClosedReadback( + CanonicalGameplayIssuerAdmissionBarrierRedisOwner.PreparedCutoffTarget prepared, + CanonicalGameplayIssuerAdmissionBarrierRedisOwner.Readback readback) { + delegate.recordClosedReadback(prepared, readback); + } + } + private record FixtureState( CanonicalGameplayAdmissionAbortCompositionFixture fixture, Candidate candidate, diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java index e975fe751b..cc2c2729f5 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java @@ -79,6 +79,8 @@ class CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest { private static final String OWNER_PRINCIPAL = "gamesession_coord_app"; private static final String ISSUER_KEY_PREFIX = "session:game:index:issuer:"; private static final String METADATA_FIELD = "!issuer-partition-bootstrap/v1"; + private static final String ACKNOWLEDGEMENT_TABLE = + "game_session_canonical_issuer_binding_local_acknowledgement"; private static final BigInteger LAYOUT_VERSION = BigInteger.valueOf(3); private static final BigInteger PARTITION_COUNT = BigInteger.ONE; private static final BigInteger PARTITION_CAPACITY = BigInteger.valueOf(2); @@ -318,7 +320,7 @@ void projectsOrdinaryNewAgainstInstalledAnchorAndReusesExactPendingOperation() t assertThatThrownBy(() -> acknowledgementRepository.acknowledge(firstCapacityOnly)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("nonterminal binding"); - assertThat(count(dsl, "game_session_canonical_issuer_binding_local_acknowledgement")).isZero(); + assertThat(count(dsl, ACKNOWLEDGEMENT_TABLE)).isZero(); assertThat(count(dsl, "game_session_canonical_issuer_binding_local_ack_gen_counter")).isZero(); var firstCapacityFields = CanonicalGameplayIssuerBootstrapCoverageRepository.decodeFieldSet( @@ -542,8 +544,7 @@ void projectsOrdinaryNewAgainstInstalledAnchorAndReusesExactPendingOperation() t "Expected immutable local issuer operation") .get("member_status", String.class)) .isEqualTo("PENDING_PHYSICAL_PROOF"); - assertThat(count(dsl, "game_session_canonical_issuer_binding_local_acknowledgement")) - .isEqualTo(1L); + assertThat(count(dsl, ACKNOWLEDGEMENT_TABLE)).isEqualTo(1L); assertThat( Objects.requireNonNull( dsl.fetchOne( @@ -584,8 +585,7 @@ void projectsOrdinaryNewAgainstInstalledAnchorAndReusesExactPendingOperation() t .isEqualTo(issuerAcknowledgement.evidence().issuerBindingLocalAcknowledgementGeneration()); assertThat(restartedAcknowledgementRepository.readHistorical(first.operationId()).exactBytes()) .containsExactly(issuerAcknowledgement.exactBytes()); - assertThat(count(dsl, "game_session_canonical_issuer_binding_local_acknowledgement")) - .isEqualTo(1L); + assertThat(count(dsl, ACKNOWLEDGEMENT_TABLE)).isEqualTo(1L); assertThat( Objects.requireNonNull( dsl.fetchOne( @@ -611,8 +611,7 @@ void projectsOrdinaryNewAgainstInstalledAnchorAndReusesExactPendingOperation() t + " WHERE operation_id = ?", first.operationId())) .hasMessageContaining("issuer binding-local acknowledgements are immutable"); - assertThat(count(dsl, "game_session_canonical_issuer_binding_local_acknowledgement")) - .isEqualTo(1L); + assertThat(count(dsl, ACKNOWLEDGEMENT_TABLE)).isEqualTo(1L); currentState.set( new CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState( checkpointShape(BigInteger.valueOf(8)), incarnation)); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPhysicalRetirementIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPhysicalRetirementIntegrationTest.java index 505ac1730c..4f87d973bc 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPhysicalRetirementIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPhysicalRetirementIntegrationTest.java @@ -1003,6 +1003,38 @@ void postRetirementProjectionRejectsUnaccountedCurrentReservationInAnotherPartit } } + @Test + void seededReleaseCompletesWithoutPublishingTheOriginalAcknowledgement() { + try (var fixture = newFixture()) { + String seed = "release-without-original-acknowledgement"; + UUID seededOperationId = fixture.prepareOtherControllerNew(seed); + fixture.projectOtherControllerNew(seed); + fixture.publishOtherControllerNew(seed); + assertThat( + fixture + .dsl() + .fetchSingle( + "SELECT count(*) FROM game_session_canonical_issuer_binding_local_acknowledgement" + + " WHERE operation_id = ?", + fixture.originalOperationId()) + .get(0, Long.class)) + .isZero(); + assertThat(fixture.recordOtherAccountAbort(seed).isAccountAborted()).isTrue(); + var pendingRelease = fixture.prepareIssuerRelease(seed); + assertThat(pendingRelease.originalOperation().operationId()).isEqualTo(seededOperationId); + assertThat(seededOperationId).isNotEqualTo(fixture.originalOperationId()); + + var completed = + fixture.completeIssuerRelease( + pendingRelease, fixture.projectIssuerRelease(pendingRelease)); + assertThat(completed.status()) + .isEqualTo(CanonicalGameplayIssuerBindingLocalReleaseOperation.Status.RELEASED); + var retry = fixture.prepareIssuerRelease(seed); + assertThat(retry.operationId()).isEqualTo(completed.operationId()); + assertThat(fixture.projectIssuerRelease(retry).scriptOutcome()).isEqualTo(2L); + } + } + @Test void actualReleaseReadbackPersistsAndReloadsWithMoreThan513PhysicalFields() throws Exception { try (var fixture = newFixture(BigInteger.valueOf(8), BigInteger.ONE, 250)) { diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayProtectedIncarnationReceiverPostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayProtectedIncarnationReceiverPostgresIntegrationTest.java index 0ac444f51d..d3e9408b85 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayProtectedIncarnationReceiverPostgresIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayProtectedIncarnationReceiverPostgresIntegrationTest.java @@ -30,8 +30,11 @@ import java.util.List; import java.util.Map; import java.util.UUID; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor; import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingIdentity; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingTransitionRequest; @@ -79,6 +82,213 @@ class CanonicalGameplayProtectedIncarnationReceiverPostgresIntegrationTest { static GenericContainer redis = new GenericContainer<>(TestContainerImages.redis()).withExposedPorts(6379); + @Test + void localDescriptorFailuresRetainNeverDispatchedOriginalForLaterValidPreparation() + throws Exception { + try (Fixture.InitialFixture fixture = Fixture.InitialFixture.open(); + InitialRedisFixture physical = InitialRedisFixture.open(); + var login = fixture.originalLogin()) { + var snapshot = fixture.initialRepository.readCurrent(fixture.original.requestId()); + String retained = fixture.initialTargetPostimage(); + String key = + CanonicalGameplayAccountInitialBarrierKey.forTarget( + fixture.tenantTags.assignmentForInitialBarrierTarget(fixture.original.requestId()), + snapshot.initializerId(), + fixture.original.requestId()); + RedisClient undispatched = mock(RedisClient.class); + RedisScriptCatalog catalog = mock(RedisScriptCatalog.class); + when(catalog.require(CanonicalGameplayAccountInitialBarrierRedisScriptContribution.SCRIPT_ID)) + .thenThrow(new IllegalStateException("missing local descriptor")) + .thenReturn(mock(RedisScriptDescriptor.class)); + var owner = fixture.initialOwner(undispatched, fixture.initialRepository, catalog); + for (int failure = 0; failure < 2; failure++) { + assertThat( + owner.initializeOnce( + fixture.original, login, fixture.tenantId, fixture.namespaceId)) + .isEqualTo( + new CanonicalGameplayAccountInitialOpenProof.Refused( + CanonicalGameplayAccountInitialOpenProof.Reason.TARGET_NEVER_DISPATCHED)); + assertThat(fixture.initialRepository.readCurrent(fixture.original.requestId()).state()) + .isEqualTo( + CanonicalGameplayAccountInitialBarrierInitializerRepository.State.NEVER_DISPATCHED); + assertThat(fixture.initialTargetPostimage()).isEqualTo(retained); + assertThat(physical.connection.sync().exists(key)).isZero(); + } + org.mockito.Mockito.verifyNoInteractions(undispatched); + var validOwner = fixture.initialOwner(physical.ownerClient(), fixture.initialRepository); + assertThat( + validOwner.initializeOnce( + fixture.original, login, fixture.tenantId, fixture.namespaceId)) + .isInstanceOf(CanonicalGameplayAccountInitialOpenProof.CurrentOpen.class); + assertThat( + fixture.initialRepository.readCurrent(fixture.original.requestId()).initializerId()) + .isEqualTo(snapshot.initializerId()); + physical.connection.sync().del(key); + } + } + + @Test + void abandonedNeverDispatchedOriginalPreventsFreshInitialForLaterLogin() throws Exception { + try (Fixture.InitialFixture fixture = Fixture.InitialFixture.open()) { + String initializer = + fixture + .dsl + .fetchSingle( + "SELECT to_jsonb(i)::text FROM" + + " game_session_canonical_initial_account_barrier_initializer i") + .get(0, String.class); + String target = fixture.initialTargetPostimage(); + fixture.dsl.execute( + "UPDATE game_session_initial_gameplay_login_journal" + + " SET abandoned = TRUE, abandoned_at = clock_timestamp() WHERE request_id = ?", + fixture.original.requestId()); + String abandonedJournal = + fixture + .dsl + .fetchSingle( + "SELECT to_jsonb(j)::text FROM game_session_initial_gameplay_login_journal j" + + " WHERE request_id = ?", + fixture.original.requestId()) + .get(0, String.class); + var later = + new InitialGameplayLoginAttemptCoordinates(UUID.randomUUID(), UUID.randomUUID(), 18L); + try (var login = + Fixture.mockInitialLoginResult(later, fixture.accountId, UUID.randomUUID())) { + fixture.dsl.execute( + "INSERT INTO game_session_initial_gameplay_login_journal" + + " (request_id, caller_context_id, expected_attempt_fence) VALUES (?, ?, ?)", + later.requestId(), + later.callerContextId(), + later.expectedAttemptFence()); + fixture.dsl.execute( + "UPDATE game_session_initial_gameplay_login_journal" + + " SET verified_token_jti = ?, verified_token_sha256 = ?," + + " verified_token_generation = 1, verified_issuance_fence = 1" + + " WHERE request_id = ?", + login.evidence().tokenJti(), + login.evidence().tokenSha256(), + later.requestId()); + assertThatThrownBy( + () -> + fixture.initialRepository.beginOrRead( + later, login, fixture.tenantId, fixture.namespaceId)) + .hasStackTraceContaining("uq_gs_initial_account_barrier_never_retarget"); + } + assertThat( + fixture + .dsl + .fetchSingle( + "SELECT to_jsonb(i)::text FROM" + + " game_session_canonical_initial_account_barrier_initializer i") + .get(0, String.class)) + .isEqualTo(initializer); + assertThat(fixture.initialTargetPostimage()).isEqualTo(target); + assertThat( + fixture + .dsl + .fetchSingle( + "SELECT to_jsonb(j)::text FROM game_session_initial_gameplay_login_journal j" + + " WHERE request_id = ?", + fixture.original.requestId()) + .get(0, String.class)) + .isEqualTo(abandonedJournal); + assertThat( + fixture + .dsl + .fetchSingle( + "SELECT target_state FROM game_session_canonical_initial_account_barrier_target" + + " WHERE original_request_id = ?", + fixture.original.requestId()) + .get(0, String.class)) + .isEqualTo("NEVER_DISPATCHED"); + } + } + + @Test + void initialTagAssignmentAndDispatchSerializeInventoryBeforeControlInBothOrders() + throws Exception { + for (boolean tagFirst : List.of(true, false)) { + try (Fixture.InitialFixture fixture = Fixture.InitialFixture.open(); + var holder = Fixture.dataSource(fixture.schema).getConnection(); + var tagConnection = Fixture.dataSource(fixture.schema).getConnection(); + var dispatchConnection = Fixture.dataSource(fixture.schema).getConnection()) { + var observation = + fixture + .receiver(new ControlledSigner(fixture.keyPair)) + .observeForInitialAccountBarrier(fixture.original.requestId()); + DSLContext holderDsl = DSL.using(holder, SQLDialect.POSTGRES); + DSLContext tagDsl = DSL.using(tagConnection, SQLDialect.POSTGRES); + DSLContext dispatchDsl = DSL.using(dispatchConnection, SQLDialect.POSTGRES); + int holderPid = + java.util.Objects.requireNonNull( + holderDsl.fetchSingle("SELECT pg_backend_pid()").get(0, Integer.class)); + int tagPid = + java.util.Objects.requireNonNull( + tagDsl.fetchSingle("SELECT pg_backend_pid()").get(0, Integer.class)); + int dispatchPid = + java.util.Objects.requireNonNull( + dispatchDsl.fetchSingle("SELECT pg_backend_pid()").get(0, Integer.class)); + var tags = + new CanonicalGameplayTenantGameplayTagRepository( + tagDsl, fixture.targetWorkloadNamespace, 1); + var repository = + new CanonicalGameplayAccountInitialBarrierInitializerRepository( + dispatchDsl, Clock.fixed(NOW, ZoneOffset.UTC)); + java.util.concurrent.Callable tag = + () -> tags.assignmentForInitialBarrierTarget(fixture.original.requestId()); + java.util.concurrent.Callable dispatch = + () -> repository.recordDispatchPossible(fixture.original.requestId(), observation); + holder.setAutoCommit(false); + holderDsl.fetchSingle( + "SELECT account_id FROM game_session_canonical_account_coverage_control" + + " WHERE account_id = ? FOR UPDATE", + fixture.accountId); + try (var executor = Executors.newFixedThreadPool(2)) { + try { + var first = executor.submit(tagFirst ? tag : dispatch); + int firstPid = tagFirst ? tagPid : dispatchPid; + int secondPid = tagFirst ? dispatchPid : tagPid; + awaitInitialBackendBlockedBy(fixture.dsl, firstPid, holderPid); + var second = executor.submit(tagFirst ? dispatch : tag); + awaitInitialBackendBlockedBy(fixture.dsl, secondPid, firstPid); + // Neither waiter may own target rows before it owns account control. + holderDsl.fetchSingle( + "SELECT initializer_id FROM game_session_canonical_initial_account_barrier_initializer" + + " WHERE original_request_id = ? FOR UPDATE NOWAIT", + fixture.original.requestId()); + holder.rollback(); + assertThat(first.get(5L, TimeUnit.SECONDS)).isNotNull(); + assertThat(second.get(5L, TimeUnit.SECONDS)).isNotNull(); + } finally { + holder.rollback(); + } + } + assertThat(fixture.initialRepository.readCurrent(fixture.original.requestId()).state()) + .isEqualTo( + CanonicalGameplayAccountInitialBarrierInitializerRepository.State + .DISPATCH_POSSIBLE); + } + } + } + + private static void awaitInitialBackendBlockedBy( + DSLContext observer, int waitingPid, int holderPid) throws InterruptedException { + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); + boolean blocked = false; + while (System.nanoTime() < deadline) { + blocked = + Boolean.TRUE.equals( + observer + .fetchSingle("SELECT ? = ANY(pg_blocking_pids(?))", holderPid, waitingPid) + .get(0, Boolean.class)); + if (blocked) break; + TimeUnit.MILLISECONDS.sleep(10L); + } + assertThat(blocked) + .as("PostgreSQL backend %s waits on exact holder %s", waitingPid, holderPid) + .isTrue(); + } + @Test void initialOwnerComposesSqlSignedObservationAndRedisWithoutRecreatingResetOpen() throws Exception { @@ -1028,14 +1238,25 @@ private CanonicalGameplayLoginResult originalLogin() { private String initialTargetPostimage() { return dsl.fetchSingle( "SELECT to_jsonb(t)::text FROM game_session_canonical_initial_account_barrier_target t" - + " WHERE initializer_id = ?", - initialRepository.readCurrent(original.requestId()).initializerId()) + + " WHERE original_request_id = ?", + original.requestId()) .get(0, String.class); } private CanonicalGameplayAccountInitialBarrierRedisOwner initialOwner( RedisClient client, CanonicalGameplayAccountInitialBarrierInitializerRepository repository) { + return initialOwner( + client, + repository, + RedisScriptCatalog.fromContributions( + List.of(new CanonicalGameplayAccountInitialBarrierRedisScriptContribution()))); + } + + private CanonicalGameplayAccountInitialBarrierRedisOwner initialOwner( + RedisClient client, + CanonicalGameplayAccountInitialBarrierInitializerRepository repository, + RedisScriptCatalog catalog) { var configuration = new CanonicalGameplayProtectedIncarnationReceiver.TrustedConfiguration( ATTESTOR_BINDING, @@ -1055,12 +1276,7 @@ private CanonicalGameplayAccountInitialBarrierRedisOwner initialOwner( configuration, Clock.systemUTC()); return new CanonicalGameplayAccountInitialBarrierRedisOwner( - client, - RedisScriptCatalog.fromContributions( - List.of(new CanonicalGameplayAccountInitialBarrierRedisScriptContribution())), - repository, - tenantTags, - receiver); + client, catalog, repository, tenantTags, receiver); } private InitialGameplayLoginAttemptCoordinates original() { From b5ae981d58e57391be62b528fe9e7df711177aa8 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 29 Oct 2026 07:26:05 +1300 Subject: [PATCH 18/26] Install live issuer control in frozen-bootstrap retry proof --- ...icalGameplayIssuerBootstrapCoverageOwnerIntegrationTest.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapCoverageOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapCoverageOwnerIntegrationTest.java index bb0a8f7384..0243c31019 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapCoverageOwnerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapCoverageOwnerIntegrationTest.java @@ -323,6 +323,8 @@ void installedAnchorReadAndRetryUseFrozenPlanAfterOrdinaryNewAdvancesInventoryCl CanonicalGameplayIssuerInstalledAnchor installed = owner(fixture, () -> current) .completeInitialBootstrap(fixture.intent().operationId(), fixture.requestId()); + new CanonicalGameplayIssuerAdmissionControlRepository(fixture.dsl()) + .installInitialOpen(installed, () -> current); var candidate = identity(PARTITION_COUNT, PARTITION_CAPACITY, "post-anchor-ordinary-new"); new CanonicalGameplayIssuerBindingLocalOperationRepository(fixture.dsl(), () -> current) From d1b051ecf82e140b0e0e6d0bcc4af66977b77d1d Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 29 Oct 2026 07:51:07 +1300 Subject: [PATCH 19/26] Guard retained issuer admission evidence with forward migration --- .../game-session-service/runtime-and-data.md | 2 +- .../architecture/system-architecture-redis.md | 2 + design/project-management/ai-observations.md | 5 + .../player-access-and-session.md | 6 +- ...uer_admission_retained_evidence_guards.sql | 104 ++++++ ...ssionBarrierRepositoryIntegrationTest.java | 305 +++++++++++++++++- 6 files changed, 409 insertions(+), 15 deletions(-) create mode 100644 services/game-session-service/src/main/resources/db/migration/V1047.1__issuer_admission_retained_evidence_guards.sql diff --git a/design/architecture/microservices/game-session-service/runtime-and-data.md b/design/architecture/microservices/game-session-service/runtime-and-data.md index c70125c8ac..375414543f 100644 --- a/design/architecture/microservices/game-session-service/runtime-and-data.md +++ b/design/architecture/microservices/game-session-service/runtime-and-data.md @@ -10,7 +10,7 @@ The service runtime model assumes replaceable workers, not authoritative in-proc The sections below define the target-state runtime contract. Current implementation and proof status is: -- **Local NEW issuer preparation:** the unregistered Game Session sources now manually compose the initial issuer anchor, ordinary post-baseline one-key member/capacity projection, issuer-local release, and original-operation terminal-capacity retirement, each with exact physical readback and controlled Account checkpoint and stable-incarnation collaborators. Ordinary ADD revalidates the target’s current Account authority, while terminal cleanup and non-target accounting preserve captured Account provenance. Completed-original bootstrap retries return retained installation evidence; current physical verification remains separate. The focused component proofs do not establish operational source or incarnation custody. The unregistered readiness owners additionally retain a separate binding-local issuer acknowledgement, live issuer admission control and tenant-local issuer OPEN/cutoff evidence. These do not supply the final session CAS or admission. Operational source/incarnation custody, legacy recovery, production PKI, runtime registration, and activation remain open; see the [Player Access tracker](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-new-admission-components) for proof attribution and limits. The [issuer anchor owner](../../system-architecture-redis.md#installed-issuer-anchor-for-ordinary-new) defines the physical contract. +- **Local NEW issuer preparation:** the unregistered Game Session sources now manually compose the initial issuer anchor, ordinary post-baseline one-key member/capacity projection, issuer-local release, and original-operation terminal-capacity retirement, each with exact physical readback and controlled Account checkpoint and stable-incarnation collaborators. Ordinary ADD revalidates the target’s current Account authority, while terminal cleanup and non-target accounting preserve captured Account provenance. Completed-original bootstrap retries return retained installation evidence; current physical verification remains separate. The focused component proofs do not establish operational source or incarnation custody. The unregistered readiness owners additionally retain a separate binding-local issuer acknowledgement, live issuer admission control and tenant-local issuer OPEN/cutoff evidence. Forward V1047.1 protects original initializer, readback receipt, frozen cutoff cohort/target and operation evidence against direct SQL removal or rewrite, permitting only the existing owner completion transitions. These do not supply the final session CAS or admission. Operational source/incarnation custody, legacy recovery, production PKI, runtime registration, and activation remain open; see the [Player Access tracker](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-new-admission-components) for proof attribution and limits. The [issuer anchor owner](../../system-architecture-redis.md#installed-issuer-anchor-for-ordinary-new) defines the physical contract. - **Local NEW account-member repair:** the unregistered owner prepares the original binding-local operation, performs one global account-member write and physical readback outside SQL, then accepts its exact acknowledgement in SQL. This supplies `ADD_OR_RETAIN` evidence only; the candidate remains provisional. Account-wide lifecycle writers, remaining index and region acknowledgements, and the guarded final admission CAS remain open. See [Session Behavior](../../system-architecture-session-behavior.md#global-account-active-binding-index) and [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-new-admission-components). diff --git a/design/architecture/system-architecture-redis.md b/design/architecture/system-architecture-redis.md index 057b13752c..7386bb265e 100644 --- a/design/architecture/system-architecture-redis.md +++ b/design/architecture/system-architecture-redis.md @@ -475,6 +475,8 @@ A pending initial candidate whose inventory snapshot became stale may be superse Within the existing Game Session issuer inventory owner, initial tenant-local issuer barriers use a distinct typed live admission-control row. The immutable bootstrap intent, control row and installed anchor retain their original layout provenance; the live barrier epoch is independently owner-allocated and never interpreted as the bootstrap epoch. Installation requires the qualified anchor, exact current Account source, registered target and stable storage incarnation. Every ordinary preparation, pending initializer, issuer acknowledgement, barrier read and final consumer joins current live control in the same inventory, layout-control and admission-control lock order. Under that current authority, the owner persists one immutable initializer and its complete intended `OPEN` tuple before Redis work. Neither a missing key, an installed anchor alone nor Account's `NO_ACTIVE_ACCOUNT_WIDE_FLOW` state authorizes initialization. Pending initializers participate in the same serialized issuer intent/cutoff cohort as binding preparations: a concurrent intent blocks new initializers, captures every existing initializer, installs the required tenant-local cutoff barriers, and reaches declared `INSTALLED` only after its complete cohort qualifies. The initial one-key tenant-slot CAS refuses conflicting, residual, previously `CLOSED`, newer-epoch or reset state; it never reopens or overwrites a cutoff. Exact independent readback and a durable original-initializer receipt precede use, with current control, epoch, source and incarnation revalidated after the remote phase and again for an admitting issuer acknowledgement and final tenant-local CAS. No SQL transaction spans Redis. Lost replies and partial attempts retain the original initializer and stay non-admitting on uncertainty; they create no reset, recovery or activation authority. +Implementation limitation: the current unregistered issuer initializer cannot recover when its original NEW aborts before its first-create claim. The tenant/namespace remains non-admitting for that live epoch; the [implementation tracker](../project-management/implementation-tracking/player-access-and-session.md#canonical-new-admission-components) records the retained evidence and missing recovery proof. + ### Recovery and Cutoff Scope Authority The permitted scope is part of the evidence contract, not an operator hint. A region- or tenant-scoped preserved-session parent may enumerate only its binding-local snapshot, repair the region-local and tenant-scoped families it owns, and validate a linked child result. It may not map an issuer layout, perform issuer Redis field or reservation-capacity repair, read back issuer partitions for coverage, publish an issuer-partition acknowledgement, or claim global account-index coverage from its narrow snapshot. An issuer-wide child or standalone issuer operation must use a complete authoritative issuer inventory. A standalone operation carries `parentRecoveryOperationId=NOT_APPLICABLE`, `parentLifecycle=NOT_APPLICABLE`, `parentOperationFence=NOT_APPLICABLE`, and `parentCoverageFence=NOT_APPLICABLE`, then uses its own `issuerCoverageOperationId`, `issuerCoverageOperationFence`, distinct `coverageFence`, later `coverageGeneration`, pinned layout, and all finite partitions. A linked child retains the exact parent tuple through its independent edge but does not nest under the parent maintenance lock; the parent owns that lock and the child owns only its operation and coverage fences. An account-wide operation may cover only the untagged account family from a complete account inventory and its own account coverage evidence; it cannot substitute for issuer coverage. A cluster recovery must rebuild or consume complete per-account and per-issuer coverage for the deployment rather than treating a local region, tenant, or aggregate snapshot as global proof. diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 2995293f8b..df8ad837d6 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -493,3 +493,8 @@ Gameplay #3310 Hosted7 finished at 03:51:18 NZDT but its native evidence was rec - Context: #3320 CLI reported that a later issuer cutoff could strand an older CLOSED barrier because the SQL operation schema permits positive prior epochs. - Observation: Gameplay initially accepted and escalated that claim before reading the actual owner. `beginCutoff` already requires current OPEN control and the original anchor-install operation, rejecting INSTALLED before allocation. The source claim was corrected in native review history and the unnecessary decision request withdrawn. - Expected pattern: Verify the concrete owner guards and supported lifecycle before accepting a finding or escalating a design choice; a table admitting a representation does not establish a reachable supported transition. Preserve the original adjudication audit and correction without expanding fail-closed behavior. + +- `2026-10-29`: Tracker proof-cell links need the architecture contract check + - Context: #3320 added production/test anchors and a link from a capability proof cell to its own proof-summary paragraph. + - Observation: links and Markdown passed locally, but CI architecture-doc-contracts rejected the proof-cell documentation path; that column permits executable tests or canonical validation/smoke tooling. The test links were valid and remain retained. + - Expected pattern: run the existing architecture-doc-contracts check when changing capability anchors; keep summary/gap links outside proof cells and retain direct executable proof links inside them. This is a selection correction, not a new validation tool. 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 2221036a66..a16f675805 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -12,6 +12,8 @@ The current local review corrections permit ordinary NEW only after proving the The receiving #3320 prerequisite contains unregistered issuer LIVE control, tenant-local issuer OPEN/cutoff owners and the separate binding-local issuer acknowledgement, together with INITIAL-only Account OPEN initialization. Ordinary binding preparation and issuer projection join current live issuer control; pending Account initializers are included in the acquisition cohort, and both barrier owners retain original dispatch and exact readback evidence without reopening uncertain or CLOSED targets. The INITIAL Account arm retains one original initializer per account, tenant and playable-state namespace even when the original LOGIN is abandoned before dispatch. A later LOGIN cannot retarget that retained `NEVER_DISPATCHED` initializer or allocate a replacement through this arm; absence of Redis work does not grant new initialization authority. Account-wide fenced recovery and settlement are not supplied here, so recovery of that scope remains unqualified and non-admitting. R902 freshly passes 55 selected cases: 14 Game Session units, 30 physical Game Session cases and 11 actual Account–Game Session abort/migration compositions, with affected enabled main/unit/integration static analysis, formatting and documentation checks. Prepared issuer reads no longer consume creation authority; each owner validates its local script inputs before its durable one-shot claim. Proof covers retained preclaim failure and valid retry, competing claims with one winner, lost-claim absence refusal, cutoffs before and after a claim, abandoned INITIAL retention, and PostgreSQL-observed inventory/control serialization in both arrival orders. The claims still commit before the remote attempt, so postclaim interruption remains non-admitting uncertainty without rearming or automatic recovery. This is focused component/composition proof with controlled upstream source and test PKI inputs, not a complete service-suite or production-admission result. This readiness boundary does not contain original-NEW candidate installation, Account bound credential/handle issuance, the final controller CAS, committed Game Session result reader or whole-flow coordinator; those remain dependent preparation and final-admission work. Extraction receiving proof R849 passes 75 of 76 selected unit/native cases, including the full 256-cycle physical-retirement case; its aggregate remains failed because the historical Account fixture opened V1038 while invoking current issuer readiness. R855 then passes both the corrected current authenticated-owner composition and a separate populated V1038→V1038.1 migration-retention proof. Its aggregate failed only an unused private fixture overload; R856 passes affected Account static, formatting and documentation checks after removing that overload. The migration fixture uses controlled historical terminal rows, while the current composition independently proves real owner calls. Earlier component evidence below retains its original source attribution; this is focused receiving proof, not a complete service-suite or public admission result. R867 subsequently passes 23 current-parent receiving cases, including latest-schema issuer OPEN composition, controlled predecessor mutation receipt retention, shared region/Human regressions and authenticated Account abort cleanup, with affected static, frontier, generation, formatting and documentation checks. Historical receipt correlation remains controlled and claims no ordinary-NEW producer at the older schema. The current parent now owns the separately controlled V1038→V1038.1 retention case in the Account abort-composition test; its duplicate standalone Game Session fixture is removed here. Earlier proof retains its original source attribution. Operational source/incarnation custody, production PKI, default registration, public admission and activation remain unproved. +The issuer INITIAL arm has a tenant/namespace-wide liveness limit: if its frozen originating NEW becomes `ABORTED` while the initializer remains `PREPARED`, later eligible NEW attempts at that live epoch retain the same initializer but cannot claim creation. An absent tenant-slot key stays absent, leaving every affected account non-admitting. No creator transfer, initializer replacement, automatic rearming or OPEN restoration through cutoff is supplied. Preserve the original evidence and keep the scope fenced; a qualified recovery mechanism and its proof remain missing. R907 freshly passes all 37 issuer-admission native cases with zero skips, including the distinct-account aborted-origin refusal, populated V1047→V1047.1 upgrade preserving all original evidence bytes, row versions and prior Flyway history, direct update/delete/truncate refusal for all five retained families, legal completion/retry and rollback-only corruption checks. Frontier, jOOQ generation, affected integration static analysis, formatting and documentation checks pass. Forward V1047.1 enforces retained-evidence guards without replacing the missing recovery mechanism or granting runtime authority. + The current local correction adds explicit recovery for a stale, uninstalled initial issuer-bootstrap candidate. Forward V1038.3 retains its original intent, cohort and issued work, captures the new actual inventory cut under monotonic fences, and atomically binds immutable supersession lineage to current control. A strictly newer trusted layout separates old physical work; installed anchors remain ineligible. Account CI selection and migration task inputs now cover its Game Session owner-composition dependency, and the native registration-image and lost-reply proofs use their actual SQL/Lua contracts. R827 passes 31 of 32 focused cases; its remaining failure is a test assertion against the transaction wrapper rather than the nested PostgreSQL refusal. R828 then passes that complete recovery case with affected integration static and formatting checks. Together they qualify 32 distinct current-source cases, including two actual Account abort compositions; frontier, jOOQ, affected static, formatting and documentation checks pass. The new recovery sequence uses controlled Account terminal input through the actual Game Session abort owner, separately from those two authenticated Account compositions. This is focused proof, not a full service-suite, live layout rotation, retained-key cleanup or production-authority claim. The local issuer owners now reject plans that exceed the executable 256-member-operation bound per partition, including retained `RELEASED` lineage independently of logical active capacity. A blocked plan retains its complete cohort and planned work; physical preparation refuses before allocating operation rows. Fresh ordinary NEW registration also checks the same nonretired local-operation set under the inventory lock before allocating new identities or rows, while exact retries retain their original operation at the bound. Both bootstrap owners use one strict Account issuer source-event verifier. R791 freshly passes the four PostgreSQL boundary cases: 256 allowed, both 257-reservation overflow forms blocked, and ordinary registration refusal/retry with unchanged durable state. R793 then freshly passes all 26 selected PostgreSQL cases across the plan, ordinary-operation and intent owners, plus affected production/integration static analysis, formatting and documentation checks. This is focused owner proof, not a complete service-suite or public admission result. Default registration, external source custody and admission limits remain unchanged. @@ -361,11 +363,11 @@ Account connect-token issuance retains its existing bootstrap and scope authenti | Capability | Implementation | Verification | Design | Implementation anchors | Proof anchors | Secondary handoffs | Gap or decision | | --- | --- | --- | --- | --- | --- | --- | --- | | `AA-1.1` Account and profile identity | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Account runtime and data](../../architecture/microservices/account-service/runtime-and-data.md); [ADR 0042](../../architecture/decisions/adr-0042-global-account-and-tenant-scoped-game-relationships.md); [ADR 0020](../../architecture/decisions/adr-0020-scoped-domain-and-operational-identifiers.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [AccountDto.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountDto.java); [AccountMapper.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/mapper/AccountMapper.java); [AccountController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java); [ProfileController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/ProfileController.java); [AccountGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java); [RuntimeAccountIdentityGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/RuntimeAccountIdentityGrpcService.java); [AccountRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountRepository.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [openapi.yaml](../../../services/account-service/src/main/resources/openapi.yaml); [AccountIdentityProvenance.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountIdentityProvenance.java); [V1__init.sql](../../../services/account-service/src/main/resources/db/migration/V1__init.sql); [V26__global_registration_join_evidence.sql](../../../services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql); [V29__account_identity_uuid_bridge.sql](../../../services/account-service/src/main/resources/db/migration/V29__account_identity_uuid_bridge.sql) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountControllerTest.java); [PublicBootstrapRoutesProdProfileTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [RuntimeAccountIdentityGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/RuntimeAccountIdentityGrpcServiceTest.java); [AccountApplicationIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java); [AccountRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java); [ProfileControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/ProfileControllerTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Account V29 and `AccountRepository` persist/read back the non-nil Account UUID, recognized provenance, and unchanged numeric source-row identity required by ADR 0020. Registration REST/gRPC output and Account fields in the existing local exports now use that UUID; new registration audit records carry the same value, and the reverse DTO mapper is removed. `AccountDto` mapping rejects missing or contradictory UUID/provenance/source-row evidence. The focused unit/controller/gRPC suites executed 238 tests (174 AccountServiceImpl, 15 AccountController, 2 production-profile route, and 47 gRPC) with no failures, errors, or skips; the 5 PostgreSQL-backed Account application integration cases compiled but skipped because Docker is unavailable. Retained-row migration proof remains available but local PostgreSQL cases skip when Docker is disabled. Registration still creates global Account state plus its platform audit outbox row only, with no profile or tenant membership; caller-supplied tenant input is not authority. Authentication results and JWT subjects remain unchanged; profile/export profile identity fields and tenant IDs remain numeric and full portable export is not implemented. Current profile GET/PUT routes enforce exact caller-account subject binding and current tenant membership; tenant-qualified routes and membership-authority-generation validation remain gaps. Credential and email-OTP gameplay authentication remain global Account-identity operations that do not select a tenant or require current membership. `RuntimeAccountIdentityGrpcService` implements the authenticated Account-owner UUID/provenance read; its 31 focused unit cases, integration-source compilation, and formatting/documentation checks do not prove PostgreSQL execution or a live mTLS handshake, and do not enable UUID authentication or gameplay admission. Lifecycle-state retention remains tracked under AA-1.3. | -| `AA-1.2` Tenant membership, roles, and delegated access | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Authentication and authorization](../../architecture/system-architecture-authentication.md); [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md); [ADR 0042](../../architecture/decisions/adr-0042-global-account-and-tenant-scoped-game-relationships.md); [ADR 0138](../../architecture/decisions/adr-0138-expiring-playtest-grants-with-bounded-active-revocation.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [AccountJoinOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepository.java); [AccountConnectScopeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectScopeRepository.java); [ExpiredConnectScopeCleanupJob.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/ExpiredConnectScopeCleanupJob.java); [AccountAuditOutboxRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepository.java); [AccountCanonicalFirstJoinTerminalCoordinator.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinator.java); [AccountMembershipAuthorityEventProducer.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java); [AccountAuthorityGenerationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepository.java); [AccountAuthoritySourceEvidenceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidenceRepository.java); [AccountTenantAuthorityEventRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepository.java); [AccountDemoTenantEntitlementRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementRepository.java); [AccountTenantEntitlementOutboxRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantEntitlementOutboxRepository.java); [AccountActorStagingEligibilityService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountActorStagingEligibilityService.java); [AccountActorStagingEligibilityGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountActorStagingEligibilityGrpcService.java); [AccountActorStagingEligibilityRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountActorStagingEligibilityRepository.java); [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountTenantMembership.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountTenantMembership.java); [AccountRealmAccessGrant.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountRealmAccessGrant.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [V26__global_registration_join_evidence.sql](../../../services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql); [V27__retain_join_connect_scopes.sql](../../../services/account-service/src/main/resources/db/migration/V27__retain_join_connect_scopes.sql); [V30__approved_legacy_tenant_associations.sql](../../../services/account-service/src/main/resources/db/migration/V30__approved_legacy_tenant_associations.sql); [V31__subscription_authority_generation.sql](../../../services/account-service/src/main/resources/db/migration/V31__subscription_authority_generation.sql); [V32__realm_grant_currentness.sql](../../../services/account-service/src/main/resources/db/migration/V32__realm_grant_currentness.sql); [V33__fresh_tenant_identity_associations.sql](../../../services/account-service/src/main/resources/db/migration/V33__fresh_tenant_identity_associations.sql); [V34__account_membership_pair_authority.sql](../../../services/account-service/src/main/resources/db/migration/V34__account_membership_pair_authority.sql); [V35__canonical_uuid_membership_identity.sql](../../../services/account-service/src/main/resources/db/migration/V35__canonical_uuid_membership_identity.sql); [V36__account_auth_authority_generations.sql](../../../services/account-service/src/main/resources/db/migration/V36__account_auth_authority_generations.sql); [V37__canonical_first_join_scope_and_intent.sql](../../../services/account-service/src/main/resources/db/migration/V37__canonical_first_join_scope_and_intent.sql); [V38__account_first_join_authority_outbox_and_roles.sql](../../../services/account-service/src/main/resources/db/migration/V38__account_first_join_authority_outbox_and_roles.sql); [V39__canonical_first_join_terminal_receipt.sql](../../../services/account-service/src/main/resources/db/migration/V39__canonical_first_join_terminal_receipt.sql); [V40__account_authority_source_baselines.sql](../../../services/account-service/src/main/resources/db/migration/V40__account_authority_source_baselines.sql); [V53__account_protected_demo_entitlements.sql](../../../services/account-service/src/main/resources/db/migration/V53__account_protected_demo_entitlements.sql); [V73__account_tenant_authority_source_bridge.sql](../../../services/account-service/src/main/resources/db/migration/V73__account_tenant_authority_source_bridge.sql); [CanonicalGameplayAccountInitialBarrierInitializerRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierInitializerRepository.java); [CanonicalGameplayAccountInitialBarrierRedisOwner.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierRedisOwner.java); [V1047__canonical_initial_account_admission_barrier.sql](../../../services/game-session-service/src/main/resources/db/migration/V1047__canonical_initial_account_admission_barrier.sql) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [AccountAuditDeliveryJobTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuditDeliveryJobTest.java); [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [ExpiredConnectScopeCleanupJobTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/ExpiredConnectScopeCleanupJobTest.java); [AccountAuditOutboxRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepositoryTest.java); [AccountJoinDigestTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountJoinDigestTest.java); [AccountAuthoritySourceEvidencePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java); [AccountDemoTenantEntitlementPersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementPersistenceIntegrationTest.java); [AccountCanonicalFirstJoinEventIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinEventIntegrationTest.java); [AccountCanonicalFirstJoinTerminalCoordinatorTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinatorTest.java); [AccountMembershipAuthorityEventProducerCanonicalJoinTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducerCanonicalJoinTest.java); [AccountAuthorityGenerationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepositoryTest.java); [AccountTenantAuthorityEventRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepositoryTest.java); [AccountActorStagingEligibilityServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountActorStagingEligibilityServiceTest.java); [AccountActorStagingEligibilityGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountActorStagingEligibilityGrpcServiceTest.java); [CanonicalGameplayProtectedIncarnationReceiverPostgresIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayProtectedIncarnationReceiverPostgresIntegrationTest.java); [CanonicalGameplayAccountInitialBarrierRedisScriptIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierRedisScriptIntegrationTest.java); [readiness receiving proof](#canonical-new-admission-components) records R849 partial execution, R855/R856 recovery, R867 and current R902 focused results with their separate limits | [Realm Routing](./realm-routing-and-playable-state.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Membership and Account-owned realm-grant records/readers are separate. `AccountTenantAuthorityEventRepository` appends the canonical tenant authority event during demo entitlement provisioning; `AccountMembershipAuthorityEventProducer` emits the first-JOIN membership event with its billing cutoff taken from that current tenant authority event, covered by [AccountCanonicalFirstJoinEventIntegrationTest](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinEventIntegrationTest.java); no entitlement caller wires it, and current PostgreSQL proof remains pending because the integration source compiled but was unrun locally. Current connect-token issuance returns `AUTH_UNAVAILABLE` before replay-cache or fresh pointer/visibility/membership reads while the canonical producer is unavailable; target current-authority and postcondition revalidation remain unproved. Current explicit `JoinPublicProductionMembership` validates a server-issued scope and caller binding, re-reads Game Session routing/catalog/pointer evidence before the Account transaction, and binds a v1 digest to verified caller/scope inputs; it does not guarantee that the exact target/catalog/pointer remains valid through Account commit. The strict ADR 0025 commit gate remains incomplete, and no durable Game Session-owned target fence is implemented or proved; transaction duration or timing thresholds alone would not prove it. The subscription authority query's `FOR UPDATE` locks only the subscription row, not its joined billing-owner Account; JOIN also locks the caller Account and operation record. Terminal-operation replay performs remote scope/target/entitlement checks outside its lock-holding transaction. Pending JOINs continue to receive fresh remote reads, while the Account transaction retains atomic membership, operation-outcome, and audit-outbox persistence. Focused unit proof verifies terminal replay revalidation occurs after commit or rollback without rewriting the stored outcome; the PostgreSQL row-lock regression compiles but skips locally without Docker. PostgreSQL runtime proof and direct text-client end-to-end proof are unclaimed. Global-only registration no longer creates an admitting membership. Expired unreferenced connect-scope rows are swept under their existing expiry; V27's restrictive scope FK preserves every scope referenced by a PENDING or terminal JOIN and fences racing intent inserts. JOIN recovery/reconciliation after an unknown database commit outcome remains a separate #2848 gap under the Overseer decision; do not mark ADR 0025 complete. The Gateway continues to block public JOIN exposure, and Game Session text JOIN/Join & Play dispatch remains #2898. `AccountActorStagingEligibilityGrpcService` is a read-only internal eligibility check disabled by default; it does not establish that a realm is public or preseeded and grants no gameplay admission. Membership authority generation in runtime admission, issuance grant validation, cached-success freshness/postcondition revalidation, and the target five-field grant codec with cross-service producer/consumer and admission-propagation proof remain incomplete. Current non-public discovery and supported text `PLAY` require admitting membership before the applicable realm grant; connect-token issuance fails closed before these checks and does not establish target grant validation. Transactional outboxes beyond the implemented registration/JOIN audit records, monotonic versioning, rate limits, tenant-scoped roles, and delegated management remain target gaps; see the [canonical Redis grant codec](../../architecture/system-architecture-redis.md#canonical-grant-authority-stream-scope-codec) and [identifier glossary](../../architecture/system-architecture-identifier-glossary.md#non-public-grant-identity). The unregistered INITIAL Account prerequisite preserves one original target and does not supply abandoned-target or account-wide fenced recovery, fresh Account authority, final admission or runtime activation; see the [readiness scope and proof](#canonical-new-admission-components). | +| `AA-1.2` Tenant membership, roles, and delegated access | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Authentication and authorization](../../architecture/system-architecture-authentication.md); [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md); [ADR 0042](../../architecture/decisions/adr-0042-global-account-and-tenant-scoped-game-relationships.md); [ADR 0138](../../architecture/decisions/adr-0138-expiring-playtest-grants-with-bounded-active-revocation.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [AccountJoinOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepository.java); [AccountConnectScopeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectScopeRepository.java); [ExpiredConnectScopeCleanupJob.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/ExpiredConnectScopeCleanupJob.java); [AccountAuditOutboxRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepository.java); [AccountCanonicalFirstJoinTerminalCoordinator.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinator.java); [AccountMembershipAuthorityEventProducer.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java); [AccountAuthorityGenerationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepository.java); [AccountAuthoritySourceEvidenceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidenceRepository.java); [AccountTenantAuthorityEventRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepository.java); [AccountDemoTenantEntitlementRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementRepository.java); [AccountTenantEntitlementOutboxRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantEntitlementOutboxRepository.java); [AccountActorStagingEligibilityService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountActorStagingEligibilityService.java); [AccountActorStagingEligibilityGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountActorStagingEligibilityGrpcService.java); [AccountActorStagingEligibilityRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountActorStagingEligibilityRepository.java); [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountTenantMembership.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountTenantMembership.java); [AccountRealmAccessGrant.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountRealmAccessGrant.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [V26__global_registration_join_evidence.sql](../../../services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql); [V27__retain_join_connect_scopes.sql](../../../services/account-service/src/main/resources/db/migration/V27__retain_join_connect_scopes.sql); [V30__approved_legacy_tenant_associations.sql](../../../services/account-service/src/main/resources/db/migration/V30__approved_legacy_tenant_associations.sql); [V31__subscription_authority_generation.sql](../../../services/account-service/src/main/resources/db/migration/V31__subscription_authority_generation.sql); [V32__realm_grant_currentness.sql](../../../services/account-service/src/main/resources/db/migration/V32__realm_grant_currentness.sql); [V33__fresh_tenant_identity_associations.sql](../../../services/account-service/src/main/resources/db/migration/V33__fresh_tenant_identity_associations.sql); [V34__account_membership_pair_authority.sql](../../../services/account-service/src/main/resources/db/migration/V34__account_membership_pair_authority.sql); [V35__canonical_uuid_membership_identity.sql](../../../services/account-service/src/main/resources/db/migration/V35__canonical_uuid_membership_identity.sql); [V36__account_auth_authority_generations.sql](../../../services/account-service/src/main/resources/db/migration/V36__account_auth_authority_generations.sql); [V37__canonical_first_join_scope_and_intent.sql](../../../services/account-service/src/main/resources/db/migration/V37__canonical_first_join_scope_and_intent.sql); [V38__account_first_join_authority_outbox_and_roles.sql](../../../services/account-service/src/main/resources/db/migration/V38__account_first_join_authority_outbox_and_roles.sql); [V39__canonical_first_join_terminal_receipt.sql](../../../services/account-service/src/main/resources/db/migration/V39__canonical_first_join_terminal_receipt.sql); [V40__account_authority_source_baselines.sql](../../../services/account-service/src/main/resources/db/migration/V40__account_authority_source_baselines.sql); [V53__account_protected_demo_entitlements.sql](../../../services/account-service/src/main/resources/db/migration/V53__account_protected_demo_entitlements.sql); [V73__account_tenant_authority_source_bridge.sql](../../../services/account-service/src/main/resources/db/migration/V73__account_tenant_authority_source_bridge.sql); [CanonicalGameplayAccountInitialBarrierInitializerRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierInitializerRepository.java); [CanonicalGameplayAccountInitialBarrierRedisOwner.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierRedisOwner.java); [V1047__canonical_initial_account_admission_barrier.sql](../../../services/game-session-service/src/main/resources/db/migration/V1047__canonical_initial_account_admission_barrier.sql) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [AccountAuditDeliveryJobTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuditDeliveryJobTest.java); [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [ExpiredConnectScopeCleanupJobTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/ExpiredConnectScopeCleanupJobTest.java); [AccountAuditOutboxRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepositoryTest.java); [AccountJoinDigestTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountJoinDigestTest.java); [AccountAuthoritySourceEvidencePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java); [AccountDemoTenantEntitlementPersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementPersistenceIntegrationTest.java); [AccountCanonicalFirstJoinEventIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinEventIntegrationTest.java); [AccountCanonicalFirstJoinTerminalCoordinatorTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinatorTest.java); [AccountMembershipAuthorityEventProducerCanonicalJoinTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducerCanonicalJoinTest.java); [AccountAuthorityGenerationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepositoryTest.java); [AccountTenantAuthorityEventRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepositoryTest.java); [AccountActorStagingEligibilityServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountActorStagingEligibilityServiceTest.java); [AccountActorStagingEligibilityGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountActorStagingEligibilityGrpcServiceTest.java); [CanonicalGameplayProtectedIncarnationReceiverPostgresIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayProtectedIncarnationReceiverPostgresIntegrationTest.java); [CanonicalGameplayAccountInitialBarrierRedisScriptIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierRedisScriptIntegrationTest.java); R849 partial execution, R855/R856 recovery, R867 and R902 focused execution have separate scopes and limits recorded above | [Realm Routing](./realm-routing-and-playable-state.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Membership and Account-owned realm-grant records/readers are separate. `AccountTenantAuthorityEventRepository` appends the canonical tenant authority event during demo entitlement provisioning; `AccountMembershipAuthorityEventProducer` emits the first-JOIN membership event with its billing cutoff taken from that current tenant authority event, covered by [AccountCanonicalFirstJoinEventIntegrationTest](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinEventIntegrationTest.java); no entitlement caller wires it, and current PostgreSQL proof remains pending because the integration source compiled but was unrun locally. Current connect-token issuance returns `AUTH_UNAVAILABLE` before replay-cache or fresh pointer/visibility/membership reads while the canonical producer is unavailable; target current-authority and postcondition revalidation remain unproved. Current explicit `JoinPublicProductionMembership` validates a server-issued scope and caller binding, re-reads Game Session routing/catalog/pointer evidence before the Account transaction, and binds a v1 digest to verified caller/scope inputs; it does not guarantee that the exact target/catalog/pointer remains valid through Account commit. The strict ADR 0025 commit gate remains incomplete, and no durable Game Session-owned target fence is implemented or proved; transaction duration or timing thresholds alone would not prove it. The subscription authority query's `FOR UPDATE` locks only the subscription row, not its joined billing-owner Account; JOIN also locks the caller Account and operation record. Terminal-operation replay performs remote scope/target/entitlement checks outside its lock-holding transaction. Pending JOINs continue to receive fresh remote reads, while the Account transaction retains atomic membership, operation-outcome, and audit-outbox persistence. Focused unit proof verifies terminal replay revalidation occurs after commit or rollback without rewriting the stored outcome; the PostgreSQL row-lock regression compiles but skips locally without Docker. PostgreSQL runtime proof and direct text-client end-to-end proof are unclaimed. Global-only registration no longer creates an admitting membership. Expired unreferenced connect-scope rows are swept under their existing expiry; V27's restrictive scope FK preserves every scope referenced by a PENDING or terminal JOIN and fences racing intent inserts. JOIN recovery/reconciliation after an unknown database commit outcome remains a separate #2848 gap under the Overseer decision; do not mark ADR 0025 complete. The Gateway continues to block public JOIN exposure, and Game Session text JOIN/Join & Play dispatch remains #2898. `AccountActorStagingEligibilityGrpcService` is a read-only internal eligibility check disabled by default; it does not establish that a realm is public or preseeded and grants no gameplay admission. Membership authority generation in runtime admission, issuance grant validation, cached-success freshness/postcondition revalidation, and the target five-field grant codec with cross-service producer/consumer and admission-propagation proof remain incomplete. Current non-public discovery and supported text `PLAY` require admitting membership before the applicable realm grant; connect-token issuance fails closed before these checks and does not establish target grant validation. Transactional outboxes beyond the implemented registration/JOIN audit records, monotonic versioning, rate limits, tenant-scoped roles, and delegated management remain target gaps; see the [canonical Redis grant codec](../../architecture/system-architecture-redis.md#canonical-grant-authority-stream-scope-codec) and [identifier glossary](../../architecture/system-architecture-identifier-glossary.md#non-public-grant-identity). The unregistered INITIAL Account prerequisite preserves one original target and does not supply abandoned-target or account-wide fenced recovery, fresh Account authority, final admission or runtime activation; see the [readiness scope and proof](#canonical-new-admission-components). | | `AA-1.3` Authentication, recovery, security policy, and account data rights | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Security](../../architecture/system-architecture-security.md); [Account runtime and data](../../architecture/microservices/account-service/runtime-and-data.md); [Moderation Policies](../../architecture/microservices/logging-admin-service/moderation-policies.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0034](../../architecture/decisions/adr-0034-layered-abuse-controls-without-attacker-triggered-account-locks.md); [ADR 0035](../../architecture/decisions/adr-0035-single-record-issued-token-registry.md); [ADR 0141](../../architecture/decisions/adr-0141-fixed-safety-restriction-categories-and-independent-lifecycles.md); [ADR 0142](../../architecture/decisions/adr-0142-bounded-moderation-appeal-cases.md); [ADR 0047](../../architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md); [Account API Contracts](../../architecture/microservices/account-service/api-contracts.md#operator-authorization-references); [Logging & Admin API Contracts](../../architecture/microservices/logging-admin-service/api-contracts.md); [Game Session API Contracts](../../architecture/microservices/game-session-service/api-contracts.md) | [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java); [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [SessionServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/SessionServiceImpl.java); [JwksController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/JwksController.java); [AccountAuthorityGenerationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepository.java); [AccountAuthoritySourceEvidenceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidenceRepository.java); [AccountJwtSignerDesiredStateRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtSignerDesiredStateRepository.java); [AccountJwtReadinessProbeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtReadinessProbeRepository.java); [AccountControlUiIssuanceService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceService.java); [AccountStartSessionOperatorAuthorizationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationService.java); [AccountJwtSignerMaterializationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationService.java); [application-prod.yml](../../../services/account-service/src/main/resources/application-prod.yml); [V36__account_auth_authority_generations.sql](../../../services/account-service/src/main/resources/db/migration/V36__account_auth_authority_generations.sql); [V40__account_authority_source_baselines.sql](../../../services/account-service/src/main/resources/db/migration/V40__account_authority_source_baselines.sql); [V77 reset receipts](../../../services/account-service/src/main/resources/db/migration/V77__account_password_reset_operation_receipts.sql); [V89 pending reset intent](../../../services/account-service/src/main/resources/db/migration/V89__account_password_reset_pending_draft_source_changes.sql); [V99__account_jwt_signer_desired_state.sql](../../../services/account-service/src/main/resources/db/migration/V99__account_jwt_signer_desired_state.sql); [V123__account_jwt_readiness_per_pod_closure.sql](../../../services/account-service/src/main/resources/db/migration/V123__account_jwt_readiness_per_pod_closure.sql); [V125__account_jwt_signer_promotion_receipt_binding.sql](../../../services/account-service/src/main/resources/db/migration/V125__account_jwt_signer_promotion_receipt_binding.sql); [V126](../../../services/account-service/src/main/resources/db/migration/V126__start_session_operator_authorization.sql); [V126.1](../../../services/account-service/src/main/resources/db/migration/V126.1__start_session_operator_response_envelope_erasure.sql); [V126.2](../../../services/account-service/src/main/resources/db/migration/V126.2__account_control_ui_registry_cleanup_deadline.sql); [V126.3](../../../services/account-service/src/main/resources/db/migration/V126.3__start_session_response_envelope_bounds.sql); [AccountPlatformRestrictionOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationRepository.java); [V137__account_platform_restriction_revision_receipts.sql](../../../services/account-service/src/main/resources/db/migration/V137__account_platform_restriction_revision_receipts.sql); [V137.1__account_platform_restriction_lifecycle_consistency.sql](../../../services/account-service/src/main/resources/db/migration/V137.1__account_platform_restriction_lifecycle_consistency.sql); [AccountPlatformRestrictionMutationRequest.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountPlatformRestrictionMutationRequest.java); [AccountSecurityStateAuthorityEventV1Codec.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1Codec.java); [AccountAuthoritySourceEventReadback.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadback.java); [AccountPasswordResetOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepository.java); [AccountPasswordResetDraftSourceChangeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPasswordResetDraftSourceChangeRepository.java); [PasswordResetTokenRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/PasswordResetTokenRepository.java); [V140](../../../services/account-service/src/main/resources/db/migration/V140__account_gameplay_admission_lease_operations.sql); [V141](../../../services/account-service/src/main/resources/db/migration/V141__account_admission_unknown_decision_abort.sql); [V142](../../../services/account-service/src/main/resources/db/migration/V142__account_admission_durable_commit_confirmation.sql); [V143](../../../services/account-service/src/main/resources/db/migration/V143__account_global_pending_admission_fences.sql); [V144](../../../services/account-service/src/main/resources/db/migration/V144__account_admission_original_ack_receipt.sql); [V145](../../../services/account-service/src/main/resources/db/migration/V145__retire_experimental_admission_confirmation_writes.sql); [V146](../../../services/account-service/src/main/resources/db/migration/V146__account_original_ack_pg18_fresh_insert.sql); [AccountGameplayAdmissionLeaseRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeaseRepository.java); [AccountGameplayAdmissionOriginalCommitExecutor.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalCommitExecutor.java); [AccountGameplayAdmissionOriginalAckReceiptRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptRepository.java); [AccountGameplayAdmissionOriginalAckReceiptCommitExecutor.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptCommitExecutor.java); [V158](../../../services/account-service/src/main/resources/db/migration/V158__account_start_session_authority_captures.sql); [V159](../../../services/account-service/src/main/resources/db/migration/V159__start_session_world_participation.sql); [V160](../../../services/account-service/src/main/resources/db/migration/V160__start_session_world_original_attempt_evidence.sql); [AccountStartSessionAuthorityCaptureRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCaptureRepository.java); [AccountStartSessionWorldParticipationRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationRepository.java); [AccountStartSessionWorldOriginalAttemptEvidenceRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidenceRepository.java); [V160.1](../../../services/account-service/src/main/resources/db/migration/V160.1__start_session_operator_bundle_source_fence.sql); [AccountStartSessionWorldParticipationAcquisitionService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationAcquisitionService.java); [AccountStartSessionWorldParticipationHistoricalReadService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationHistoricalReadService.java); [AccountStartSessionWorldParticipationSettlementService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationSettlementService.java); [Logging StartSessionAuthorizationCoordinator.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinator.java); [Logging StartSessionOperatorAuthorizationClient.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClient.java); [Logging StartSessionPreAuthorizationReservationRepository.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/repository/StartSessionPreAuthorizationReservationRepository.java); [Game Session StartSessionOperatorRedemptionClient.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClient.java); [GameSessionStartSessionOperatorAttemptRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepository.java); [GameSessionCanonicalLaunchPreparationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationService.java); [CanonicalGameInstanceLaunchAssociationRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameInstanceLaunchAssociationRepository.java); [V1003 original StartSession protections](../../../services/account-service/src/main/resources/db/migration/V1003__original_start_session_source_protections.sql); [V1004 activation settlement lifecycle integrity](../../../services/account-service/src/main/resources/db/migration/V1004__activation_settlement_lifecycle_integrity.sql); [V1004.1 monotonic lifecycle counters](../../../services/account-service/src/main/resources/db/migration/V1004.1__activation_settlement_monotonic_lifecycle_counters.sql); [V1004.2 retained lifecycle and canonical UUID integrity](../../../services/account-service/src/main/resources/db/migration/V1004.2__activation_settlement_retained_lifecycle_integrity.sql); [V1004.3 canonical activation acquisition carriers](../../../services/account-service/src/main/resources/db/migration/V1004.3__activation_acquisition_canonical_carriers.sql); [AccountStartSessionActivationProtectionRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionRepository.java); [V1006 World activation terminal digest alignment](../../../services/account-service/src/main/resources/db/migration/V1006__world_activation_terminal_digest_alignment.sql); [V1007 selected source reservations](../../../services/account-service/src/main/resources/db/migration/V1007__selected_owner_intake_source_reservations.sql); [AccountSelectedOwnerIntakeSourceReservationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationService.java); [V1008 selected-owner intake final authorizations](../../../services/account-service/src/main/resources/db/migration/V1008__selected_owner_intake_final_authorizations.sql); [V1009 selected-owner intake terminal settlement](../../../services/account-service/src/main/resources/db/migration/V1009__selected_owner_intake_terminal_settlement.sql); [V1010 Entity selected-owner intake terminal settlement](../../../services/account-service/src/main/resources/db/migration/V1010__entity_selected_owner_intake_terminal_settlement.sql); [AccountSelectedOwnerIntakeSettlementService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementService.java); [AccountSelectedOwnerIntakeAuthorizationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationService.java); [AccountSelectedOwnerIntakeWorldClosureAuthorizationReadService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeWorldClosureAuthorizationReadService.java); [AccountSelectedOwnerIntakeSettlementReceipt.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/AccountSelectedOwnerIntakeSettlementReceipt.java); [AccountStartSessionAdmissionProtectionAcquisitionService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionService.java); [AccountStartSessionAdmissionProtectionSettlementService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionSettlementService.java); [AccountStartSessionAdmissionProtectionGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionGrpcService.java); [AccountStartSessionAdmissionProtectionRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionRepository.java) | [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [JwksControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/JwksControllerTest.java); [AuthTokenInterceptorTest.java](../../../services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/AuthTokenInterceptorTest.java); [AccountAuthorityGenerationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepositoryTest.java); [AccountAuthoritySourceEvidencePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java); [PasswordResetAuthorityProducerPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/PasswordResetAuthorityProducerPostgresIntegrationTest.java); [AccountPasswordResetOperationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepositoryTest.java); [AccountJwtSignerStoragePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountJwtSignerStoragePostgresIntegrationTest.java); [AccountJwtReadinessStoragePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessStoragePostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java); [AccountControlUiIssuancePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuancePostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorizationConfigurationTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountStartSessionOperatorAuthorizationConfigurationTest.java); [AccountJwtJwksTrustedSourceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksTrustedSourceTest.java); [AccountStartSessionOperatorAuthorizationServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationServiceTest.java); [StartSessionOperatorAuthorizationGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/StartSessionOperatorAuthorizationGrpcServiceTest.java); [AccountJwtSignerMaterializationServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationServiceTest.java); [AccountPlatformRestrictionOperationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationPostgresIntegrationTest.java); [AccountPlatformRestrictionOperationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationRepositoryTest.java); [AccountAuthoritySourceEventReadbackTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadbackTest.java); [AccountSecurityStateAuthorityEventV1CodecTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1CodecTest.java); [AccountGenerationProjectionRestrictionDispatchTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountGenerationProjectionRestrictionDispatchTest.java); [RuntimeMembershipAuthorityEvidenceValidatorRestrictionDispatchTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimeMembershipAuthorityEvidenceValidatorRestrictionDispatchTest.java); [AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java); [AccountStartSessionWorldParticipationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationPostgresIntegrationTest.java); [AccountStartSessionWorldOriginalAttemptEvidencePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidencePostgresIntegrationTest.java); [AccountStartSessionAuthorityCapturePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCapturePostgresIntegrationTest.java); [HostedTermsDisclosureHandoffPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/HostedTermsDisclosureHandoffPostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorityBundleTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorityBundleTest.java); [Logging StartSessionOperatorAuthorizationClientTest.java](../../../services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClientTest.java); [Logging StartSessionAuthorizationCoordinatorTest.java](../../../services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinatorTest.java); [Logging reservation PostgreSQL test](../../../services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/StartSessionPreAuthorizationReservationPostgresIntegrationTest.java); [Game Session StartSessionOperatorRedemptionClientTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClientTest.java); [Game Session operator-attempt storage test](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepositoryIntegrationTest.java); [Game Session canonical launch preparation test](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationServiceIntegrationTest.java); [Admission protection PostgreSQL suite](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java); [Activation protection PostgreSQL suite](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionPostgresIntegrationTest.java); [AccountSelectedOwnerIntakeSourceReservationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationPostgresIntegrationTest.java); [SelectedOwnerSourceDisclosurePostgresIntegrationTest.java](../../../services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedOwnerSourceDisclosurePostgresIntegrationTest.java); [AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java); [AccountSelectedOwnerIntakeSettlementServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementServiceTest.java); [SelectedOwnerIntakeSettlementGrpcCodecTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSettlementGrpcCodecTest.java); [AccountStartSessionAdmissionProtectionAcquisitionPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionPostgresIntegrationTest.java); [AccountStartSessionAdmissionProtectionRepositoryPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionRepositoryPostgresIntegrationTest.java); [AccountStartSessionAdmissionProtectionServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionServiceTest.java); [AccountStartSessionAdmissionProtectionGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionGrpcServiceTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md); [Platform Operations](./platform-operations-and-delivery.md) | Public password-reset, username-recovery, and email-verification initiation use normalized email selectors and return the same neutral HTTP success for known and unknown addresses, including when known-account post-commit SMTP errors are caught and logged; unknown addresses create no token or delivery attempt. However, SMTP delivery remains synchronous after commit and is a timing oracle; durable asynchronous delivery is absent, and focused service tests prove exception containment only, not timing resistance or durable delivery. Public verification accepts no numeric account selector. The login-factor `PUT` now fails closed with `501 NOT_IMPLEMENTED` because Account has no recent ordinary reauthentication evidence mechanism; implementing that Account-owned proof and enabling the mutation remain open under ADR 0045. The current Account restriction slice adds a closed restriction event variant, V137 immutable revision/current-result receipts, exact SQL source-head dispatch, and protective-category lifecycle sync; the owner mutation stays default-denied because no authoritative policy/intent and authenticated-caller proof receiver exists. V137.1 adds forward final-state protective-category consistency guards while preserving published V137 and retained V126.x bytes. The staged Java writer rejects protective restrictions on pending-deletion and deleted accounts before side effects; supported deletion/recovery producer sequencing remains a gap. V81 (source V88) `NONRESTRICTED` birth results remain historical predecessor evidence, not current absence; physical forward migration, contradiction rollback, concurrency, and readback proof remain pending, so no authorized admission or end-to-end enforcement is claimed. Separate complete bounded moderation appeal handoff, `/auth/logout` and `/auth/logout-all` revocation authority, TOTP, trusted source context, Account-owned graduated login throttles, and fail-closed limiter-outage behavior remain absent. Current token issuance still writes scope-duplicated account/tenant keys and downstream validators do not enforce the one-record issued-token registry from ADR 0035. `AUTH_ACCOUNT_LOCKED` remains reserved, while the current Game Session command limiter performs a Redis operation per command contrary to ADR 0034. Current `AccountServiceImpl.deleteAccount` fails closed by rejecting any retained JOIN operation first, then nonterminal subscriptions, and otherwise throwing `ACCOUNT_DELETE_UNAVAILABLE` before any repository deletion; retained-data lifecycle and deletion reconciliation remain unimplemented. Password-reset token consumption and exact source-fenced completion are implemented for Accounts with valid current source evidence; reset-driven revocation, other recovery workflows, and passing physical PostgreSQL proof remain incomplete. Export and JWKS foundations are live. Account signer lifecycle, current readiness, and validator-inventory storage remain passive V99–V125 evidence preparation; focused physical PostgreSQL 18 signer/readiness suites confirm bounded storage proof only with synthetic inventory/resource inputs, not live Kubernetes currentness, readiness activation, or signer activation; signer runtime/currentness remains inactive. V126/V126.1 separately add Account-owned StartSession authorization and signer-materialization source preparation: StartSession composition remains off by default, materializer trust remains off by default and denies every RPC when absent, and missing bootstrap-coordinator composition denies enrollment and promotion. These source adapters do not register a runtime issuer or promotion/consumer coordinator, establish operator lifecycle ownership under AA-1.3, or establish activation. The current AA-1.3 owner-source cut also includes V126.2 cleanup-deadline storage and V126.3 response-envelope size-guard migration. At exact source head `44bbd2a9fff1e1561816e16fd0deb9cc274ae251`, the Control-UI issuance PostgreSQL suite passed 5/5, including retained-V126.2 row preservation and denial; direct PostgreSQL proof that a newly recorded cleanup deadline cannot be changed remains a tracked gap. Bounded cleanup and late revocation remain incomplete. StartSession recovery accepts a 128 KiB authority bundle and 144 KiB binding/response within the 160 KiB envelope ceiling; the exact-head authorization repository suite passed 15/15 and covers fresh-install, ambiguous legacy-guard rejection, the 160 KiB storage edge, and retained maximum-size V126.2 ciphertext through V126.3 migration. This is bounded fixture proof and does not establish complete mTLS flow or runtime activation. Current receiving original-ACK PostgreSQL proof remains pending. The Account admission-protection acquisition, settlement, gRPC and repository sources are manually composed, but remain unregistered. Focused proof is recorded by the acquisition PostgreSQL, repository PostgreSQL, service unit and gRPC service unit suites linked above; this does not establish runtime registration, the downstream final-admission path, production authority or PKI, operational custody, or Entity placement and delivery. The World protected-activation consumer is also unregistered. The historical R9 report above records 13 Account PostgreSQL cases and four composed World/Account/Game Session cases, including exact authenticated World terminal settlement, with its missing tested-snapshot and original XML attribution stated explicitly. The separately source-bound receiving proof above qualifies only its named scope. These controlled upstream inputs establish no broader proof; runtime registration, genuine upstream authority, admission, Entity placement and delivery remain unproved. V1003 storage remains passive and V1004 lifecycle integrity checks do not authenticate World. V1004.1 and V1004.2 provide storage checks for nondecreasing lifecycle counters, retained PREPARING evidence, and canonical activation-request UUID spelling. V1004.3 requires canonical Base64 spellings for the tuple, projection, launch-read, and PREPARING lifecycle carriers at acquisition; its focused physical PostgreSQL and retained-row upgrade proof passes in the 25-case Account gate, including all 16 whitespace variants. These are controlled Account integrity checks; authenticated World production and runtime activation remain unproved. | | `AA-1.4` Commerce, subscriptions, purchases, donations, and platform fees | `partial` | `audited` | [Subscription management](../../architecture/microservices/account-service/subscription-management.md); [Stripe integration](../../architecture/microservices/account-service/stripe-integration.md); [Account runtime/data](../../architecture/microservices/account-service/runtime-and-data.md); [ADR 0143](../../architecture/decisions/adr-0143-stripe-v1-hosting-billing-and-deferred-creator-monetization.md) | [PaymentServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImpl.java); [PurchaseWorkflowServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PurchaseWorkflowServiceImpl.java); [PaymentTransaction.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/PaymentTransaction.java); [Subscription.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Subscription.java); [payment_service.proto](../../../protos/account/v1/payment_service.proto); [V2__payment_tables.sql](../../../services/account-service/src/main/resources/db/migration/V2__payment_tables.sql); [application.yml](../../../services/account-service/src/main/resources/application.yml) | [PaymentServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImplTest.java); [PaymentGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentGrpcServiceTest.java); [PurchaseWorkflowServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PurchaseWorkflowServiceImplTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Incomplete subscription creation now fails closed before mutation instead of persisting a caller-selected locally active entitlement row. The target caller-bound billing-owner, stable request/digest, instrument, outbox, provider lifecycle/reconciliation, billing-safe owner transfer/deletion guards, and complete subscription-to-entitlement follow-through remain absent. Before first subscription creation can be enabled, Account must define the authoritative initial billing-owner source and consent/assignment workflow with a version/generation fence; no such source is selected, and caller-supplied account ID, tenant role, Creator Party, or payment-instrument ownership must not be inferred as that authority. The generic `CreatePaymentIntent`, `CreateDonation`, and `RefundPayment` RPCs fail closed with `FAILED_PRECONDITION` before `PaymentService` or provider invocation; the generic service/provider substrate remains unsupported. Creator/player purchases, donations, fees/shares, payouts, and settlement are deferred and not supported by current code. | | `AA-1.5` Entitlements, quotas, and hosting eligibility | `partial` | `drift-found` | [Subscription management](../../architecture/microservices/account-service/subscription-management.md); [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Versioning and runtime](../../architecture/system-architecture-versioning-runtime.md); [ADR 0028](../../architecture/decisions/adr-0028-differentiated-entitlement-freshness.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [RuntimeEntitlementsDto.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/RuntimeEntitlementsDto.java); [Subscription.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Subscription.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [application.yml](../../../services/account-service/src/main/resources/application.yml) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [PublicBootstrapRoutesProdProfileTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Game Authoring](./game-authoring-publishing-and-activation.md) | The producer returns retryable `ENTITLEMENT_UNAVAILABLE` for zero or multiple tenant subscription rows and projects status only from exactly one explicit row; gRPC carries the unavailable outcome in its error field and HTTP bootstrap routes map it to 503. Focused Account proofs cover zero rows, conflicting active/canceled rows, gRPC classification, and connect-token retry after recovery without caching an unavailable receipt. Explicit free/trial row creation and authoritative current-row selection/constraint/history remain absent. The runtime response still lacks committed status and the full explicit entitlement/freshness evidence; its row-ID-derived version/sequence and newly stamped evaluation time, quotas, real sequencing/source freshness, caching/events, strict new-commitment enforcement, five-minute continuity, and instance lifecycle enforcement remain open. The target handoff between fresh connect-token reissuance and eligible exact-binding entitlement-only reconnect continuity is unresolved: token expiry can block that continuity before Account's resume lease, and no fallback reissuance path is authorized pending owner decision. Current `past_due` handling remains gameplay-available and public-join-eligible only when the sole explicit row is `past_due`. | -| `AA-2.1` Gameplay login, character selection, and session binding | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0021](../../architecture/decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md); [JWT and Token Contracts](../../architecture/system-architecture-jwt-and-token-contracts.md#game-session-original-attempt-coordination); [Gateway Architecture](../../architecture/system-architecture-gateway.md#gameplay-websocket-route) | [SessionAuthenticationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionAuthenticationService.java); [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [CanonicalGameplayMigrationDriverMain.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMain.java); [CanonicalGameplayMigrationDriverProtocol.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocol.java); [CanonicalGameplayMigrationDriverLauncher.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverLauncher.java); [game-session-service build](../../../services/game-session-service/build.gradle.kts); [AccountGameplayCanonicalLoginOwner.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayCanonicalLoginOwner.java); [AccountGameplayDelegationIssuanceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuanceRepository.java); [V147__account_gameplay_delegation_issuance.sql](../../../services/account-service/src/main/resources/db/migration/V147__account_gameplay_delegation_issuance.sql); [V157.1__account_gameplay_token_fence_truncate_guard.sql](../../../services/account-service/src/main/resources/db/migration/V157.1__account_gameplay_token_fence_truncate_guard.sql); [CanonicalGameplayRosterSelectionService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionService.java); [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [GatewayFirstPartyConnectContextEnvelope.java](../../../services/common-security/src/main/java/net/firedevops/firemud/common/security/GatewayFirstPartyConnectContextEnvelope.java); [FirstPartyConnectContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContext.java); [FirstPartyConnectContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextService.java); [FirstPartyConnectContextRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextRegistry.java); [FirstPartyConnectContextResolution.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextResolution.java); [RedisFirstPartyConnectContextRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisFirstPartyConnectContextRegistry.java); [GameSessionWebSocketHandshakeInterceptor.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptor.java); [GameSessionWebSocketHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandler.java); [SessionRoutingNormalizationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationService.java); [InitialGameplayLoginOwner.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialGameplayLoginOwner.java); [CanonicalGameplayLoginAccountClient.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalGameplayLoginAccountClient.java); [CanonicalGameplayLoginResult.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalGameplayLoginResult.java); [GameplayHandshakeFilter.java](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/filter/GameplayHandshakeFilter.java); [GameplayRouteReadinessHealthIndicator.java](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/health/GameplayRouteReadinessHealthIndicator.java); [FirstPartyConnectContextConfig.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/FirstPartyConnectContextConfig.java); [FirstPartyConnectContextProperties.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/FirstPartyConnectContextProperties.java); [CanonicalPlayerRouteReadService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalPlayerRouteReadService.java); [SessionContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContext.java); [RedisSessionContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java); [ActiveTransportSessionRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/ActiveTransportSessionRegistry.java); [InMemoryActiveTransportSessionRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/InMemoryActiveTransportSessionRegistry.java); [CommunicationRecipientDeliveryService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CommunicationRecipientDeliveryService.java); [PlayerOutputDeliveryService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/PlayerOutputDeliveryService.java); [CanonicalGameplayIssuerAdmissionControlRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionControlRepository.java); [CanonicalGameplayIssuerAdmissionBarrierRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepository.java); [CanonicalGameplayIssuerBindingLocalAcknowledgementRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalAcknowledgementRepository.java); [V1045__canonical_issuer_binding_local_acknowledgement.sql](../../../services/game-session-service/src/main/resources/db/migration/V1045__canonical_issuer_binding_local_acknowledgement.sql); [V1046__canonical_issuer_live_admission_control.sql](../../../services/game-session-service/src/main/resources/db/migration/V1046__canonical_issuer_live_admission_control.sql) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [CanonicalGameplayMigrationDriverMainTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMainTest.java); [CanonicalGameplayMigrationDriverProtocolTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocolTest.java); [CanonicalGameplayMigrationDriverStdoutTest.java](../../../services/game-session-service/src/test/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverStdoutTest.java); [migration-driver image contract](../../../dev-tools/tests/game-session-migration-driver-image-contract.sh); [V34.3 PostgreSQL fixture](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayInitialAdmissionIntentRequestIdMigrationIntegrationTest.java); [AccountGameplayCanonicalLoginOwnerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayCanonicalLoginOwnerTest.java); [AccountGameplayDelegationIssuancePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuancePersistenceIntegrationTest.java); [CanonicalGameplayRosterSelectionServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionServiceTest.java); [GatewayFirstPartyConnectContextEnvelopeTest.java](../../../services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/GatewayFirstPartyConnectContextEnvelopeTest.java); [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [FirstPartyConnectContextServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextServiceTest.java); [FirstPartyConnectContextResolutionTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextResolutionTest.java); [RedisFirstPartyConnectContextRegistryTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisFirstPartyConnectContextRegistryTest.java); [GameSessionWebSocketHandshakeInterceptorTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptorTest.java); [GameSessionWebSocketHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerTest.java); [InitialGameplayLoginOwnerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/InitialGameplayLoginOwnerTest.java); [InitialGameplayLoginContextRedisIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextRedisIntegrationTest.java); [CanonicalGameplayLoginAccountClientTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalGameplayLoginAccountClientTest.java); [CanonicalGameplayLoginResultTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/dto/CanonicalGameplayLoginResultTest.java); [GameplayHandshakeFilterTest.java](../../../services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/filter/GameplayHandshakeFilterTest.java); [GameplayRouteReadinessHealthIndicatorTest.java](../../../services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/health/GameplayRouteReadinessHealthIndicatorTest.java); [CanonicalPlayerRouteReadServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalPlayerRouteReadServiceTest.java); [RedisSessionContextServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextServiceTest.java); [SessionContextTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionContextTest.java); [InitialGameplayLoginCoordinationJournalRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/InitialGameplayLoginCoordinationJournalRepositoryIntegrationTest.java); [InMemoryActiveTransportSessionRegistryTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InMemoryActiveTransportSessionRegistryTest.java); [CommunicationRecipientDeliveryServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CommunicationRecipientDeliveryServiceTest.java); [PlayerOutputDeliveryServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/PlayerOutputDeliveryServiceTest.java); [CanonicalGameplayIssuerAdmissionBarrierRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepositoryIntegrationTest.java); [CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java); [readiness receiving proof](#canonical-new-admission-components) records R849 partial execution, R855/R856 recovery, R867 and current R902 focused results with their separate limits | [Realm Routing](./realm-routing-and-playable-state.md); [Player Experience](./player-experience-commands-and-communication.md) | Gameplay admission and binding remain partial. Exact-head execution scope and fixture results, including the V34.3 fixture pass, are recorded in the [consolidated proof record](#consolidated-exact-head-and-historical-proof). This verifies the tested migration fixture, not namespace-aware atomic takeover: that remains incomplete, as do issuer-index and region reconciliation and retained-binding inventory/conversion. Final immutable image build and authority, trusted bootstrap/execution, and live playable proof remain unproved. Current `/auth/connect-token` validates existing bootstrap and scope, then returns `AUTH_UNAVAILABLE` before cached-success replay, token minting, or replay/session mutation. The canonical Account producer, shared replay fence, dedicated Gateway signing keys, and deployment qualification remain unavailable. Game Session retains complete signed-context, canonical-route/private-handle, and retention sources, but public first-party bare `LOGIN`/`PLAY` deny before legacy Account, Entity, or binding effects; partial selectors never provide fallback. Generic credential LOGIN/PLAY and retained-edge rebind remain separate behavior, and earlier first-party happy-handshake/reconnect proofs are historical. Synthetic actor fallback, descriptor/template resolution, and fork-local identity proof remain gaps under [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) and the [Game Session persisted-actor boundary](../../architecture/microservices/game-session-service/runtime-and-data.md#persisted-actor-admission-boundary). Deployment/mTLS and fresh-image proof for gameplay admission remain incomplete; gameplay completion under #2967/#2898 remains open. Live no-key disposal remains fail-closed pending the protected retained binding-history/restore-continuity producer tracked with `PO-3.4` in [Platform Operations](./platform-operations-and-delivery.md#capability-status). The initial private gameplay LOGIN now has local unregistered composition source; runtime caller registration and authentication, deployed ACL/TLS and signer custody, missing-Account decoy timing parity, and singleton source-fence allocator throughput remain open (see [source-intake status](#initial-private-gameplay-login-issuance-source-intake)). The default-off roster selection source has no player-command caller; `PLAY`/`LOOK` activation and live owner-RPC execution remain unproved, so `AA-2.1` stays partial. Issuer LIVE/OPEN/cutoff and INITIAL Account components are manually composed prerequisites, not complete original NEW or playable admission; custody, default registration, final admission and activation remain unqualified as recorded in the [readiness scope and proof](#canonical-new-admission-components). | +| `AA-2.1` Gameplay login, character selection, and session binding | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0021](../../architecture/decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md); [JWT and Token Contracts](../../architecture/system-architecture-jwt-and-token-contracts.md#game-session-original-attempt-coordination); [Gateway Architecture](../../architecture/system-architecture-gateway.md#gameplay-websocket-route) | [SessionAuthenticationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionAuthenticationService.java); [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [CanonicalGameplayMigrationDriverMain.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMain.java); [CanonicalGameplayMigrationDriverProtocol.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocol.java); [CanonicalGameplayMigrationDriverLauncher.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverLauncher.java); [game-session-service build](../../../services/game-session-service/build.gradle.kts); [AccountGameplayCanonicalLoginOwner.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayCanonicalLoginOwner.java); [AccountGameplayDelegationIssuanceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuanceRepository.java); [V147__account_gameplay_delegation_issuance.sql](../../../services/account-service/src/main/resources/db/migration/V147__account_gameplay_delegation_issuance.sql); [V157.1__account_gameplay_token_fence_truncate_guard.sql](../../../services/account-service/src/main/resources/db/migration/V157.1__account_gameplay_token_fence_truncate_guard.sql); [CanonicalGameplayRosterSelectionService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionService.java); [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [GatewayFirstPartyConnectContextEnvelope.java](../../../services/common-security/src/main/java/net/firedevops/firemud/common/security/GatewayFirstPartyConnectContextEnvelope.java); [FirstPartyConnectContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContext.java); [FirstPartyConnectContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextService.java); [FirstPartyConnectContextRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextRegistry.java); [FirstPartyConnectContextResolution.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextResolution.java); [RedisFirstPartyConnectContextRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisFirstPartyConnectContextRegistry.java); [GameSessionWebSocketHandshakeInterceptor.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptor.java); [GameSessionWebSocketHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandler.java); [SessionRoutingNormalizationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationService.java); [InitialGameplayLoginOwner.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialGameplayLoginOwner.java); [CanonicalGameplayLoginAccountClient.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalGameplayLoginAccountClient.java); [CanonicalGameplayLoginResult.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalGameplayLoginResult.java); [GameplayHandshakeFilter.java](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/filter/GameplayHandshakeFilter.java); [GameplayRouteReadinessHealthIndicator.java](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/health/GameplayRouteReadinessHealthIndicator.java); [FirstPartyConnectContextConfig.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/FirstPartyConnectContextConfig.java); [FirstPartyConnectContextProperties.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/FirstPartyConnectContextProperties.java); [CanonicalPlayerRouteReadService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalPlayerRouteReadService.java); [SessionContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContext.java); [RedisSessionContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java); [ActiveTransportSessionRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/ActiveTransportSessionRegistry.java); [InMemoryActiveTransportSessionRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/InMemoryActiveTransportSessionRegistry.java); [CommunicationRecipientDeliveryService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CommunicationRecipientDeliveryService.java); [PlayerOutputDeliveryService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/PlayerOutputDeliveryService.java); [CanonicalGameplayIssuerAdmissionControlRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionControlRepository.java); [CanonicalGameplayIssuerAdmissionBarrierRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepository.java); [CanonicalGameplayIssuerBindingLocalAcknowledgementRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalAcknowledgementRepository.java); [V1045__canonical_issuer_binding_local_acknowledgement.sql](../../../services/game-session-service/src/main/resources/db/migration/V1045__canonical_issuer_binding_local_acknowledgement.sql); [V1046__canonical_issuer_live_admission_control.sql](../../../services/game-session-service/src/main/resources/db/migration/V1046__canonical_issuer_live_admission_control.sql) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [CanonicalGameplayMigrationDriverMainTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMainTest.java); [CanonicalGameplayMigrationDriverProtocolTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocolTest.java); [CanonicalGameplayMigrationDriverStdoutTest.java](../../../services/game-session-service/src/test/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverStdoutTest.java); [migration-driver image contract](../../../dev-tools/tests/game-session-migration-driver-image-contract.sh); [V34.3 PostgreSQL fixture](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayInitialAdmissionIntentRequestIdMigrationIntegrationTest.java); [AccountGameplayCanonicalLoginOwnerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayCanonicalLoginOwnerTest.java); [AccountGameplayDelegationIssuancePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuancePersistenceIntegrationTest.java); [CanonicalGameplayRosterSelectionServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionServiceTest.java); [GatewayFirstPartyConnectContextEnvelopeTest.java](../../../services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/GatewayFirstPartyConnectContextEnvelopeTest.java); [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [FirstPartyConnectContextServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextServiceTest.java); [FirstPartyConnectContextResolutionTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextResolutionTest.java); [RedisFirstPartyConnectContextRegistryTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisFirstPartyConnectContextRegistryTest.java); [GameSessionWebSocketHandshakeInterceptorTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptorTest.java); [GameSessionWebSocketHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerTest.java); [InitialGameplayLoginOwnerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/InitialGameplayLoginOwnerTest.java); [InitialGameplayLoginContextRedisIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextRedisIntegrationTest.java); [CanonicalGameplayLoginAccountClientTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalGameplayLoginAccountClientTest.java); [CanonicalGameplayLoginResultTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/dto/CanonicalGameplayLoginResultTest.java); [GameplayHandshakeFilterTest.java](../../../services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/filter/GameplayHandshakeFilterTest.java); [GameplayRouteReadinessHealthIndicatorTest.java](../../../services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/health/GameplayRouteReadinessHealthIndicatorTest.java); [CanonicalPlayerRouteReadServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalPlayerRouteReadServiceTest.java); [RedisSessionContextServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextServiceTest.java); [SessionContextTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionContextTest.java); [InitialGameplayLoginCoordinationJournalRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/InitialGameplayLoginCoordinationJournalRepositoryIntegrationTest.java); [InMemoryActiveTransportSessionRegistryTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InMemoryActiveTransportSessionRegistryTest.java); [CommunicationRecipientDeliveryServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CommunicationRecipientDeliveryServiceTest.java); [PlayerOutputDeliveryServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/PlayerOutputDeliveryServiceTest.java); [CanonicalGameplayIssuerAdmissionBarrierRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepositoryIntegrationTest.java); [CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java); R849 partial execution, R855/R856 recovery, R867 and R902 focused execution have separate scopes and limits recorded above | [Realm Routing](./realm-routing-and-playable-state.md); [Player Experience](./player-experience-commands-and-communication.md) | Gameplay admission and binding remain partial. Exact-head execution scope and fixture results, including the V34.3 fixture pass, are recorded in the [consolidated proof record](#consolidated-exact-head-and-historical-proof). This verifies the tested migration fixture, not namespace-aware atomic takeover: that remains incomplete, as do issuer-index and region reconciliation and retained-binding inventory/conversion. Final immutable image build and authority, trusted bootstrap/execution, and live playable proof remain unproved. Current `/auth/connect-token` validates existing bootstrap and scope, then returns `AUTH_UNAVAILABLE` before cached-success replay, token minting, or replay/session mutation. The canonical Account producer, shared replay fence, dedicated Gateway signing keys, and deployment qualification remain unavailable. Game Session retains complete signed-context, canonical-route/private-handle, and retention sources, but public first-party bare `LOGIN`/`PLAY` deny before legacy Account, Entity, or binding effects; partial selectors never provide fallback. Generic credential LOGIN/PLAY and retained-edge rebind remain separate behavior, and earlier first-party happy-handshake/reconnect proofs are historical. Synthetic actor fallback, descriptor/template resolution, and fork-local identity proof remain gaps under [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) and the [Game Session persisted-actor boundary](../../architecture/microservices/game-session-service/runtime-and-data.md#persisted-actor-admission-boundary). Deployment/mTLS and fresh-image proof for gameplay admission remain incomplete; gameplay completion under #2967/#2898 remains open. Live no-key disposal remains fail-closed pending the protected retained binding-history/restore-continuity producer tracked with `PO-3.4` in [Platform Operations](./platform-operations-and-delivery.md#capability-status). The initial private gameplay LOGIN now has local unregistered composition source; runtime caller registration and authentication, deployed ACL/TLS and signer custody, missing-Account decoy timing parity, and singleton source-fence allocator throughput remain open (see [source-intake status](#initial-private-gameplay-login-issuance-source-intake)). The default-off roster selection source has no player-command caller; `PLAY`/`LOOK` activation and live owner-RPC execution remain unproved, so `AA-2.1` stays partial. Issuer LIVE/OPEN/cutoff and INITIAL Account components are manually composed prerequisites, not complete original NEW or playable admission; custody, default registration, final admission and activation remain unqualified as recorded in the [readiness scope and proof](#canonical-new-admission-components). | | `AA-2.2` Reconnect, resume eligibility, and cross-device continuity | `partial` | `drift-found` | [Reconnection](../../architecture/system-architecture-reconnection.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [Redis architecture](../../architecture/system-architecture-redis.md); [ADR 0019](../../architecture/decisions/adr-0019-separate-active-session-resume-and-transcript-lifetimes.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md); [ADR 0133](../../architecture/decisions/adr-0133-fresh-edge-reconnect-without-client-input-replay.md); [ADR 0134](../../architecture/decisions/adr-0134-bounded-durable-semantic-reconnect-context.md) | [SessionAuthenticationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionAuthenticationService.java); [RedisSessionContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java); [DurableScreenBufferService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DurableScreenBufferService.java); [GameplayWebSocketBridgeHandler.java](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketBridgeHandler.java); [FirstPartyConnectContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextService.java); [EffectiveReconnectionSettingsResolver.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/EffectiveReconnectionSettingsResolver.java) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [LookWebSocketCrossServiceTest.java](../../../services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/LookWebSocketCrossServiceTest.java); [GameSessionWebSocketHandlerIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java); [Telnet cross-service test](../../../services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/TelnetGatewayGameSessionAccountCrossServiceIntegrationTest.java) | [Player Experience](./player-experience-commands-and-communication.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md); [Platform Operations](./platform-operations-and-delivery.md) | Generic resume, bounded semantic context, and edge rebind exist, but the effective disconnected-resume window is resolved without `PLAY` enforcement; namespace-aware binding/transfer, complete authenticated real-service replacement, lifecycle/presence/stalled-input outcomes, first-party post-logout replay suppression, and proof of fresh-edge `LOOK`/prompt behavior are not complete or proved. The earlier first-party post-logout replay defect is historical: current first-party `LOGIN` and `PLAY` deny before legacy effects while the genuine context consumers remain unavailable. Successful post-logout replay suppression and a complete playable flow remain unproved. Fresh edge reconnect must not replay client input/bytes/frames and must end with fresh `LOOK` plus exactly one reconnect prompt when both effective reconnect-prompt settings are enabled, or zero reconnect prompts when either is disabled. Full token refresh, membership-version and membership-authority-generation persistence, revocation, and non-edge restart continuity remain. See AA-2.1 for the finite namespace controller-index migration-driver prefix, its implementation and proof anchors, and the unproved physical PostgreSQL/Redis, final-image, and trusted-bootstrap/execution gates. | | `AA-2.3` Takeover, logout, idle expiry, and revocation | `partial` | `drift-found` | [Session behavior](../../architecture/system-architecture-session-behavior.md); [Reconnection](../../architecture/system-architecture-reconnection.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md) | [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [LogoutCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandler.java); [RedisSessionContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java); [TelnetServerHandler.java](../../../services/tcp-proxy-service/src/main/java/net/firedevops/firemud/tcpproxy/telnet/TelnetServerHandler.java); [application.yml](../../../services/game-session-service/src/main/resources/application.yml) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [LogoutCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandlerTest.java); [LookWebSocketCrossServiceTest.java](../../../services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/LookWebSocketCrossServiceTest.java) | [Player Experience](./player-experience-commands-and-communication.md); [World Runtime](./world-runtime-and-movement.md); [Gameplay Rules](./gameplay-rules-entities-and-effects.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Gameplay takeover/LOGOUT and transport idle-close handling exist; target takeover requires namespace-scoped atomic monotonic `bindingGeneration`, old-input fencing, and preservation of already-admitted work as defined by [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md), while Account control-plane logout/authority-generation workflows, full idle/session expiry convergence, and first-party post-logout replay cleanup are absent. | diff --git a/services/game-session-service/src/main/resources/db/migration/V1047.1__issuer_admission_retained_evidence_guards.sql b/services/game-session-service/src/main/resources/db/migration/V1047.1__issuer_admission_retained_evidence_guards.sql new file mode 100644 index 0000000000..955c235a9f --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V1047.1__issuer_admission_retained_evidence_guards.sql @@ -0,0 +1,104 @@ +-- Retain original issuer admission evidence. Only the existing owner's one-way completion +-- updates are allowed; insertion and current control authority remain with their existing owners. +-- [jooq ignore start] +CREATE FUNCTION guard_gs_issuer_admission_immutable_evidence() RETURNS trigger AS $$ +BEGIN + RAISE EXCEPTION 'Retained issuer admission evidence is immutable: %', TG_TABLE_NAME + USING ERRCODE = '23514'; +END; +$$ LANGUAGE plpgsql; + +CREATE FUNCTION guard_gs_issuer_admission_initializer() RETURNS trigger AS $$ +BEGIN + IF TG_OP IN ('DELETE', 'TRUNCATE') THEN + RAISE EXCEPTION 'Retained issuer admission initializer cannot be removed' + USING ERRCODE = '23514'; + END IF; + IF (to_jsonb(NEW) - 'initialization_state') + IS DISTINCT FROM (to_jsonb(OLD) - 'initialization_state') + OR NOT ((OLD.initialization_state = 'PREPARED' AND NEW.initialization_state = 'INITIALIZING') + OR (OLD.initialization_state = 'INITIALIZING' AND NEW.initialization_state = 'OPEN_CONFIRMED')) THEN + RAISE EXCEPTION 'Retained issuer admission initializer permits only original forward completion' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE FUNCTION guard_gs_issuer_admission_cutoff_target() RETURNS trigger AS $$ +BEGIN + IF TG_OP IN ('DELETE', 'TRUNCATE') THEN + RAISE EXCEPTION 'Retained issuer admission cutoff target cannot be removed' + USING ERRCODE = '23514'; + END IF; + IF (to_jsonb(NEW) - ARRAY['target_state', 'exact_closed_readback_bytes', + 'exact_closed_readback_digest', 'script_outcome']) + IS DISTINCT FROM + (to_jsonb(OLD) - ARRAY['target_state', 'exact_closed_readback_bytes', + 'exact_closed_readback_digest', 'script_outcome']) + OR OLD.target_state <> 'REQUIRED' OR NEW.target_state <> 'CLOSED' + OR OLD.exact_closed_readback_bytes IS NOT NULL + OR OLD.exact_closed_readback_digest IS NOT NULL OR OLD.script_outcome IS NOT NULL + OR NEW.exact_closed_readback_bytes IS DISTINCT FROM OLD.closed_payload_bytes + OR NEW.exact_closed_readback_digest IS DISTINCT FROM OLD.closed_payload_digest + OR NEW.script_outcome IS NULL OR NEW.script_outcome NOT IN (1, 2, 3) THEN + RAISE EXCEPTION 'Retained issuer admission cutoff target requires its one exact original readback' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE FUNCTION guard_gs_issuer_admission_operation() RETURNS trigger AS $$ +BEGIN + IF TG_OP IN ('DELETE', 'TRUNCATE') THEN + RAISE EXCEPTION 'Retained issuer admission operation cannot be removed' + USING ERRCODE = '23514'; + END IF; + IF (to_jsonb(NEW) - ARRAY['operation_state', 'installed_at']) + IS DISTINCT FROM (to_jsonb(OLD) - ARRAY['operation_state', 'installed_at']) + OR OLD.operation_kind <> 'CUTOFF' + OR OLD.operation_state <> 'CUTOFF_PENDING' OR NEW.operation_state <> 'INSTALLED' + OR OLD.installed_at IS NOT NULL OR NEW.installed_at IS NULL THEN + RAISE EXCEPTION 'Retained issuer admission operation permits only original cutoff installation' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER gs_issuer_admission_initializer_guard + BEFORE UPDATE OR DELETE ON game_session_canonical_issuer_admission_initializer + FOR EACH ROW EXECUTE FUNCTION guard_gs_issuer_admission_initializer(); +CREATE TRIGGER gs_issuer_admission_initializer_retention + BEFORE TRUNCATE ON game_session_canonical_issuer_admission_initializer + FOR EACH STATEMENT EXECUTE FUNCTION guard_gs_issuer_admission_initializer(); + +CREATE TRIGGER gs_issuer_admission_receipt_guard + BEFORE UPDATE OR DELETE ON game_session_canonical_issuer_admission_initializer_receipt + FOR EACH ROW EXECUTE FUNCTION guard_gs_issuer_admission_immutable_evidence(); +CREATE TRIGGER gs_issuer_admission_receipt_retention + BEFORE TRUNCATE ON game_session_canonical_issuer_admission_initializer_receipt + FOR EACH STATEMENT EXECUTE FUNCTION guard_gs_issuer_admission_immutable_evidence(); + +CREATE TRIGGER gs_issuer_admission_cohort_guard + BEFORE UPDATE OR DELETE ON game_session_canonical_issuer_admission_cohort_row + FOR EACH ROW EXECUTE FUNCTION guard_gs_issuer_admission_immutable_evidence(); +CREATE TRIGGER gs_issuer_admission_cohort_retention + BEFORE TRUNCATE ON game_session_canonical_issuer_admission_cohort_row + FOR EACH STATEMENT EXECUTE FUNCTION guard_gs_issuer_admission_immutable_evidence(); + +CREATE TRIGGER gs_issuer_admission_cutoff_target_guard + BEFORE UPDATE OR DELETE ON game_session_canonical_issuer_admission_cutoff_target + FOR EACH ROW EXECUTE FUNCTION guard_gs_issuer_admission_cutoff_target(); +CREATE TRIGGER gs_issuer_admission_cutoff_target_retention + BEFORE TRUNCATE ON game_session_canonical_issuer_admission_cutoff_target + FOR EACH STATEMENT EXECUTE FUNCTION guard_gs_issuer_admission_cutoff_target(); + +CREATE TRIGGER gs_issuer_admission_operation_guard + BEFORE UPDATE OR DELETE ON game_session_canonical_issuer_admission_operation + FOR EACH ROW EXECUTE FUNCTION guard_gs_issuer_admission_operation(); +CREATE TRIGGER gs_issuer_admission_operation_retention + BEFORE TRUNCATE ON game_session_canonical_issuer_admission_operation + FOR EACH STATEMENT EXECUTE FUNCTION guard_gs_issuer_admission_operation(); +-- [jooq ignore stop] diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepositoryIntegrationTest.java index d115c97024..be8fda1442 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepositoryIntegrationTest.java @@ -36,6 +36,9 @@ import net.firedevops.firemud.gamesession.service.CanonicalGameplayIssuerAdmissionBarrierRedisScriptContribution; import net.firedevops.firemud.gamesession.service.CanonicalGameplayIssuerBindingLocalRedisScriptContribution; import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.api.MigrationVersion; +import org.jooq.DSLContext; +import org.jooq.impl.DSL; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -54,6 +57,9 @@ class CanonicalGameplayIssuerAdmissionBarrierRepositoryIntegrationTest { private static final String ISSUER = GameSessionAccountDelegationProfile.ISSUER; private static final String OWNER_PRINCIPAL = "gamesession_coord_app"; private static final BigInteger ONE = BigInteger.ONE; + private static final String EVIDENCE_PREFIX = "game_session_canonical_issuer_admission_"; + private static final List EVIDENCE_TABLES = + List.of("initializer", "initializer_receipt", "cohort_row", "cutoff_target", "operation"); @Container private static final PostgreSQLContainer POSTGRES = @@ -759,9 +765,10 @@ void cutoffRefusesChangedOrMissingFrozenEvidence(String corruption) { FixtureState state = fixtureState(); state.owner().initializeAndRead(state.fixture().originalOperationId()); UUID cutoffOperationId = UUID.randomUUID(); - state.repository().beginCutoff(cutoffOperationId, UUID.randomUUID()); + var pending = state.repository().beginCutoff(cutoffOperationId, UUID.randomUUID()); var target = state.repository().readPreparedCutoffTargets(cutoffOperationId).getFirst(); - // Controlled corruption of retained SQL evidence; no trigger or runtime guard is bypassed. + // Controlled corruption is confined to a rollback-only SQL transaction. The public owners + // reject ambient transactions, so exercise their shared frozen-evidence verifier directly. String mutation = switch (corruption) { case "SOURCE_BYTES" -> @@ -776,18 +783,79 @@ void cutoffRefusesChangedOrMissingFrozenEvidence(String corruption) { + " SET target_source_digest = 'sha256:' || repeat('0', 64) WHERE operation_id = ?"; default -> throw new IllegalArgumentException(corruption); }; - assertThat(state.fixture().dsl().execute(mutation, cutoffOperationId)).isPositive(); + var dsl = state.fixture().dsl(); + var before = retainedEvidenceImage(dsl); + String family = + corruption.endsWith("SOURCE") || "SOURCE_BYTES".equals(corruption) + ? "cohort_row" + : "cutoff_target"; + String trigger = + "cohort_row".equals(family) + ? "gs_issuer_admission_cohort_guard" + : "gs_issuer_admission_cutoff_target_guard"; + RuntimeException rollback = new IllegalStateException("Controlled corruption rollback"); assertThatThrownBy( () -> - state - .repository() - .readPreparedCutoffTarget( - cutoffOperationId, - target.closedValue().tenantId(), - target.closedValue().playableStateNamespaceId())) - .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class); + dsl.transaction( + configuration -> { + var transaction = DSL.using(configuration); + transaction.execute( + "ALTER TABLE " + + EVIDENCE_PREFIX + + family + + " DISABLE TRIGGER " + + trigger); + assertThat(transaction.execute(mutation, cutoffOperationId)).isPositive(); + String expectedMessage = + switch (corruption) { + case "SOURCE_BYTES" -> + "cohort source digest differs from its stored JSON"; + case "MISSING_SOURCE" -> + "cohort no longer matches its frozen complete digest"; + case "MISSING_TARGET" -> + "target set differs from its complete frozen cohort"; + case "TARGET_DIGEST" -> + "target differs from its immutable captured source"; + default -> throw new IllegalArgumentException(corruption); + }; + assertThatThrownBy( + () -> + new CanonicalGameplayIssuerAdmissionControlRepository(transaction) + .verifyCurrentCutoffTarget( + transaction, + pending, + target.closedValue().tenantId(), + target.closedValue().playableStateNamespaceId(), + target.closedValue().exactBytes())) + .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) + .hasMessageContaining(expectedMessage); + throw rollback; + })) + .isSameAs(rollback); + assertThat(retainedEvidenceImage(dsl)).isEqualTo(before); + assertThat( + state + .repository() + .readPreparedCutoffTarget( + cutoffOperationId, + target.closedValue().tenantId(), + target.closedValue().playableStateNamespaceId()) + .closedValue() + .exactBytes()) + .containsExactly(target.closedValue().exactBytes()); assertThatThrownBy(() -> state.repository().completeCutoff(cutoffOperationId)) - .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class); + .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) + .hasMessageContaining("Every frozen issuer tenant target must read back CLOSED"); + assertThatThrownBy(() -> dsl.execute(mutation, cutoffOperationId)) + .hasMessageContaining("Retained issuer admission"); + state + .owner() + .closeAndRead( + cutoffOperationId, + target.closedValue().tenantId(), + target.closedValue().playableStateNamespaceId()); + assertThat(state.repository().completeCutoff(cutoffOperationId).state()) + .isEqualTo(CanonicalGameplayIssuerAdmissionControlValue.State.INSTALLED); } @Test @@ -853,6 +921,215 @@ void reusesFrozenTargetInitializerAcrossOperationsRevisionProgressAndOriginAbort assertThat(administratorCommands.exists(bytes(prepared.key()))).isZero(); } + @Test + void preparedInitializerWithAbortedOriginBlocksAnotherAccountInTheSameTenantNamespace() { + FixtureState state = fixtureState(); + UUID originalOperationId = state.fixture().originalOperationId(); + var original = state.repository().readPreparedInitializer(originalOperationId); + var frozenBeforeAbort = retainedEvidenceImage(state.fixture().dsl()); + assertThat(initializationState(state, originalOperationId)).isEqualTo("PREPARED"); + assertThat(administratorCommands.exists(bytes(original.key()))).isZero(); + assertThat(state.fixture().recordOriginalAccountAbort().isAccountAborted()).isTrue(); + + UUID anotherAccountId = UUID.randomUUID(); + assertThat(anotherAccountId).isNotEqualTo(state.candidate().accountId()); + var anotherOperation = + prepareCurrentOperation(state, "aborted-unclaimed-origin", anotherAccountId); + var retained = state.repository().readPreparedInitializer(anotherOperation.operationId()); + assertThat(retained.value().initializer().operationId()).isEqualTo(originalOperationId); + assertThat(retained.value().exactBytes()).containsExactly(original.value().exactBytes()); + assertThat(retained.value().tenantId()).isEqualTo(state.candidate().tenantId()); + assertThat(retained.value().playableStateNamespaceId()) + .isEqualTo(state.candidate().playableStateNamespaceId()); + assertThat(state.repository().claimFirstCreatePermit(retained)).isFalse(); + assertThatThrownBy(() -> state.owner().initializeAndRead(anotherOperation.operationId())) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy(() -> state.owner().initializeAndRead(originalOperationId)) + .isInstanceOf(IllegalStateException.class); + assertThat(initializationState(state, originalOperationId)).isEqualTo("PREPARED"); + assertThat(countReceipt(state, originalOperationId)).isZero(); + assertThat(administratorCommands.exists(bytes(original.key()))).isZero(); + assertThat(retainedEvidenceImage(state.fixture().dsl())).isEqualTo(frozenBeforeAbort); + } + + @Test + void forwardRetentionGuardsPreservePopulatedV1047EvidenceAndCompleteFlywayHistory() { + FixtureState state = fixtureState(MigrationVersion.fromVersion("1047")); + UUID operationId = state.fixture().originalOperationId(); + state.owner().initializeAndRead(operationId); + UUID cutoffOperationId = UUID.randomUUID(); + UUID cutoffRequestId = UUID.randomUUID(); + var pending = state.repository().beginCutoff(cutoffOperationId, cutoffRequestId); + var before = retainedEvidenceImage(state.fixture().dsl()); + before.values().forEach(rows -> assertThat(rows).isNotEmpty()); + var historyBefore = state.fixture().migrationHistoryImage(); + assertThat( + state + .fixture() + .dsl() + .fetchSingle( + "SELECT version FROM flyway_schema_history ORDER BY installed_rank DESC LIMIT 1") + .get(0, String.class)) + .isEqualTo("1047"); + + assertThat( + state + .fixture() + .upgradeWithDefaultGameSessionMigrations(MigrationVersion.fromVersion("1047.1"))) + .isEqualTo(1); + assertThat(retainedEvidenceImage(state.fixture().dsl())).isEqualTo(before); + var historyAfter = state.fixture().migrationHistoryImage(); + assertThat(historyAfter).hasSize(historyBefore.size() + 1); + assertThat(historyAfter.subList(0, historyBefore.size())) + .containsExactlyElementsOf(historyBefore); + assertThat( + state + .fixture() + .dsl() + .fetchSingle("SELECT script FROM flyway_schema_history WHERE version = '1047.1'") + .get(0, String.class)) + .isEqualTo("V1047.1__issuer_admission_retained_evidence_guards.sql"); + assertThat( + state + .fixture() + .upgradeWithDefaultGameSessionMigrations(MigrationVersion.fromVersion("1047.1"))) + .isZero(); + assertThat(retainedEvidenceImage(state.fixture().dsl())).isEqualTo(before); + assertThat(state.fixture().migrationHistoryImage()).containsExactlyElementsOf(historyAfter); + + assertThat(state.repository().beginCutoff(cutoffOperationId, cutoffRequestId).exactBytes()) + .containsExactly(pending.exactBytes()); + var target = state.repository().readPreparedCutoffTargets(cutoffOperationId).getFirst(); + var closed = + state + .owner() + .closeAndRead( + cutoffOperationId, + target.closedValue().tenantId(), + target.closedValue().playableStateNamespaceId()); + assertThat(closed.scriptOutcome()).isEqualTo(3L); + assertThat( + state + .owner() + .closeAndRead( + cutoffOperationId, + target.closedValue().tenantId(), + target.closedValue().playableStateNamespaceId()) + .scriptOutcome()) + .isEqualTo(2L); + var installed = state.repository().completeCutoff(cutoffOperationId); + assertThat(installed.state()) + .isEqualTo(CanonicalGameplayIssuerAdmissionControlValue.State.INSTALLED); + assertThat(state.repository().completeCutoff(cutoffOperationId).exactBytes()) + .containsExactly(installed.exactBytes()); + assertThat(countReceipt(state, operationId)).isEqualTo(1L); + } + + @ParameterizedTest + @ValueSource( + strings = {"initializer", "initializer_receipt", "cohort_row", "cutoff_target", "operation"}) + void retainedEvidenceRejectsDirectUpdateDeleteAndTruncate(String family) { + FixtureState state = fixtureState(); + state.owner().initializeAndRead(state.fixture().originalOperationId()); + state.repository().beginCutoff(UUID.randomUUID(), UUID.randomUUID()); + var dsl = state.fixture().dsl(); + String table = EVIDENCE_PREFIX + family; + String update = + switch (family) { + case "initializer" -> "initialization_state = 'PREPARED'"; + case "initializer_receipt" -> "script_outcome = script_outcome"; + case "cohort_row" -> "source_row_json = source_row_json || ' '"; + case "cutoff_target" -> "target_source_digest = 'sha256:' || repeat('0', 64)"; + case "operation" -> "operation_state = operation_state"; + default -> throw new IllegalArgumentException(family); + }; + var before = retainedEvidenceImage(dsl); + assertThatThrownBy(() -> dsl.execute("UPDATE " + table + " SET " + update)) + .hasMessageContaining("Retained issuer admission"); + assertThatThrownBy(() -> dsl.execute("DELETE FROM " + table)) + .hasMessageContaining("Retained issuer admission"); + assertThatThrownBy(() -> dsl.execute("TRUNCATE TABLE " + table + " CASCADE")) + .hasMessageContaining("Retained issuer admission"); + assertThat(retainedEvidenceImage(dsl)).isEqualTo(before); + } + + @ParameterizedTest + @ValueSource( + strings = { + "INITIALIZER_SKIP", + "INITIALIZER_ID", + "INITIALIZER_PAYLOAD", + "INITIALIZER_REARM", + "TARGET_ID", + "TARGET_PAYLOAD", + "TARGET_PARTIAL", + "TARGET_READBACK", + "TARGET_REWRITE", + "OPERATION_SOURCE", + "OPERATION_REOPEN" + }) + void retainedEvidenceRejectsIllegalTransitionsIdentityAndPayloadChanges(String change) { + FixtureState state = fixtureState(); + UUID operationId = state.fixture().originalOperationId(); + var prepared = state.repository().readPreparedInitializer(operationId); + if ("INITIALIZER_REARM".equals(change)) { + assertThat(state.repository().claimFirstCreatePermit(prepared)).isTrue(); + } + UUID cutoffOperationId = UUID.randomUUID(); + state.repository().beginCutoff(cutoffOperationId, UUID.randomUUID()); + if ("TARGET_REWRITE".equals(change)) { + var target = state.repository().readPreparedCutoffTargets(cutoffOperationId).getFirst(); + state + .owner() + .closeAndRead( + cutoffOperationId, + target.closedValue().tenantId(), + target.closedValue().playableStateNamespaceId()); + } + var dsl = state.fixture().dsl(); + String mutation = + switch (change) { + case "INITIALIZER_SKIP" -> "initializer SET initialization_state = 'OPEN_CONFIRMED'"; + case "INITIALIZER_ID" -> + "initializer SET operation_id = '11111111-1111-4111-8111-111111111111'"; + case "INITIALIZER_PAYLOAD" -> + "initializer SET open_payload_bytes = convert_to('changed', 'UTF8')"; + case "INITIALIZER_REARM" -> "initializer SET initialization_state = 'PREPARED'"; + case "TARGET_ID" -> "cutoff_target SET target_ordinal = target_ordinal + 1"; + case "TARGET_PAYLOAD" -> + "cutoff_target SET closed_payload_bytes = convert_to('changed', 'UTF8')"; + case "TARGET_PARTIAL" -> "cutoff_target SET target_state = 'CLOSED'"; + case "TARGET_READBACK" -> + "cutoff_target SET target_state = 'CLOSED', script_outcome = 1," + + " exact_closed_readback_bytes = convert_to('changed', 'UTF8')," + + " exact_closed_readback_digest = closed_payload_digest"; + case "TARGET_REWRITE" -> "cutoff_target SET script_outcome = 2"; + case "OPERATION_SOURCE" -> "operation SET cohort_digest = 'sha256:' || repeat('0', 64)"; + case "OPERATION_REOPEN" -> + "operation SET operation_state = 'OPEN' WHERE operation_kind = 'CUTOFF'"; + default -> throw new IllegalArgumentException(change); + }; + var before = retainedEvidenceImage(dsl); + assertThatThrownBy(() -> dsl.execute("UPDATE " + EVIDENCE_PREFIX + mutation)) + .hasMessageContaining("Retained issuer admission"); + assertThat(retainedEvidenceImage(dsl)).isEqualTo(before); + } + + private static Map> retainedEvidenceImage(DSLContext dsl) { + Map> snapshots = new LinkedHashMap<>(); + for (String family : EVIDENCE_TABLES) { + snapshots.put( + family, + dsl.fetch( + "SELECT to_jsonb(evidence)::text || ':' || xmin::text AS image FROM " + + EVIDENCE_PREFIX + + family + + " evidence ORDER BY to_jsonb(evidence)::text") + .getValues("image", String.class)); + } + return snapshots; + } + @Test void callerOwnedJooqTransactionRefusesBeforeSourceOrRemoteDispatch() { FixtureState state = fixtureState(); @@ -900,6 +1177,10 @@ void callerOwnedJooqTransactionRefusesBeforeSourceOrRemoteDispatch() { } private FixtureState fixtureState() { + return fixtureState(null); + } + + private FixtureState fixtureState(MigrationVersion migrationTarget) { Candidate candidate = candidate(); DriverManagerDataSource accountDataSource = new DriverManagerDataSource(); accountDataSource.setDriverClassName("org.postgresql.Driver"); @@ -910,7 +1191,7 @@ private FixtureState fixtureState() { accountDataSource.setPassword(POSTGRES.getPassword()); fixture = new CanonicalGameplayAdmissionAbortCompositionFixture( - accountDataSource, candidate, ownerClient); + accountDataSource, candidate, ownerClient, 0, migrationTarget); Candidate actualCandidate = fixture.candidate(); CanonicalGameplayBindingIdentity identity = identity(actualCandidate); fixture.publish(controlledLeaseEvidence(identity, fixture.generation(), fixture.target())); From 2c4c63742bd2a194f77981769c76fb2b610c7422 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 29 Oct 2026 08:41:41 +1300 Subject: [PATCH 20/26] Harden one-shot admission preflight and live epoch guards --- .../architecture/system-architecture-redis.md | 2 +- .../player-access-and-session.md | 2 + ...meplayAccountInitialBarrierRedisOwner.java | 56 ++-- ...eplayIssuerAdmissionBarrierRedisOwner.java | 20 +- ...lGameplayProtectedIncarnationReceiver.java | 2 +- ...InitialBarrierRedisScriptContribution.java | 30 +- ...ionBarrierRedisScriptDescriptorLoader.java | 43 +++ ...missionBarrierRedisScriptContribution.java | 40 +-- ...__issuer_admission_live_control_guards.sql | 118 +++++++ ...ssionBarrierRepositoryIntegrationTest.java | 308 ++++++++++++++++++ ...nationReceiverPostgresIntegrationTest.java | 96 ++++++ ...ationJournalRepositoryIntegrationTest.java | 8 +- ...ayAccountInitialBarrierRedisOwnerTest.java | 41 ++- 13 files changed, 663 insertions(+), 103 deletions(-) create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayAdmissionBarrierRedisScriptDescriptorLoader.java create mode 100644 services/game-session-service/src/main/resources/db/migration/V1047.2__issuer_admission_live_control_guards.sql diff --git a/design/architecture/system-architecture-redis.md b/design/architecture/system-architecture-redis.md index 7386bb265e..6d491d275f 100644 --- a/design/architecture/system-architecture-redis.md +++ b/design/architecture/system-architecture-redis.md @@ -475,7 +475,7 @@ A pending initial candidate whose inventory snapshot became stale may be superse Within the existing Game Session issuer inventory owner, initial tenant-local issuer barriers use a distinct typed live admission-control row. The immutable bootstrap intent, control row and installed anchor retain their original layout provenance; the live barrier epoch is independently owner-allocated and never interpreted as the bootstrap epoch. Installation requires the qualified anchor, exact current Account source, registered target and stable storage incarnation. Every ordinary preparation, pending initializer, issuer acknowledgement, barrier read and final consumer joins current live control in the same inventory, layout-control and admission-control lock order. Under that current authority, the owner persists one immutable initializer and its complete intended `OPEN` tuple before Redis work. Neither a missing key, an installed anchor alone nor Account's `NO_ACTIVE_ACCOUNT_WIDE_FLOW` state authorizes initialization. Pending initializers participate in the same serialized issuer intent/cutoff cohort as binding preparations: a concurrent intent blocks new initializers, captures every existing initializer, installs the required tenant-local cutoff barriers, and reaches declared `INSTALLED` only after its complete cohort qualifies. The initial one-key tenant-slot CAS refuses conflicting, residual, previously `CLOSED`, newer-epoch or reset state; it never reopens or overwrites a cutoff. Exact independent readback and a durable original-initializer receipt precede use, with current control, epoch, source and incarnation revalidated after the remote phase and again for an admitting issuer acknowledgement and final tenant-local CAS. No SQL transaction spans Redis. Lost replies and partial attempts retain the original initializer and stay non-admitting on uncertainty; they create no reset, recovery or activation authority. -Implementation limitation: the current unregistered issuer initializer cannot recover when its original NEW aborts before its first-create claim. The tenant/namespace remains non-admitting for that live epoch; the [implementation tracker](../project-management/implementation-tracking/player-access-and-session.md#canonical-new-admission-components) records the retained evidence and missing recovery proof. +See the [implementation tracker](../project-management/implementation-tracking/player-access-and-session.md#canonical-new-admission-components) for current coverage, retained evidence and recovery proof gaps. ### Recovery and Cutoff Scope 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 a16f675805..00f32cc43b 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -14,6 +14,8 @@ The receiving #3320 prerequisite contains unregistered issuer LIVE control, tena The issuer INITIAL arm has a tenant/namespace-wide liveness limit: if its frozen originating NEW becomes `ABORTED` while the initializer remains `PREPARED`, later eligible NEW attempts at that live epoch retain the same initializer but cannot claim creation. An absent tenant-slot key stays absent, leaving every affected account non-admitting. No creator transfer, initializer replacement, automatic rearming or OPEN restoration through cutoff is supplied. Preserve the original evidence and keep the scope fenced; a qualified recovery mechanism and its proof remain missing. R907 freshly passes all 37 issuer-admission native cases with zero skips, including the distinct-account aborted-origin refusal, populated V1047→V1047.1 upgrade preserving all original evidence bytes, row versions and prior Flyway history, direct update/delete/truncate refusal for all five retained families, legal completion/retry and rollback-only corruption checks. Frontier, jOOQ generation, affected integration static analysis, formatting and documentation checks pass. Forward V1047.1 enforces retained-evidence guards without replacing the missing recovery mechanism or granting runtime authority. +The next receiving correction adds forward [V1047.2](../../../services/game-session-service/src/main/resources/db/migration/V1047.2__issuer_admission_live_control_guards.sql) live counter/control guards: immutable provenance, original forward transitions, retention and deferred commit-time epoch coherence, preserving initial zero-without-control and same-epoch cutoff completion. Both INITIAL Redis owners now verify the principal and script on one connection before committing their one-shot SQL claim, then issue EVAL on that same connection; a lost SQL claim reply remains uncertain and never rearms creation. INITIAL observations leave the inapplicable account-fence cohort digest absent. R914 freshly passes all 79 selected cases (11 units and 68 PostgreSQL/Redis cases), including populated upgrade/history/row-version retention, incompatible upgrade and counter-only commit refusal, valid owner transitions, preflight failure followed by valid retry, lost-claim refusal and journal retention. Migration frontier, jOOQ generation, affected Checkstyle, formatting and documentation checks pass. R912 retains its two test-setup failures; R913 was stopped before executing tests, and neither is reported as successful. These are focused manually composed component results with controlled source and PKI inputs; the recovery, custody, registration and activation limits above remain. + The current local correction adds explicit recovery for a stale, uninstalled initial issuer-bootstrap candidate. Forward V1038.3 retains its original intent, cohort and issued work, captures the new actual inventory cut under monotonic fences, and atomically binds immutable supersession lineage to current control. A strictly newer trusted layout separates old physical work; installed anchors remain ineligible. Account CI selection and migration task inputs now cover its Game Session owner-composition dependency, and the native registration-image and lost-reply proofs use their actual SQL/Lua contracts. R827 passes 31 of 32 focused cases; its remaining failure is a test assertion against the transaction wrapper rather than the nested PostgreSQL refusal. R828 then passes that complete recovery case with affected integration static and formatting checks. Together they qualify 32 distinct current-source cases, including two actual Account abort compositions; frontier, jOOQ, affected static, formatting and documentation checks pass. The new recovery sequence uses controlled Account terminal input through the actual Game Session abort owner, separately from those two authenticated Account compositions. This is focused proof, not a full service-suite, live layout rotation, retained-key cleanup or production-authority claim. The local issuer owners now reject plans that exceed the executable 256-member-operation bound per partition, including retained `RELEASED` lineage independently of logical active capacity. A blocked plan retains its complete cohort and planned work; physical preparation refuses before allocating operation rows. Fresh ordinary NEW registration also checks the same nonretired local-operation set under the inventory lock before allocating new identities or rows, while exact retries retain their original operation at the bound. Both bootstrap owners use one strict Account issuer source-event verifier. R791 freshly passes the four PostgreSQL boundary cases: 256 allowed, both 257-reservation overflow forms blocked, and ordinary registration refusal/retry with unchanged durable state. R793 then freshly passes all 26 selected PostgreSQL cases across the plan, ordinary-operation and intent owners, plus affected production/integration static analysis, formatting and documentation checks. This is focused owner proof, not a complete service-suite or public admission result. Default registration, external source custody and admission limits remain unchanged. diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierRedisOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierRedisOwner.java index ddcc448e3b..4eb5ea395f 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierRedisOwner.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierRedisOwner.java @@ -119,9 +119,19 @@ CanonicalGameplayAccountInitialOpenProof initializeOnce( incarnationReceiver.observeForInitialAccountBarrier(snapshot.originalRequestId()); requireObservation(snapshot, before); PreparedWrite prepared = prepareWrite(snapshot, assignment, before); - repository.recordDispatchPossible(snapshot.originalRequestId(), before); - // The state transition above is durable before this one and only possible remote attempt. - tryCreateOnce(prepared); + requireNoAmbientTransaction(); + try (StatefulRedisConnection connection = + redisClient.connect(ByteArrayCodec.INSTANCE)) { + RedisAsyncCommands commands = requireCommands(connection); + requirePrincipal(await(commands.aclWhoami())); + byte[] script = ascii(prepared.script()); + String sha = await(commands.scriptLoad(script)); + if (!digest("SHA-1", script).equals(sha)) throw unavailable(); + repository.recordDispatchPossible(snapshot.originalRequestId(), before); + // The claim commits before EVAL on this same preflighted connection. A lost SQL + // commit reply is still uncertain and must never authorize another create attempt. + tryCreateOnce(prepared, commands, sha); + } } catch (RuntimeException possibleDispatchOrSourceFailure) { // Never create a replacement initializer or repeat a possibly dispatched write. A positive // exact readback can still finish the original receipt; absence remains explicit uncertainty. @@ -274,16 +284,19 @@ private PreparedWrite prepareWrite( return new PreparedWrite(asciiString(script), key, arguments); } - private void tryCreateOnce(PreparedWrite prepared) { + private void tryCreateOnce( + PreparedWrite prepared, RedisAsyncCommands commands, String sha) { requireNoAmbientTransaction(); - long outcome = - writeOneKey( - ascii(prepared.script()), - prepared.key(), - prepared.arguments().stream() - .map(CanonicalGameplayAccountInitialBarrierRedisOwner::ascii) - .toArray(byte[][]::new)); - if (outcome < 0 || outcome > 1) throw unavailable(); + Long outcome = + await( + commands.evalsha( + sha, + ScriptOutputType.INTEGER, + new byte[][] {ascii(prepared.key())}, + prepared.arguments().stream() + .map(CanonicalGameplayAccountInitialBarrierRedisOwner::ascii) + .toArray(byte[][]::new))); + if (outcome == null || outcome < 0 || outcome > 1) throw unavailable(); } private record PreparedWrite(String script, String key, List arguments) {} @@ -357,25 +370,6 @@ private Map readExactPhysicalState( } } - private long writeOneKey(byte[] script, String key, byte[]... arguments) { - requireNoAmbientTransaction(); - try (StatefulRedisConnection connection = - redisClient.connect(ByteArrayCodec.INSTANCE)) { - RedisAsyncCommands commands = requireCommands(connection); - requirePrincipal(await(commands.aclWhoami())); - String sha = await(commands.scriptLoad(script)); - if (!digest("SHA-1", script).equals(sha)) throw unavailable(); - Long reply = - await( - commands.evalsha( - sha, ScriptOutputType.INTEGER, new byte[][] {ascii(key)}, arguments)); - if (reply == null) throw unavailable(); - return reply; - } catch (RuntimeException failure) { - throw unavailable(failure); - } - } - private RedisScriptDescriptor requireDescriptor() { String scriptId = CanonicalGameplayAccountInitialBarrierRedisScriptContribution.SCRIPT_ID; String resourcePath = diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRedisOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRedisOwner.java index 4ba9708a74..048235e95f 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRedisOwner.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRedisOwner.java @@ -98,8 +98,24 @@ Readback initializeAndRead(UUID operationId) { ascii("REPLAY_ONLY") }; byte[] createOnce = ascii("CREATE_ONCE"); - if (repository.claimFirstCreatePermit(prepared)) arguments[10] = createOnce; - long result = writeOneKey(script, key, arguments); + long result; + requireNoAmbientTransaction(); + try (StatefulRedisConnection connection = + redisClient.connect(ByteArrayCodec.INSTANCE)) { + RedisAsyncCommands commands = requireCommands(connection); + requirePrincipal(await(commands.aclWhoami())); + String sha = await(commands.scriptLoad(script)); + if (!digest("SHA-1", script).equals(sha)) throw unavailable(); + requireNoAmbientTransaction(); + if (repository.claimFirstCreatePermit(prepared)) arguments[10] = createOnce; + // The claim commits before EVAL on this same preflighted connection. A lost SQL + // commit reply remains uncertain; later attempts retain replay-only behavior. + requireNoAmbientTransaction(); + Long reply = + await(commands.evalsha(sha, ScriptOutputType.INTEGER, new byte[][] {key}, arguments)); + if (reply == null) throw unavailable(); + result = reply; + } if (result < 1 || result > 2) throw unavailable(); byte[] observed = readExactPhysicalState(prepared.key(), value); requireCurrentState(value.initializer()); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayProtectedIncarnationReceiver.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayProtectedIncarnationReceiver.java index 7c99ac70b7..8f590f928d 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayProtectedIncarnationReceiver.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayProtectedIncarnationReceiver.java @@ -375,7 +375,7 @@ private CurrentContext loadInitialCurrentContext(UUID originalRequestId) { null, null, context.inventorySnapshotRevision().toString(), - context.sourceControlDigest(), + null, context.targetDigest(), 0L, context.tenantId(), diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayAccountInitialBarrierRedisScriptContribution.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayAccountInitialBarrierRedisScriptContribution.java index bad4527a8b..d815d68614 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayAccountInitialBarrierRedisScriptContribution.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayAccountInitialBarrierRedisScriptContribution.java @@ -1,14 +1,9 @@ package net.firedevops.firemud.gamesession.service; -import java.io.IOException; -import java.io.InputStream; import java.util.Collection; import java.util.List; import net.firedevops.firemud.common.redis.contracts.RedisScriptContribution; import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor; -import tools.jackson.core.StreamReadFeature; -import tools.jackson.databind.DeserializationFeature; -import tools.jackson.databind.json.JsonMapper; /** Passive descriptor for the one-key create-only INITIAL OPEN barrier script. */ public final class CanonicalGameplayAccountInitialBarrierRedisScriptContribution @@ -18,12 +13,6 @@ public final class CanonicalGameplayAccountInitialBarrierRedisScriptContribution "redis/lua/game-session-account-admission-barrier-initial-open.lua"; private static final String DESCRIPTOR_PATH = "/redis/scripts/game-session-account-admission-barrier-initial-open.json"; - private static final JsonMapper JSON = - JsonMapper.builder() - .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) - .enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) - .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) - .build(); @Override public String ownerId() { @@ -32,21 +21,8 @@ public String ownerId() { @Override public Collection descriptors() { - try (InputStream input = getClass().getResourceAsStream(DESCRIPTOR_PATH)) { - if (input == null) throw unavailable(); - byte[] bytes = input.readNBytes(16 * 1024 + 1); - if (bytes.length == 0 || bytes.length > 16 * 1024) throw unavailable(); - RedisScriptDescriptor descriptor = JSON.readValue(bytes, RedisScriptDescriptor.class); - if (!ownerId().equals(descriptor.owner()) || !SCRIPT_ID.equals(descriptor.scriptId())) { - throw unavailable(); - } - return List.of(descriptor); - } catch (IOException | RuntimeException failure) { - throw unavailable(); - } - } - - private static IllegalStateException unavailable() { - return new IllegalStateException("INITIAL account barrier descriptor is unavailable"); + return List.of( + CanonicalGameplayAdmissionBarrierRedisScriptDescriptorLoader.read( + DESCRIPTOR_PATH, SCRIPT_ID, "INITIAL account barrier descriptor is unavailable")); } } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayAdmissionBarrierRedisScriptDescriptorLoader.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayAdmissionBarrierRedisScriptDescriptorLoader.java new file mode 100644 index 0000000000..553286411b --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayAdmissionBarrierRedisScriptDescriptorLoader.java @@ -0,0 +1,43 @@ +package net.firedevops.firemud.gamesession.service; + +import java.io.IOException; +import java.io.InputStream; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.json.JsonMapper; + +/** + * Bounded strict descriptor reader for the manual Account INITIAL and issuer admission barriers. + */ +final class CanonicalGameplayAdmissionBarrierRedisScriptDescriptorLoader { + private static final int MAX_DESCRIPTOR_BYTES = 16 * 1024; + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + private CanonicalGameplayAdmissionBarrierRedisScriptDescriptorLoader() {} + + static RedisScriptDescriptor read(String path, String scriptId, String unavailableMessage) { + try (InputStream input = + CanonicalGameplayAdmissionBarrierRedisScriptDescriptorLoader.class.getResourceAsStream( + path)) { + if (input == null) throw new IllegalStateException(unavailableMessage); + byte[] bytes = input.readNBytes(MAX_DESCRIPTOR_BYTES + 1); + if (bytes.length == 0 || bytes.length > MAX_DESCRIPTOR_BYTES) { + throw new IllegalStateException(unavailableMessage); + } + RedisScriptDescriptor descriptor = JSON.readValue(bytes, RedisScriptDescriptor.class); + if (!"game-session-service".equals(descriptor.owner()) + || !scriptId.equals(descriptor.scriptId())) { + throw new IllegalStateException(unavailableMessage); + } + return descriptor; + } catch (IOException | RuntimeException failure) { + throw new IllegalStateException(unavailableMessage); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayIssuerAdmissionBarrierRedisScriptContribution.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayIssuerAdmissionBarrierRedisScriptContribution.java index d8e1bb24cf..ec40a8c006 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayIssuerAdmissionBarrierRedisScriptContribution.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayIssuerAdmissionBarrierRedisScriptContribution.java @@ -1,14 +1,9 @@ package net.firedevops.firemud.gamesession.service; -import java.io.IOException; -import java.io.InputStream; import java.util.Collection; import java.util.List; import net.firedevops.firemud.common.redis.contracts.RedisScriptContribution; import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor; -import tools.jackson.core.StreamReadFeature; -import tools.jackson.databind.DeserializationFeature; -import tools.jackson.databind.json.JsonMapper; /** Passive manual descriptor contribution for one-key issuer tenant barrier scripts. */ public final class CanonicalGameplayIssuerAdmissionBarrierRedisScriptContribution @@ -23,12 +18,6 @@ public final class CanonicalGameplayIssuerAdmissionBarrierRedisScriptContributio "/redis/scripts/game-session-issuer-admission-barrier-open.json"; private static final String CLOSE_DESCRIPTOR_PATH = "/redis/scripts/game-session-issuer-admission-barrier-close.json"; - private static final JsonMapper JSON = - JsonMapper.builder() - .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) - .enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) - .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) - .build(); @Override public String ownerId() { @@ -38,26 +27,13 @@ public String ownerId() { @Override public Collection descriptors() { return List.of( - readDescriptor(OPEN_DESCRIPTOR_PATH, OPEN_SCRIPT_ID), - readDescriptor(CLOSE_DESCRIPTOR_PATH, CLOSE_SCRIPT_ID)); - } - - private RedisScriptDescriptor readDescriptor(String path, String scriptId) { - try (InputStream input = getClass().getResourceAsStream(path)) { - if (input == null) throw unavailable(); - byte[] bytes = input.readNBytes(16 * 1024 + 1); - if (bytes.length == 0 || bytes.length > 16 * 1024) throw unavailable(); - var descriptor = JSON.readValue(bytes, RedisScriptDescriptor.class); - if (!ownerId().equals(descriptor.owner()) || !scriptId.equals(descriptor.scriptId())) { - throw unavailable(); - } - return descriptor; - } catch (IOException | RuntimeException failure) { - throw unavailable(); - } - } - - private static IllegalStateException unavailable() { - return new IllegalStateException("Issuer admission barrier descriptors are unavailable"); + CanonicalGameplayAdmissionBarrierRedisScriptDescriptorLoader.read( + OPEN_DESCRIPTOR_PATH, + OPEN_SCRIPT_ID, + "Issuer admission barrier descriptors are unavailable"), + CanonicalGameplayAdmissionBarrierRedisScriptDescriptorLoader.read( + CLOSE_DESCRIPTOR_PATH, + CLOSE_SCRIPT_ID, + "Issuer admission barrier descriptors are unavailable")); } } diff --git a/services/game-session-service/src/main/resources/db/migration/V1047.2__issuer_admission_live_control_guards.sql b/services/game-session-service/src/main/resources/db/migration/V1047.2__issuer_admission_live_control_guards.sql new file mode 100644 index 0000000000..243b36664e --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V1047.2__issuer_admission_live_control_guards.sql @@ -0,0 +1,118 @@ +-- Live issuer admission authority has its own retained epoch domain. These guards constrain +-- existing owner updates; initial insertion does not gain any new activation authority. +-- [jooq ignore start] +-- A never-installed issuer starts at zero without a control row. Every allocated live epoch +-- otherwise has its matching control in the same committed transaction. Reject incompatible +-- retained data rather than manufacturing or resetting current authority during this upgrade. +DO $$ +BEGIN + IF EXISTS ( + SELECT 1 + FROM game_session_canonical_issuer_admission_epoch_counter counter + FULL JOIN game_session_canonical_issuer_admission_control control USING (issuer_id) + WHERE counter.issuer_id IS NULL + OR (control.issuer_id IS NULL AND counter.last_live_barrier_epoch <> 0) + OR (control.issuer_id IS NOT NULL + AND counter.last_live_barrier_epoch <> control.live_barrier_epoch) + ) THEN + RAISE EXCEPTION 'Live issuer admission epoch counter and control must retain the same current epoch' + USING ERRCODE = '23514'; + END IF; +END; +$$; + +CREATE FUNCTION guard_gs_issuer_admission_current_epoch_pair() RETURNS trigger AS $$ +BEGIN + IF EXISTS ( + SELECT 1 + FROM game_session_canonical_issuer_admission_epoch_counter counter + FULL JOIN game_session_canonical_issuer_admission_control control USING (issuer_id) + WHERE COALESCE(counter.issuer_id, control.issuer_id) = NEW.issuer_id + AND (counter.issuer_id IS NULL + OR (control.issuer_id IS NULL AND counter.last_live_barrier_epoch <> 0) + OR (control.issuer_id IS NOT NULL + AND counter.last_live_barrier_epoch <> control.live_barrier_epoch)) + ) THEN + RAISE EXCEPTION 'Live issuer admission epoch counter and control must retain the same current epoch' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +-- The owner allocates before writing control. Validate the final pair at commit, not the +-- intermediate allocation, and cover inserts as well as updates of either side. +CREATE CONSTRAINT TRIGGER gs_issuer_admission_epoch_counter_current_pair + AFTER INSERT OR UPDATE ON game_session_canonical_issuer_admission_epoch_counter + DEFERRABLE INITIALLY DEFERRED + FOR EACH ROW EXECUTE FUNCTION guard_gs_issuer_admission_current_epoch_pair(); +CREATE CONSTRAINT TRIGGER gs_issuer_admission_live_control_current_pair + AFTER INSERT OR UPDATE ON game_session_canonical_issuer_admission_control + DEFERRABLE INITIALLY DEFERRED + FOR EACH ROW EXECUTE FUNCTION guard_gs_issuer_admission_current_epoch_pair(); + +CREATE FUNCTION guard_gs_issuer_admission_epoch_counter() RETURNS trigger AS $$ +BEGIN + IF TG_OP IN ('DELETE', 'TRUNCATE') THEN + RAISE EXCEPTION 'Live issuer admission epoch counter cannot be removed' + USING ERRCODE = '23514'; + END IF; + -- Both initial installation and cutoff allocate exactly one epoch in the existing owner. + IF (to_jsonb(NEW) - ARRAY['last_live_barrier_epoch', 'updated_at']) + IS DISTINCT FROM (to_jsonb(OLD) - ARRAY['last_live_barrier_epoch', 'updated_at']) + OR NEW.last_live_barrier_epoch <> OLD.last_live_barrier_epoch + 1 THEN + RAISE EXCEPTION 'Live issuer admission epoch counter must advance its original domain by one' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE FUNCTION guard_gs_issuer_admission_live_control() RETURNS trigger AS $$ +BEGIN + IF TG_OP IN ('DELETE', 'TRUNCATE') THEN + RAISE EXCEPTION 'Live issuer admission control cannot be removed' + USING ERRCODE = '23514'; + END IF; + IF OLD.state = 'OPEN' AND NEW.state = 'CUTOFF_PENDING' + AND OLD.current_operation_kind = 'INITIAL_ANCHOR_INSTALL' + AND NEW.current_operation_kind = 'CUTOFF' + AND NEW.current_operation_id IS DISTINCT FROM OLD.current_operation_id + AND NEW.live_barrier_epoch = OLD.live_barrier_epoch + 1 + AND NEW.inventory_snapshot_revision >= OLD.inventory_snapshot_revision + AND (to_jsonb(NEW) - ARRAY['state', 'live_barrier_epoch', 'current_operation_id', + 'current_operation_kind', 'inventory_snapshot_revision', 'cohort_row_count', + 'cohort_digest', 'control_exact_bytes', 'control_exact_digest', 'updated_at']) + IS NOT DISTINCT FROM + (to_jsonb(OLD) - ARRAY['state', 'live_barrier_epoch', 'current_operation_id', + 'current_operation_kind', 'inventory_snapshot_revision', 'cohort_row_count', + 'cohort_digest', 'control_exact_bytes', 'control_exact_digest', 'updated_at']) THEN + RETURN NEW; + END IF; + -- Completion publishes the captured cutoff, retaining its epoch, operation and whole cohort. + IF OLD.state = 'CUTOFF_PENDING' AND NEW.state = 'INSTALLED' + AND OLD.current_operation_kind = 'CUTOFF' + AND (to_jsonb(NEW) - ARRAY['state', 'control_exact_bytes', 'control_exact_digest', 'updated_at']) + IS NOT DISTINCT FROM + (to_jsonb(OLD) - ARRAY['state', 'control_exact_bytes', 'control_exact_digest', 'updated_at']) THEN + RETURN NEW; + END IF; + RAISE EXCEPTION 'Live issuer admission control permits only original forward cutoff transitions' + USING ERRCODE = '23514'; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER gs_issuer_admission_epoch_counter_guard + BEFORE UPDATE OR DELETE ON game_session_canonical_issuer_admission_epoch_counter + FOR EACH ROW EXECUTE FUNCTION guard_gs_issuer_admission_epoch_counter(); +CREATE TRIGGER gs_issuer_admission_epoch_counter_retention + BEFORE TRUNCATE ON game_session_canonical_issuer_admission_epoch_counter + FOR EACH STATEMENT EXECUTE FUNCTION guard_gs_issuer_admission_epoch_counter(); + +CREATE TRIGGER gs_issuer_admission_live_control_guard + BEFORE UPDATE OR DELETE ON game_session_canonical_issuer_admission_control + FOR EACH ROW EXECUTE FUNCTION guard_gs_issuer_admission_live_control(); +CREATE TRIGGER gs_issuer_admission_live_control_retention + BEFORE TRUNCATE ON game_session_canonical_issuer_admission_control + FOR EACH STATEMENT EXECUTE FUNCTION guard_gs_issuer_admission_live_control(); +-- [jooq ignore stop] diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepositoryIntegrationTest.java index be8fda1442..b7adaa6115 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepositoryIntegrationTest.java @@ -2,12 +2,19 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.when; import io.lettuce.core.AclSetuserArgs; import io.lettuce.core.ClientOptions; import io.lettuce.core.RedisClient; import io.lettuce.core.RedisURI; import io.lettuce.core.api.StatefulRedisConnection; +import io.lettuce.core.api.async.RedisAsyncCommands; import io.lettuce.core.api.sync.RedisCommands; import io.lettuce.core.codec.ByteArrayCodec; import io.lettuce.core.protocol.CommandKeyword; @@ -174,6 +181,47 @@ public void requireStillCurrent( assertThat(countReceipt(state, operationId)).isEqualTo(1L); } + @Test + @SuppressWarnings({"unchecked", "rawtypes"}) + void remotePreflightFailuresRetainPreparedInitializerAndAllowOneValidCreate() { + FixtureState state = fixtureState(); + UUID operationId = state.fixture().originalOperationId(); + var prepared = state.repository().readPreparedInitializer(operationId); + RedisClient connectFailure = mock(RedisClient.class); + when(connectFailure.connect(any(ByteArrayCodec.class))) + .thenThrow(new IllegalStateException("controlled connect failure")); + RedisClient loadFailure = mock(RedisClient.class); + try (var loadConnection = ownerClient.connect(ByteArrayCodec.INSTANCE)) { + StatefulRedisConnection connection = spy(loadConnection); + RedisAsyncCommands commands = spy(loadConnection.async()); + doReturn(commands).when(connection).async(); + doThrow(new IllegalStateException("controlled SCRIPT LOAD failure")) + .when(commands) + .scriptLoad(any(byte[].class)); + when(loadFailure.connect(any(ByteArrayCodec.class))).thenReturn(connection); + // The actual administrator connection reports principal 'default', which must be refused. + for (RedisClient failingClient : List.of(connectFailure, administrator, loadFailure)) { + var owner = + new CanonicalGameplayIssuerAdmissionBarrierRedisOwner( + failingClient, + RedisScriptCatalog.fromContributions( + List.of(new CanonicalGameplayIssuerAdmissionBarrierRedisScriptContribution())), + state.repository(), + state.sourceReader()); + assertThatThrownBy(() -> owner.initializeAndRead(operationId)) + .isInstanceOf(IllegalStateException.class); + assertThat(initializationState(state, operationId)).isEqualTo("PREPARED"); + assertThat(countReceipt(state, operationId)).isZero(); + assertThat(administratorCommands.exists(bytes(prepared.key()))).isZero(); + } + org.mockito.Mockito.verify(commands, org.mockito.Mockito.never()) + .evalsha(any(), any(), any(byte[][].class), any(byte[][].class)); + } + assertThat(state.owner().initializeAndRead(operationId).scriptOutcome()).isEqualTo(1L); + assertThat(state.owner().initializeAndRead(operationId).scriptOutcome()).isEqualTo(2L); + assertThat(countReceipt(state, operationId)).isEqualTo(1L); + } + @Test void concurrentClaimsOfRetainedPreparedReadsHaveOnlyOneFirstCreateWinner() throws Exception { FixtureState state = fixtureState(); @@ -1115,6 +1163,266 @@ void retainedEvidenceRejectsIllegalTransitionsIdentityAndPayloadChanges(String c assertThat(retainedEvidenceImage(dsl)).isEqualTo(before); } + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void forwardLiveControlGuardsPreserveV1047_1RowsAndSameEpochCutoffCompletion( + boolean cutoffBeforeUpgrade) { + FixtureState state = fixtureState(MigrationVersion.fromVersion("1047.1")); + var opened = state.owner().initializeAndRead(state.fixture().originalOperationId()); + UUID cutoffOperationId = UUID.randomUUID(); + UUID cutoffRequestId = UUID.randomUUID(); + if (cutoffBeforeUpgrade) { + state.repository().beginCutoff(cutoffOperationId, cutoffRequestId); + } + var dsl = state.fixture().dsl(); + var before = liveControlEvidenceImage(dsl); + var historyBefore = state.fixture().migrationHistoryImage(); + assertThat( + dsl.fetchSingle( + "SELECT version FROM flyway_schema_history ORDER BY installed_rank DESC LIMIT 1") + .get(0, String.class)) + .isEqualTo("1047.1"); + + assertThat( + state + .fixture() + .upgradeWithDefaultGameSessionMigrations(MigrationVersion.fromVersion("1047.2"))) + .isEqualTo(1); + assertThat(liveControlEvidenceImage(dsl)).isEqualTo(before); + var historyAfter = state.fixture().migrationHistoryImage(); + assertThat(historyAfter).hasSize(historyBefore.size() + 1); + assertThat(historyAfter.subList(0, historyBefore.size())) + .containsExactlyElementsOf(historyBefore); + assertThat( + dsl.fetchSingle("SELECT script FROM flyway_schema_history WHERE version = '1047.2'") + .get(0, String.class)) + .isEqualTo("V1047.2__issuer_admission_live_control_guards.sql"); + assertThat( + state + .fixture() + .upgradeWithDefaultGameSessionMigrations(MigrationVersion.fromVersion("1047.2"))) + .isZero(); + assertThat(liveControlEvidenceImage(dsl)).isEqualTo(before); + assertThat(state.fixture().migrationHistoryImage()).containsExactlyElementsOf(historyAfter); + + var pending = state.repository().beginCutoff(cutoffOperationId, cutoffRequestId); + assertThat(pending.liveBarrierEpoch()).isEqualTo(opened.value().admissionEpoch().add(ONE)); + var pendingImage = liveControlEvidenceImage(dsl); + assertThat(state.repository().beginCutoff(cutoffOperationId, cutoffRequestId).exactBytes()) + .containsExactly(pending.exactBytes()); + assertThat(liveControlEvidenceImage(dsl)).isEqualTo(pendingImage); + var target = state.repository().readPreparedCutoffTargets(cutoffOperationId).getFirst(); + state + .owner() + .closeAndRead( + cutoffOperationId, + target.closedValue().tenantId(), + target.closedValue().playableStateNamespaceId()); + String pendingProvenance = + dsl.fetchSingle( + "SELECT (to_jsonb(control) - ARRAY['state', 'control_exact_bytes'," + + " 'control_exact_digest', 'updated_at'])::text FROM " + + EVIDENCE_PREFIX + + "control control") + .get(0, String.class); + var installed = state.repository().completeCutoff(cutoffOperationId); + assertThat(installed.state()) + .isEqualTo(CanonicalGameplayIssuerAdmissionControlValue.State.INSTALLED); + assertThat(installed.liveBarrierEpoch()).isEqualTo(pending.liveBarrierEpoch()); + assertThat(installed.currentOperationId()).isEqualTo(pending.currentOperationId()); + assertThat(installed.cohortDigest()).isEqualTo(pending.cohortDigest()); + assertThat( + dsl.fetchSingle( + "SELECT (to_jsonb(control) - ARRAY['state', 'control_exact_bytes'," + + " 'control_exact_digest', 'updated_at'])::text FROM " + + EVIDENCE_PREFIX + + "control control") + .get(0, String.class)) + .isEqualTo(pendingProvenance); + var installedImage = liveControlEvidenceImage(dsl); + assertThat(installedImage.get("epoch_counter")).isEqualTo(pendingImage.get("epoch_counter")); + assertThat(state.repository().completeCutoff(cutoffOperationId).exactBytes()) + .containsExactly(installed.exactBytes()); + assertThat(liveControlEvidenceImage(dsl)).isEqualTo(installedImage); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void liveIssuerCounterOnlyAdvanceFailsAtCommitAndRetainsOriginalAuthority(boolean cutoffPending) { + FixtureState state = fixtureState(); + state.owner().initializeAndRead(state.fixture().originalOperationId()); + if (cutoffPending) { + state.repository().beginCutoff(UUID.randomUUID(), UUID.randomUUID()); + } + var dsl = state.fixture().dsl(); + var before = liveControlEvidenceImage(dsl); + AtomicBoolean allocationExecuted = new AtomicBoolean(); + assertThatThrownBy( + () -> + dsl.transaction( + configuration -> { + DSLContext transaction = DSL.using(configuration); + assertThat( + transaction.execute( + "UPDATE " + + EVIDENCE_PREFIX + + "epoch_counter" + + " SET last_live_barrier_epoch = last_live_barrier_epoch + 1")) + .isEqualTo(1); + assertThat( + transaction + .fetchSingle( + "SELECT counter.last_live_barrier_epoch - control.live_barrier_epoch FROM " + + EVIDENCE_PREFIX + + "epoch_counter counter JOIN " + + EVIDENCE_PREFIX + + "control control USING (issuer_id)") + .get(0, BigInteger.class)) + .isEqualTo(ONE); + allocationExecuted.set(true); + })) + .hasStackTraceContaining("Live issuer admission epoch counter and control"); + assertThat(allocationExecuted).isTrue(); + assertThat(liveControlEvidenceImage(dsl)).isEqualTo(before); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void liveIssuerGuardUpgradeRejectsIncompatibleRetainedEpochPair(boolean missingControl) { + FixtureState state = fixtureState(MigrationVersion.fromVersion("1047.1")); + var dsl = state.fixture().dsl(); + if (missingControl) { + assertThat(dsl.execute("DELETE FROM " + EVIDENCE_PREFIX + "control")).isEqualTo(1); + } else { + assertThat( + dsl.execute( + "UPDATE " + + EVIDENCE_PREFIX + + "epoch_counter" + + " SET last_live_barrier_epoch = last_live_barrier_epoch + 1")) + .isEqualTo(1); + } + var before = liveControlEvidenceImage(dsl); + var historyBefore = state.fixture().migrationHistoryImage(); + assertThatThrownBy( + () -> + state + .fixture() + .upgradeWithDefaultGameSessionMigrations( + MigrationVersion.fromVersion("1047.2"))) + .hasStackTraceContaining("Live issuer admission epoch counter and control"); + assertThat(liveControlEvidenceImage(dsl)).isEqualTo(before); + assertThat(state.fixture().migrationHistoryImage()).containsExactlyElementsOf(historyBefore); + } + + @ParameterizedTest + @ValueSource(strings = {"epoch_counter", "control"}) + void liveIssuerAuthorityRejectsResetRemovalAndProvenanceRewrites(String family) { + FixtureState state = fixtureState(); + var dsl = state.fixture().dsl(); + String table = EVIDENCE_PREFIX + family; + var before = liveControlEvidenceImage(dsl); + String cutoffTransition = + "state = 'CUTOFF_PENDING', current_operation_kind = 'CUTOFF'," + + " current_operation_id = '11111111-1111-4111-8111-111111111111'," + + " live_barrier_epoch = live_barrier_epoch + 1, "; + List changes = + "epoch_counter".equals(family) + ? List.of( + "last_live_barrier_epoch = last_live_barrier_epoch - 1", + "last_live_barrier_epoch = 0", + "last_live_barrier_epoch = last_live_barrier_epoch", + "last_live_barrier_epoch = last_live_barrier_epoch + 2", + "issuer_id = 'changed-issuer', last_live_barrier_epoch = last_live_barrier_epoch + 1") + : List.of( + "live_barrier_epoch = live_barrier_epoch - 1", + "live_barrier_epoch = 0", + "live_barrier_epoch = live_barrier_epoch", + "state = 'INSTALLED', current_operation_kind = 'CUTOFF'", + "state = 'CUTOFF_PENDING', current_operation_kind = 'CUTOFF'," + + " current_operation_id = '11111111-1111-4111-8111-111111111111'", + "state = 'CUTOFF_PENDING', current_operation_kind = 'CUTOFF'," + + " current_operation_id = '11111111-1111-4111-8111-111111111111'," + + " live_barrier_epoch = live_barrier_epoch + 2", + cutoffTransition + "anchor_exact_bytes = convert_to('changed', 'UTF8')", + cutoffTransition + "account_checkpoint_bytes = convert_to('changed', 'UTF8')", + cutoffTransition + "stable_incarnation_bytes = convert_to('changed', 'UTF8')"); + for (String change : changes) { + assertThatThrownBy(() -> dsl.execute("UPDATE " + table + " SET " + change)) + .as(change) + .hasMessageContaining("Live issuer admission"); + } + assertThatThrownBy(() -> dsl.execute("DELETE FROM " + table)) + .hasMessageContaining("Live issuer admission"); + assertThatThrownBy(() -> dsl.execute("TRUNCATE TABLE " + table + " CASCADE")) + .hasMessageContaining("Live issuer admission"); + assertThat(liveControlEvidenceImage(dsl)).isEqualTo(before); + } + + @Test + void liveIssuerCutoffCompletionFreezesEpochOperationCohortAndSourceAndCannotReopen() { + FixtureState state = fixtureState(); + state.owner().initializeAndRead(state.fixture().originalOperationId()); + UUID cutoffOperationId = UUID.randomUUID(); + state.repository().beginCutoff(cutoffOperationId, UUID.randomUUID()); + var dsl = state.fixture().dsl(); + var pendingImage = liveControlEvidenceImage(dsl); + for (String change : + List.of( + "state = 'OPEN', current_operation_kind = 'INITIAL_ANCHOR_INSTALL'", + "state = 'CUTOFF_PENDING'", + "state = 'INSTALLED', live_barrier_epoch = live_barrier_epoch + 1", + "state = 'INSTALLED', live_barrier_epoch = live_barrier_epoch - 1", + "state = 'INSTALLED', current_operation_id = '11111111-1111-4111-8111-111111111111'", + "state = 'INSTALLED', cohort_row_count = cohort_row_count + 1", + "state = 'INSTALLED', cohort_digest = 'sha256:' || repeat('0', 64)", + "state = 'INSTALLED', bootstrap_control_epoch = bootstrap_control_epoch + 1", + "state = 'INSTALLED', account_checkpoint_bytes = convert_to('changed', 'UTF8')", + "state = 'INSTALLED', anchor_exact_bytes = convert_to('changed', 'UTF8')", + "state = 'INSTALLED', stable_incarnation_bytes = convert_to('changed', 'UTF8')")) { + assertThatThrownBy(() -> dsl.execute("UPDATE " + EVIDENCE_PREFIX + "control SET " + change)) + .as(change) + .hasMessageContaining("Live issuer admission"); + } + assertThat(liveControlEvidenceImage(dsl)).isEqualTo(pendingImage); + var target = state.repository().readPreparedCutoffTargets(cutoffOperationId).getFirst(); + state + .owner() + .closeAndRead( + cutoffOperationId, + target.closedValue().tenantId(), + target.closedValue().playableStateNamespaceId()); + var installed = state.repository().completeCutoff(cutoffOperationId); + var installedImage = liveControlEvidenceImage(dsl); + for (String change : + List.of( + "state = 'INSTALLED'", + "state = 'OPEN', current_operation_kind = 'INITIAL_ANCHOR_INSTALL'", + "state = 'CUTOFF_PENDING', live_barrier_epoch = live_barrier_epoch + 1")) { + assertThatThrownBy(() -> dsl.execute("UPDATE " + EVIDENCE_PREFIX + "control SET " + change)) + .as(change) + .hasMessageContaining("Live issuer admission"); + } + assertThat(state.repository().completeCutoff(cutoffOperationId).exactBytes()) + .containsExactly(installed.exactBytes()); + assertThat(liveControlEvidenceImage(dsl)).isEqualTo(installedImage); + } + + private static Map> liveControlEvidenceImage(DSLContext dsl) { + Map> snapshots = new LinkedHashMap<>(retainedEvidenceImage(dsl)); + for (String family : List.of("epoch_counter", "control")) { + snapshots.put( + family, + dsl.fetch( + "SELECT to_jsonb(evidence)::text || ':' || xmin::text AS image FROM " + + EVIDENCE_PREFIX + + family + + " evidence ORDER BY to_jsonb(evidence)::text") + .getValues("image", String.class)); + } + return snapshots; + } + private static Map> retainedEvidenceImage(DSLContext dsl) { Map> snapshots = new LinkedHashMap<>(); for (String family : EVIDENCE_TABLES) { diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayProtectedIncarnationReceiverPostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayProtectedIncarnationReceiverPostgresIntegrationTest.java index d3e9408b85..3f44927ceb 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayProtectedIncarnationReceiverPostgresIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayProtectedIncarnationReceiverPostgresIntegrationTest.java @@ -4,6 +4,7 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; @@ -14,6 +15,8 @@ import io.lettuce.core.RedisClient; import io.lettuce.core.RedisURI; import io.lettuce.core.api.StatefulRedisConnection; +import io.lettuce.core.api.async.RedisAsyncCommands; +import io.lettuce.core.codec.ByteArrayCodec; import io.lettuce.core.protocol.CommandKeyword; import io.lettuce.core.protocol.CommandType; import java.math.BigInteger; @@ -127,6 +130,98 @@ void localDescriptorFailuresRetainNeverDispatchedOriginalForLaterValidPreparatio } } + @Test + @SuppressWarnings({"unchecked", "rawtypes"}) + void remotePreflightFailuresRetainNeverDispatchedOriginalForValidRetry() throws Exception { + try (Fixture.InitialFixture fixture = Fixture.InitialFixture.open(); + InitialRedisFixture physical = InitialRedisFixture.open(); + var login = fixture.originalLogin(); + var loadConnection = physical.ownerClient.connect(ByteArrayCodec.INSTANCE)) { + var snapshot = fixture.initialRepository.readCurrent(fixture.original.requestId()); + String retained = fixture.initialTargetPostimage(); + String key = + CanonicalGameplayAccountInitialBarrierKey.forTarget( + fixture.tenantTags.assignmentForInitialBarrierTarget(fixture.original.requestId()), + snapshot.initializerId(), + fixture.original.requestId()); + RedisClient connectFailure = mock(RedisClient.class); + when(connectFailure.connect(any(ByteArrayCodec.class))) + .thenThrow(new IllegalStateException("controlled connect failure")); + RedisClient loadFailure = mock(RedisClient.class); + StatefulRedisConnection connection = spy(loadConnection); + RedisAsyncCommands commands = spy(loadConnection.async()); + doReturn(commands).when(connection).async(); + doThrow(new IllegalStateException("controlled SCRIPT LOAD failure")) + .when(commands) + .scriptLoad(any(byte[].class)); + when(loadFailure.connect(any(ByteArrayCodec.class))).thenReturn(connection); + // The actual administrator connection reports principal 'default', which must be refused. + for (RedisClient failingClient : + List.of(connectFailure, physical.administrator, loadFailure)) { + var owner = fixture.initialOwner(failingClient, fixture.initialRepository); + assertThat( + owner.initializeOnce( + fixture.original, login, fixture.tenantId, fixture.namespaceId)) + .isEqualTo( + new CanonicalGameplayAccountInitialOpenProof.Refused( + CanonicalGameplayAccountInitialOpenProof.Reason.TARGET_NEVER_DISPATCHED)); + assertThat(fixture.initialTargetPostimage()).isEqualTo(retained); + assertThat(fixture.initialRepository.readCurrent(fixture.original.requestId()).state()) + .isEqualTo( + CanonicalGameplayAccountInitialBarrierInitializerRepository.State.NEVER_DISPATCHED); + assertThat(physical.connection.sync().exists(key)).isZero(); + } + assertThat( + fixture + .initialOwner(physical.ownerClient, fixture.initialRepository) + .initializeOnce(fixture.original, login, fixture.tenantId, fixture.namespaceId)) + .isInstanceOf(CanonicalGameplayAccountInitialOpenProof.CurrentOpen.class); + assertThat( + fixture.initialRepository.readCurrent(fixture.original.requestId()).initializerId()) + .isEqualTo(snapshot.initializerId()); + physical.connection.sync().del(key); + } + } + + @Test + void lostDispatchClaimReplyLeavesMissingAccountOpenUncertainWithoutAnotherCreate() + throws Exception { + try (Fixture.InitialFixture fixture = Fixture.InitialFixture.open(); + InitialRedisFixture physical = InitialRedisFixture.open(); + var login = fixture.originalLogin()) { + var repository = spy(fixture.initialRepository); + org.mockito.Mockito.doAnswer( + invocation -> { + invocation.callRealMethod(); + throw new IllegalStateException("controlled loss after dispatch claim committed"); + }) + .when(repository) + .recordDispatchPossible(any(), any()); + var owner = fixture.initialOwner(physical.ownerClient, repository); + assertThat( + owner.initializeOnce(fixture.original, login, fixture.tenantId, fixture.namespaceId)) + .isInstanceOf(CanonicalGameplayAccountInitialOpenProof.Refused.class); + var snapshot = fixture.initialRepository.readCurrent(fixture.original.requestId()); + assertThat(snapshot.state()) + .isEqualTo( + CanonicalGameplayAccountInitialBarrierInitializerRepository.State.DISPATCH_POSSIBLE); + String retained = fixture.initialTargetPostimage(); + String key = + CanonicalGameplayAccountInitialBarrierKey.forTarget( + fixture.tenantTags.assignmentForInitialBarrierTarget(fixture.original.requestId()), + snapshot.initializerId(), + fixture.original.requestId()); + assertThat(physical.connection.sync().exists(key)).isZero(); + var retry = fixture.initialOwner(physical.ownerClient, fixture.initialRepository); + assertThat( + retry.initializeOnce(fixture.original, login, fixture.tenantId, fixture.namespaceId)) + .isInstanceOf(CanonicalGameplayAccountInitialOpenProof.Refused.class); + assertThat(fixture.initialTargetPostimage()).isEqualTo(retained); + assertThat(physical.connection.sync().exists(key)).isZero(); + org.mockito.Mockito.verify(repository).recordDispatchPossible(any(), any()); + } + } + @Test void abandonedNeverDispatchedOriginalPreventsFreshInitialForLaterLogin() throws Exception { try (Fixture.InitialFixture fixture = Fixture.InitialFixture.open()) { @@ -607,6 +702,7 @@ void initialArmVerifiesExactOriginalAndNonzeroNoActiveEpochWithSameTrustedVerifi .isEqualTo(fixture.original().callerContextId()); assertThat(verified.originalAttemptFence()).isEqualTo(17L); assertThat(verified.accountId()).isEqualTo(fixture.accountId()); + assertThat(verified.cohortDigest()).isNull(); assertThat(verified.sourceControlState()).isEqualTo("NO_ACTIVE_ACCOUNT_WIDE_FLOW"); assertThat(verified.sourceControlEpoch()).isEqualTo("8"); assertThat(verified.acceptedAttestationDigest()).isEqualTo(ACCEPTED_ATTESTATION_DIGEST); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/InitialGameplayLoginCoordinationJournalRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/InitialGameplayLoginCoordinationJournalRepositoryIntegrationTest.java index 747bf7223f..6d62c22eac 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/InitialGameplayLoginCoordinationJournalRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/InitialGameplayLoginCoordinationJournalRepositoryIntegrationTest.java @@ -457,7 +457,13 @@ void physicalSqlRejectsReplacementReopeningDeletionAndTruncation() throws Except + " SET disposal_disposition = 'PENDING', disposal_proof_kind = 'NONE' WHERE request_id = ?", original.requestId()); rejectedSql("DELETE FROM " + TABLE + " WHERE request_id = ?", original.requestId()); - rejectedSql("TRUNCATE " + TABLE); + // Include references in this disposable schema so the journal guard, rather than the + // foreign-key precheck, rejects truncation before any retained evidence can be removed. + assertThatThrownBy(() -> dsl.execute("TRUNCATE " + TABLE + " CASCADE")) + .hasMessageContaining("Initial gameplay LOGIN journal retention is held") + .isInstanceOfSatisfying( + DataAccessException.class, + failure -> assertThat(failure.sqlState()).isEqualTo("23514")); assertThat(journal.readCommitted(original).orElseThrow().retainedReceipt()).contains(terminal); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierRedisOwnerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierRedisOwnerTest.java index 0cf078dcd0..604808d8e2 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierRedisOwnerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierRedisOwnerTest.java @@ -130,7 +130,9 @@ void missingPhysicalValueAfterPossibleDispatchRefusesWithoutFreshScriptAttempt() } @Test - void possibleDispatchIsPersistedBeforeRedisAndMissingAfterwardNeverGetsAFreshCreate() { + @SuppressWarnings({"unchecked", "rawtypes"}) + void possibleDispatchIsPersistedBeforeEvalAndMissingAfterwardNeverGetsAFreshCreate() + throws Exception { UUID requestId = UUID.randomUUID(); UUID callerContextId = UUID.randomUUID(); UUID initializerId = UUID.randomUUID(); @@ -189,14 +191,33 @@ void possibleDispatchIsPersistedBeforeRedisAndMissingAfterwardNeverGetsAFreshCre when(receiver.observeForInitialAccountBarrier(requestId)).thenReturn(before); RedisClient redis = mock(RedisClient.class); + StatefulRedisConnection connection = mock(StatefulRedisConnection.class); + RedisAsyncCommands commands = mock(RedisAsyncCommands.class); + when(connection.isOpen()).thenReturn(true); + when(connection.async()).thenReturn(commands); + doReturn(future("gamesession_coord_app")).when(commands).aclWhoami(); + when(commands.scriptLoad(any(byte[].class))) + .thenAnswer( + invocation -> { + verify(repository, org.mockito.Mockito.never()).recordDispatchPossible(any(), any()); + return future( + java.util.HexFormat.of() + .formatHex( + java.security.MessageDigest.getInstance("SHA-1") + .digest(invocation.getArgument(0, byte[].class)))); + }); + when(commands.evalsha(any(), any(), any(byte[][].class), any(byte[][].class))) + .thenAnswer( + ignored -> { + verify(repository).recordDispatchPossible(requestId, before); + throw new IllegalStateException("controlled unknown EVAL outcome"); + }); AtomicInteger connectionAttempts = new AtomicInteger(); when(redis.connect(any(ByteArrayCodec.class))) .thenAnswer( ignored -> { - if (connectionAttempts.getAndIncrement() == 0) { - verify(repository).recordDispatchPossible(requestId, before); - } - throw new IllegalStateException("controlled lost connection"); + if (connectionAttempts.getAndIncrement() == 0) return connection; + throw new IllegalStateException("controlled lost readback connection"); }); RedisScriptCatalog catalog = RedisScriptCatalog.fromContributions( @@ -215,6 +236,7 @@ void possibleDispatchIsPersistedBeforeRedisAndMissingAfterwardNeverGetsAFreshCre CanonicalGameplayAccountInitialOpenProof.Reason.REMOTE_OUTCOME_UNCERTAIN)); assertThat(connectionAttempts.get()).isEqualTo(2); verify(repository).recordDispatchPossible(requestId, before); + verify(commands).evalsha(any(), any(), any(byte[][].class), any(byte[][].class)); } @Test @@ -310,7 +332,8 @@ void exactSameOriginalOpenReplayIsReadOnlyAndReturnsCurrentTypedProof() throws E verify(receiver, org.mockito.Mockito.times(2)).observeForInitialAccountBarrier(requestId); verifyNoInteractions(catalog); verify(commands).hgetall(any(byte[].class)); - verify(commands, org.mockito.Mockito.never()).evalsha(any(), any(), any(), any()); + verify(commands, org.mockito.Mockito.never()) + .evalsha(any(), any(), any(byte[][].class), any(byte[][].class)); } @Test @@ -403,7 +426,8 @@ void installedOpenCanBeResolvedByExactTargetAndOnlyPerformsFreshReadback() throw verify(receiver, org.mockito.Mockito.times(2)).observeForInitialAccountBarrier(requestId); verifyNoInteractions(catalog); verify(commands).hgetall(any(byte[].class)); - verify(commands, org.mockito.Mockito.never()).evalsha(any(), any(), any(), any()); + verify(commands, org.mockito.Mockito.never()) + .evalsha(any(), any(), any(byte[][].class), any(byte[][].class)); } @Test @@ -593,7 +617,8 @@ void ambiguousDispatchRetryRequiresExactOpenReadbackBeforeCompletingOriginalRece verify(receiver, org.mockito.Mockito.times(2)).observeForInitialAccountBarrier(requestId); verifyNoInteractions(catalog); verify(commands).hgetall(any(byte[].class)); - verify(commands, org.mockito.Mockito.never()).evalsha(any(), any(), any(), any()); + verify(commands, org.mockito.Mockito.never()) + .evalsha(any(), any(), any(byte[][].class), any(byte[][].class)); } private static CanonicalGameplayAccountInitialBarrierInitializerRepository.InitializerSnapshot From e6b3f691d79b94cfcbce0381e585327708c37240 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 29 Oct 2026 08:53:46 +1300 Subject: [PATCH 21/26] Clarify acknowledgement counter scope and retain descriptor causes --- ...icalGameplayAdmissionBarrierRedisScriptDescriptorLoader.java | 2 +- .../V1047.3__issuer_local_ack_counter_scope_comment.sql | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) create mode 100644 services/game-session-service/src/main/resources/db/migration/V1047.3__issuer_local_ack_counter_scope_comment.sql diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayAdmissionBarrierRedisScriptDescriptorLoader.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayAdmissionBarrierRedisScriptDescriptorLoader.java index 553286411b..74b72f2e93 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayAdmissionBarrierRedisScriptDescriptorLoader.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayAdmissionBarrierRedisScriptDescriptorLoader.java @@ -37,7 +37,7 @@ static RedisScriptDescriptor read(String path, String scriptId, String unavailab } return descriptor; } catch (IOException | RuntimeException failure) { - throw new IllegalStateException(unavailableMessage); + throw new IllegalStateException(unavailableMessage, failure); } } } diff --git a/services/game-session-service/src/main/resources/db/migration/V1047.3__issuer_local_ack_counter_scope_comment.sql b/services/game-session-service/src/main/resources/db/migration/V1047.3__issuer_local_ack_counter_scope_comment.sql new file mode 100644 index 0000000000..05b52925dd --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V1047.3__issuer_local_ack_counter_scope_comment.sql @@ -0,0 +1,2 @@ +COMMENT ON TABLE game_session_canonical_issuer_binding_local_ack_gen_counter IS + 'Independent owner-issued per-issuer binding-local acknowledgement generation; distinct from local member-operation and global issuer coverage generations.'; From fe7dddf2b47f4cad6603a3ee2be959729b8052c7 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 29 Oct 2026 09:28:12 +1300 Subject: [PATCH 22/26] Prepare locked-expiry and acknowledgement-scope review corrections --- .../game-session-service/runtime-and-data.md | 4 +- ...ntInitialBarrierInitializerRepository.java | 16 +-- ...BindingLocalAcknowledgementRepository.java | 21 +++- ...BindingLocalRedisOwnerIntegrationTest.java | 77 +++++++++++++ ...suerPhysicalRetirementIntegrationTest.java | 3 +- ...nationReceiverPostgresIntegrationTest.java | 101 +++++++++++++++++- ...rBindingLocalAcknowledgementCodecTest.java | 19 +++- 7 files changed, 226 insertions(+), 15 deletions(-) diff --git a/design/architecture/microservices/game-session-service/runtime-and-data.md b/design/architecture/microservices/game-session-service/runtime-and-data.md index 375414543f..eff3ad67ed 100644 --- a/design/architecture/microservices/game-session-service/runtime-and-data.md +++ b/design/architecture/microservices/game-session-service/runtime-and-data.md @@ -10,11 +10,11 @@ The service runtime model assumes replaceable workers, not authoritative in-proc The sections below define the target-state runtime contract. Current implementation and proof status is: -- **Local NEW issuer preparation:** the unregistered Game Session sources now manually compose the initial issuer anchor, ordinary post-baseline one-key member/capacity projection, issuer-local release, and original-operation terminal-capacity retirement, each with exact physical readback and controlled Account checkpoint and stable-incarnation collaborators. Ordinary ADD revalidates the target’s current Account authority, while terminal cleanup and non-target accounting preserve captured Account provenance. Completed-original bootstrap retries return retained installation evidence; current physical verification remains separate. The focused component proofs do not establish operational source or incarnation custody. The unregistered readiness owners additionally retain a separate binding-local issuer acknowledgement, live issuer admission control and tenant-local issuer OPEN/cutoff evidence. Forward V1047.1 protects original initializer, readback receipt, frozen cutoff cohort/target and operation evidence against direct SQL removal or rewrite, permitting only the existing owner completion transitions. These do not supply the final session CAS or admission. Operational source/incarnation custody, legacy recovery, production PKI, runtime registration, and activation remain open; see the [Player Access tracker](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-new-admission-components) for proof attribution and limits. The [issuer anchor owner](../../system-architecture-redis.md#installed-issuer-anchor-for-ordinary-new) defines the physical contract. +- **Local NEW issuer preparation:** the unregistered Game Session sources now manually compose the initial issuer anchor, ordinary post-baseline one-key member/capacity projection, issuer-local release, and original-operation terminal-capacity retirement, each with exact physical readback and controlled Account checkpoint and stable-incarnation collaborators. Ordinary ADD revalidates the target’s current Account authority, while terminal cleanup and non-target accounting preserve captured Account provenance. Completed-original bootstrap retries return retained installation evidence; current physical verification remains separate. The focused component proofs do not establish operational source or incarnation custody. The added readiness boundary remains unregistered and does not supply final session CAS or admission. Operational source/incarnation custody, legacy recovery, production PKI, runtime registration, and activation remain open; see the [Player Access tracker](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-new-admission-components) for proof attribution and limits. The [issuer anchor owner](../../system-architecture-redis.md#installed-issuer-anchor-for-ordinary-new) defines the physical contract. - **Local NEW account-member repair:** the unregistered owner prepares the original binding-local operation, performs one global account-member write and physical readback outside SQL, then accepts its exact acknowledgement in SQL. This supplies `ADD_OR_RETAIN` evidence only; the candidate remains provisional. Account-wide lifecycle writers, remaining index and region acknowledgements, and the guarded final admission CAS remain open. See [Session Behavior](../../system-architecture-session-behavior.md#global-account-active-binding-index) and [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-new-admission-components). -- **Account-fence intent and CLOSED target preparation:** local sources persist account acquisition intent and cohort, tenant-to-gameplay-tag mapping, protected current observations, a one-key CLOSED installer/readback, and immutable per-target receipts. A receipt is historical AS-OF evidence; targets remain `REQUIRED`. A separate unregistered INITIAL-only Account OPEN owner retains its original login/control source, target, possible dispatch and exact readback; pending initializers participate in the next acquisition cohort. This arm cannot reopen a CLOSED or uncertain target and does not complete account-wide acquisition or release. Operational protected-incarnation authority, all-target `INSTALLED`, token release, final admitting CAS and production admission remain unproved. See [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-new-admission-components) for proof attribution and limits. +- **Account-fence intent and CLOSED target preparation:** local sources persist account acquisition intent and cohort, tenant-to-gameplay-tag mapping, protected current observations, a one-key CLOSED installer/readback, and immutable per-target receipts. A receipt is historical AS-OF evidence; targets remain `REQUIRED`. The unregistered INITIAL-only Account OPEN component does not complete account-wide acquisition or release. Operational protected-incarnation authority, all-target `INSTALLED`, token release, final admitting CAS and production admission remain unproved. See [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-new-admission-components) for proof attribution and limits. - **Current first-party receiving boundary:** Game Session's prepared receiver verifies the Gateway-signed context and rechecks the canonical target and retained private-handle evidence. When that first-party context is present, bare `LOGIN` and `PLAY` return `FIRST_PARTY_AUTHORITY_UNAVAILABLE` before legacy Account authentication, Entity resolution, or gameplay binding effects. Recovery from registry loss still requires the persisted compact JWS to remain valid; registry loss does not extend its expiry. The public Gateway cookie path is currently denied and its gameplay-route readiness is `OUT_OF_SERVICE`; no first-party wire success or admission is claimed. Account context production, shared replay fencing, and dedicated Gateway key qualification remain open. diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierInitializerRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierInitializerRepository.java index 30ab265e9f..940f767eb8 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierInitializerRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierInitializerRepository.java @@ -311,14 +311,6 @@ InitializerSnapshot acceptOpenReadback( throw conflict("INITIAL readback belongs to a different original request"); } requireReadback(readback); - long now = clock.millis(); - if (now <= 0 - || now < readback.beforeIncarnation().issuedAtEpochMillis() - || now >= readback.beforeIncarnation().expiresAtEpochMillis() - || now < readback.afterIncarnation().issuedAtEpochMillis() - || now >= readback.afterIncarnation().expiresAtEpochMillis()) { - throw conflict("INITIAL protected incarnation observation expired before SQL completion"); - } String fieldsDigest = digestFields(readback.value().fields()); return dsl.transactionResult( @@ -334,6 +326,14 @@ InitializerSnapshot acceptOpenReadback( requireSameCurrentSource(current, source); requireOriginalJournalStillCurrent(transaction, current); requireSameReadbackContext(current, readback); + long now = clock.millis(); + if (now <= 0 + || now < readback.beforeIncarnation().issuedAtEpochMillis() + || now >= readback.beforeIncarnation().expiresAtEpochMillis() + || now < readback.afterIncarnation().issuedAtEpochMillis() + || now >= readback.afterIncarnation().expiresAtEpochMillis()) { + throw conflict("INITIAL protected incarnation observation expired before SQL completion"); + } if (current.state() == State.OPEN_INSTALLED) { if (!fieldsDigest.equals(current.installedFieldsDigest())) { throw conflict("An installed INITIAL OPEN value cannot be replaced"); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalAcknowledgementRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalAcknowledgementRepository.java index 94cbbd9f79..42b9436621 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalAcknowledgementRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalAcknowledgementRepository.java @@ -749,10 +749,27 @@ private static String sha256Hex(byte[] digestBytes) { return "sha256:" + java.util.HexFormat.of().formatHex(digestBytes); } - private static void requireNoAmbientTransaction() { - if (TransactionSynchronizationManager.isActualTransactionActive()) { + private void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { throw unavailable("Issuer acknowledgement owner cannot join an ambient SQL transaction"); } + try { + dsl.connectionResult( + connection -> { + if (!connection.getAutoCommit()) { + throw unavailable("Issuer acknowledgement owner cannot join a jOOQ transaction"); + } + return Boolean.TRUE; + }); + } catch (RuntimeException failure) { + if (failure instanceof IllegalStateException state + && state.getMessage() != null + && state.getMessage().contains("Issuer binding-local acknowledgement is unavailable")) { + throw state; + } + throw unavailable("Issuer acknowledgement SQL connection state is unavailable", failure); + } } private static IllegalStateException unavailable(String message) { diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java index cc2c2729f5..124258a578 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java @@ -62,6 +62,7 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.transaction.support.TransactionSynchronizationManager; import org.testcontainers.containers.GenericContainer; import org.testcontainers.containers.PostgreSQLContainer; import org.testcontainers.junit.jupiter.Container; @@ -516,6 +517,82 @@ void projectsOrdinaryNewAgainstInstalledAnchorAndReusesExactPendingOperation() t .containsEntry(firstCapacityField, first.exactMemberValueBytes()); assertThat(projectionOwner.projectAndRead(first).scriptOutcome()).isEqualTo(3L); + String acknowledgementImageBeforeAmbientRefusals = + dsl.fetch("SELECT * FROM " + ACKNOWLEDGEMENT_TABLE).formatJSON(); + String acknowledgementCounterImageBeforeAmbientRefusals = + dsl.fetch("SELECT * FROM game_session_canonical_issuer_binding_local_ack_gen_counter") + .formatJSON(); + AtomicInteger acknowledgementSourceReads = new AtomicInteger(); + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerStateSource + acknowledgementSource = + () -> { + acknowledgementSourceReads.incrementAndGet(); + return currentState.get(); + }; + var guardedAcknowledgementRepository = + new CanonicalGameplayIssuerBindingLocalAcknowledgementRepository(dsl, acknowledgementSource); + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + assertThatThrownBy(() -> guardedAcknowledgementRepository.acknowledge(firstWithBinding)) + .isInstanceOf(IllegalStateException.class) + .hasMessage( + "Issuer binding-local acknowledgement is unavailable: Issuer acknowledgement owner cannot join an ambient SQL transaction"); + assertThat(acknowledgementSourceReads).hasValue(0); + } finally { + TransactionSynchronizationManager.setActualTransactionActive(false); + } + assertThat(dsl.fetch("SELECT * FROM " + ACKNOWLEDGEMENT_TABLE).formatJSON()) + .isEqualTo(acknowledgementImageBeforeAmbientRefusals); + assertThat( + dsl.fetch("SELECT * FROM game_session_canonical_issuer_binding_local_ack_gen_counter") + .formatJSON()) + .isEqualTo(acknowledgementCounterImageBeforeAmbientRefusals); + + TransactionSynchronizationManager.initSynchronization(); + try { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThatThrownBy(() -> guardedAcknowledgementRepository.acknowledge(firstWithBinding)) + .isInstanceOf(IllegalStateException.class) + .hasMessage( + "Issuer binding-local acknowledgement is unavailable: Issuer acknowledgement owner cannot join an ambient SQL transaction"); + assertThat(acknowledgementSourceReads).hasValue(0); + } finally { + TransactionSynchronizationManager.clearSynchronization(); + } + assertThat(dsl.fetch("SELECT * FROM " + ACKNOWLEDGEMENT_TABLE).formatJSON()) + .isEqualTo(acknowledgementImageBeforeAmbientRefusals); + assertThat( + dsl.fetch("SELECT * FROM game_session_canonical_issuer_binding_local_ack_gen_counter") + .formatJSON()) + .isEqualTo(acknowledgementCounterImageBeforeAmbientRefusals); + + dsl.transaction( + configuration -> { + DSLContext callerTransaction = DSL.using(configuration); + var callerOwnedAcknowledgementRepository = + new CanonicalGameplayIssuerBindingLocalAcknowledgementRepository( + callerTransaction, acknowledgementSource); + assertThatThrownBy(() -> callerOwnedAcknowledgementRepository.acknowledge(firstWithBinding)) + .isInstanceOf(IllegalStateException.class) + .hasMessage( + "Issuer binding-local acknowledgement is unavailable: Issuer acknowledgement owner cannot join a jOOQ transaction"); + assertThat(acknowledgementSourceReads).hasValue(0); + assertThat(callerTransaction.fetch("SELECT * FROM " + ACKNOWLEDGEMENT_TABLE).formatJSON()) + .isEqualTo(acknowledgementImageBeforeAmbientRefusals); + assertThat( + callerTransaction + .fetch( + "SELECT * FROM game_session_canonical_issuer_binding_local_ack_gen_counter") + .formatJSON()) + .isEqualTo(acknowledgementCounterImageBeforeAmbientRefusals); + }); + assertThat(dsl.fetch("SELECT * FROM " + ACKNOWLEDGEMENT_TABLE).formatJSON()) + .isEqualTo(acknowledgementImageBeforeAmbientRefusals); + assertThat( + dsl.fetch("SELECT * FROM game_session_canonical_issuer_binding_local_ack_gen_counter") + .formatJSON()) + .isEqualTo(acknowledgementCounterImageBeforeAmbientRefusals); + var issuerAcknowledgement = acknowledgementRepository.acknowledge(firstWithBinding); assertThat(issuerAcknowledgement.evidence().operationId()).isEqualTo(first.operationId()); assertThat(issuerAcknowledgement.evidence().issuerBindingLocalAcknowledgementGeneration()) diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPhysicalRetirementIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPhysicalRetirementIntegrationTest.java index 4f87d973bc..cbb6a55b0c 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPhysicalRetirementIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPhysicalRetirementIntegrationTest.java @@ -1005,7 +1005,8 @@ void postRetirementProjectionRejectsUnaccountedCurrentReservationInAnotherPartit @Test void seededReleaseCompletesWithoutPublishingTheOriginalAcknowledgement() { - try (var fixture = newFixture()) { + // This class retains prior physical partitions; keep this original in its own layout domain. + try (var fixture = newFixture(BigInteger.valueOf(10), BigInteger.ONE, 0)) { String seed = "release-without-original-acknowledgement"; UUID seededOperationId = fixture.prepareOtherControllerNew(seed); fixture.projectOtherControllerNew(seed); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayProtectedIncarnationReceiverPostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayProtectedIncarnationReceiverPostgresIntegrationTest.java index 3f44927ceb..ecf09a2edc 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayProtectedIncarnationReceiverPostgresIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayProtectedIncarnationReceiverPostgresIntegrationTest.java @@ -35,6 +35,8 @@ import java.util.UUID; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicLong; +import java.util.concurrent.atomic.AtomicReference; import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor; @@ -51,6 +53,8 @@ import org.jooq.SQLDialect; import org.jooq.impl.DSL; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.testcontainers.containers.GenericContainer; import org.testcontainers.containers.PostgreSQLContainer; @@ -441,6 +445,93 @@ void initialOwnerComposesSqlSignedObservationAndRedisWithoutRecreatingResetOpen( } } + @ParameterizedTest + @ValueSource(strings = {"INVENTORY", "CONTROL"}) + void initialOpenReadbackExpiredDuringSqlLockWaitCannotCompleteOriginal(String heldLock) + throws Exception { + AtomicLong trustedMillis = new AtomicLong(NOW.toEpochMilli()); + Clock trustedClock = mock(Clock.class); + when(trustedClock.millis()).thenAnswer(ignored -> trustedMillis.get()); + try (Fixture.InitialFixture fixture = Fixture.InitialFixture.open(); + InitialRedisFixture physical = InitialRedisFixture.open(); + var login = fixture.originalLogin(); + var holder = Fixture.dataSource(fixture.schema).getConnection(); + var acceptanceConnection = Fixture.dataSource(fixture.schema).getConnection()) { + var repository = spy( + new CanonicalGameplayAccountInitialBarrierInitializerRepository(fixture.dsl, trustedClock)); + AtomicReference captured = + new AtomicReference<>(); + org.mockito.Mockito.doAnswer(invocation -> { + captured.set(invocation.getArgument(1)); + throw new IllegalStateException("controlled capture before SQL completion"); + }) + .when(repository).acceptOpenReadback(eq(fixture.original.requestId()), any()); + var owner = fixture.initialOwner( + physical.ownerClient(), repository, + RedisScriptCatalog.fromContributions( + List.of(new CanonicalGameplayAccountInitialBarrierRedisScriptContribution())), + trustedClock); + assertThat(owner.initializeOnce( + fixture.original, login, fixture.tenantId, fixture.namespaceId)) + .isInstanceOf(CanonicalGameplayAccountInitialOpenProof.Refused.class); + var readback = java.util.Objects.requireNonNull(captured.get()); + assertThat(trustedMillis.get()) + .isGreaterThanOrEqualTo(Math.max( + readback.beforeIncarnation().issuedAtEpochMillis(), + readback.afterIncarnation().issuedAtEpochMillis())) + .isLessThan(Math.min( + readback.beforeIncarnation().expiresAtEpochMillis(), + readback.afterIncarnation().expiresAtEpochMillis())); + assertThat(fixture.initialRepository.readCurrent(fixture.original.requestId()).state()) + .isEqualTo( + CanonicalGameplayAccountInitialBarrierInitializerRepository.State.DISPATCH_POSSIBLE); + String retainedTarget = fixture.initialTargetPostimage(); + Map retainedPhysical = physical.connection().sync().hgetall(readback.key()); + assertThat(retainedPhysical).isEqualTo(readback.barrierFields()); + DSLContext holderDsl = DSL.using(holder, SQLDialect.POSTGRES); + DSLContext acceptanceDsl = DSL.using(acceptanceConnection, SQLDialect.POSTGRES); + int holderPid = java.util.Objects.requireNonNull( + holderDsl.fetchSingle("SELECT pg_backend_pid()").get(0, Integer.class)); + int acceptancePid = java.util.Objects.requireNonNull( + acceptanceDsl.fetchSingle("SELECT pg_backend_pid()").get(0, Integer.class)); + var acceptanceRepository = + new CanonicalGameplayAccountInitialBarrierInitializerRepository( + acceptanceDsl, trustedClock); + holder.setAutoCommit(false); + if ("INVENTORY".equals(heldLock)) { + holderDsl.fetchSingle( + "SELECT inventory_revision FROM game_session_canonical_binding_inventory_clock" + + " WHERE singleton_id = 1 FOR UPDATE"); + } else { + holderDsl.fetchSingle( + "SELECT account_id FROM game_session_canonical_account_coverage_control" + + " WHERE account_id = ? FOR UPDATE", fixture.accountId); + } + try (var executor = Executors.newSingleThreadExecutor()) { + try { + var acceptance = executor.submit( + () -> acceptanceRepository.acceptOpenReadback(fixture.original.requestId(), readback)); + awaitInitialBackendBlockedBy(fixture.dsl, acceptancePid, holderPid); + trustedMillis.set(Math.max( + readback.beforeIncarnation().expiresAtEpochMillis(), + readback.afterIncarnation().expiresAtEpochMillis()) + 1L); + holder.rollback(); + assertThatThrownBy(() -> acceptance.get(5L, TimeUnit.SECONDS)) + .hasStackTraceContaining( + "INITIAL protected incarnation observation expired before SQL completion"); + } finally { + holder.rollback(); + } + } + assertThat(fixture.initialRepository.readCurrent(fixture.original.requestId()).state()) + .isEqualTo( + CanonicalGameplayAccountInitialBarrierInitializerRepository.State.DISPATCH_POSSIBLE); + assertThat(fixture.initialTargetPostimage()).isEqualTo(retainedTarget); + assertThat(physical.connection().sync().hgetall(readback.key())).isEqualTo(retainedPhysical); + physical.connection().sync().del(readback.key()); + } + } + @Test void initialOwnerRecoversLostSqlReceiptFromExactPhysicalOpenWithoutAnotherCreate() throws Exception { @@ -1353,6 +1444,14 @@ private CanonicalGameplayAccountInitialBarrierRedisOwner initialOwner( RedisClient client, CanonicalGameplayAccountInitialBarrierInitializerRepository repository, RedisScriptCatalog catalog) { + return initialOwner(client, repository, catalog, Clock.systemUTC()); + } + + private CanonicalGameplayAccountInitialBarrierRedisOwner initialOwner( + RedisClient client, + CanonicalGameplayAccountInitialBarrierInitializerRepository repository, + RedisScriptCatalog catalog, + Clock trustedClock) { var configuration = new CanonicalGameplayProtectedIncarnationReceiver.TrustedConfiguration( ATTESTOR_BINDING, @@ -1370,7 +1469,7 @@ private CanonicalGameplayAccountInitialBarrierRedisOwner initialOwner( tenantTags, new ControlledSigner(keyPair), configuration, - Clock.systemUTC()); + trustedClock); return new CanonicalGameplayAccountInitialBarrierRedisOwner( client, catalog, repository, tenantTags, receiver); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalAcknowledgementCodecTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalAcknowledgementCodecTest.java index 3e8cd65162..8fef593149 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalAcknowledgementCodecTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalAcknowledgementCodecTest.java @@ -39,6 +39,18 @@ void roundTripsDistinctOriginalReservationAnchorAndLocalOperationEvidence() thro .isNotEqualTo(root.path("globalIssuerCoverageGeneration").textValue()); } + @Test + void roundTripsGenerationBeyondJsonExactIntegerRange() throws Exception { + byte[] encoded = CanonicalGameplayIssuerBindingLocalAcknowledgementCodec.encode(fixture(LARGE)); + var decoded = CanonicalGameplayIssuerBindingLocalAcknowledgementCodec.decode(encoded); + + assertThat(JSON.readTree(encoded).path("issuerBindingLocalAcknowledgementGeneration").textValue()) + .isEqualTo(LARGE.toString()); + assertThat(decoded.issuerBindingLocalAcknowledgementGeneration()).isEqualTo(LARGE); + assertThat(CanonicalGameplayIssuerBindingLocalAcknowledgementCodec.encode(decoded)) + .containsExactly(encoded); + } + @Test void rejectsUnknownFieldsAndAnAccountOrGlobalCoverageAlias() throws Exception { byte[] encoded = CanonicalGameplayIssuerBindingLocalAcknowledgementCodec.encode(fixture()); @@ -110,6 +122,11 @@ void rejectsDifferentOriginalReservationProvenanceUnderTheSameBinding() { } private static CanonicalGameplayIssuerBindingLocalAcknowledgement.Evidence fixture() { + return fixture(BigInteger.valueOf(83)); + } + + private static CanonicalGameplayIssuerBindingLocalAcknowledgement.Evidence fixture( + BigInteger acknowledgementGeneration) { var sourceMember = CanonicalGameplayIssuerMemberV2ValueCodecTest.fixture(); var original = sourceMember.reservation(); var reservation = @@ -153,7 +170,7 @@ private static CanonicalGameplayIssuerBindingLocalAcknowledgement.Evidence fixtu .multiply(member.layoutDescriptor().partitionCapacity()); return new CanonicalGameplayIssuerBindingLocalAcknowledgement.Evidence( member.memberOperation().operationId(), - BigInteger.valueOf(83), + acknowledgementGeneration, uuid(41), member.reservation().transitionId(), uuid(42), From be2743f7dee6c3b851583ae5b347db247aef4193 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 29 Oct 2026 10:02:33 +1300 Subject: [PATCH 23/26] Record qualified admission fixes and receiving regression proof --- .../player-access-and-session.md | 2 + ...ntInitialBarrierInitializerRepository.java | 3 +- ...BindingLocalRedisOwnerIntegrationTest.java | 15 ++-- ...nationReceiverPostgresIntegrationTest.java | 82 +++++++++++-------- ...rBindingLocalAcknowledgementCodecTest.java | 3 +- 5 files changed, 63 insertions(+), 42 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 304c47599c..9bdbdd378e 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -18,6 +18,8 @@ The issuer INITIAL arm has a tenant/namespace-wide liveness limit: if its frozen The next receiving correction adds forward [V1047.2](../../../services/game-session-service/src/main/resources/db/migration/V1047.2__issuer_admission_live_control_guards.sql) live counter/control guards: immutable provenance, original forward transitions, retention and deferred commit-time epoch coherence, preserving initial zero-without-control and same-epoch cutoff completion. Both INITIAL Redis owners now verify the principal and script on one connection before committing their one-shot SQL claim, then issue EVAL on that same connection; a lost SQL claim reply remains uncertain and never rearms creation. INITIAL observations leave the inapplicable account-fence cohort digest absent. R914 freshly passes all 79 selected cases (11 units and 68 PostgreSQL/Redis cases), including populated upgrade/history/row-version retention, incompatible upgrade and counter-only commit refusal, valid owner transitions, preflight failure followed by valid retry, lost-claim refusal and journal retention. Migration frontier, jOOQ generation, affected Checkstyle, formatting and documentation checks pass. R912 retains its two test-setup failures; R913 was stopped before executing tests, and neither is reported as successful. These are focused manually composed component results with controlled source and PKI inputs; the recovery, custody, registration and activation limits above remain. +The final receiving correction checks protected INITIAL observation expiry after all SQL lock waits and source guards, and refuses Spring transaction/synchronization and caller-owned jOOQ transactions before acknowledgement external-source reads. Its codec preserves generations above the JSON exact-integer range. R917 freshly passes all 100 selected cases (15 units and 85 PostgreSQL/Redis cases), including both actual lock-wait expiry refusals, reconstructed ordinary-NEW progression with fresh acknowledgement readback, transaction-scope refusals, the whole 11-case physical-retirement class and populated live-control migration proof. The new retirement case uses a distinct retained layout domain rather than sharing another case's physical partition. Migration frontier, jOOQ generation, affected enabled main/integration static analysis, formatting and documentation checks pass on the reconciled parent. The earlier R916 broad aggregate retains its one fixture failure and one existing skip; its 2,732 units, 36 cross-service cases and 21 selected Account native cases passed at that preceding source. These results retain their source attribution and the existing custody, recovery, registration and activation limits. + The current local correction adds explicit recovery for a stale, uninstalled initial issuer-bootstrap candidate. Forward V1038.3 retains its original intent, cohort and issued work, captures the new actual inventory cut under monotonic fences, and atomically binds immutable supersession lineage to current control. A strictly newer trusted layout separates old physical work; installed anchors remain ineligible. Account CI selection and migration task inputs now cover its Game Session owner-composition dependency, and the native registration-image and lost-reply proofs use their actual SQL/Lua contracts. R827 passes 31 of 32 focused cases; its remaining failure is a test assertion against the transaction wrapper rather than the nested PostgreSQL refusal. R828 then passes that complete recovery case with affected integration static and formatting checks. Together they qualify 32 distinct current-source cases, including two actual Account abort compositions; frontier, jOOQ, affected static, formatting and documentation checks pass. The new recovery sequence uses controlled Account terminal input through the actual Game Session abort owner, separately from those two authenticated Account compositions. This is focused proof, not a full service-suite, live layout rotation, retained-key cleanup or production-authority claim. The local issuer owners now reject plans that exceed the executable 256-member-operation bound per partition, including retained `RELEASED` lineage independently of logical active capacity. A blocked plan retains its complete cohort and planned work; physical preparation refuses before allocating operation rows. Fresh ordinary NEW registration also checks the same nonretired local-operation set under the inventory lock before allocating new identities or rows, while exact retries retain their original operation at the bound. Both bootstrap owners use one strict Account issuer source-event verifier. R791 freshly passes the four PostgreSQL boundary cases: 256 allowed, both 257-reservation overflow forms blocked, and ordinary registration refusal/retry with unchanged durable state. R793 then freshly passes all 26 selected PostgreSQL cases across the plan, ordinary-operation and intent owners, plus affected production/integration static analysis, formatting and documentation checks. This is focused owner proof, not a complete service-suite or public admission result. Default registration, external source custody and admission limits remain unchanged. diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierInitializerRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierInitializerRepository.java index 940f767eb8..ed4281cef3 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierInitializerRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierInitializerRepository.java @@ -332,7 +332,8 @@ InitializerSnapshot acceptOpenReadback( || now >= readback.beforeIncarnation().expiresAtEpochMillis() || now < readback.afterIncarnation().issuedAtEpochMillis() || now >= readback.afterIncarnation().expiresAtEpochMillis()) { - throw conflict("INITIAL protected incarnation observation expired before SQL completion"); + throw conflict( + "INITIAL protected incarnation observation expired before SQL completion"); } if (current.state() == State.OPEN_INSTALLED) { if (!fieldsDigest.equals(current.installedFieldsDigest())) { diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java index aa19cdd0ec..9286390eea 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java @@ -562,10 +562,12 @@ void projectsOrdinaryNewAgainstInstalledAnchorAndReusesExactPendingOperation() t return currentState.get(); }; var guardedAcknowledgementRepository = - new CanonicalGameplayIssuerBindingLocalAcknowledgementRepository(dsl, acknowledgementSource); + new CanonicalGameplayIssuerBindingLocalAcknowledgementRepository( + dsl, acknowledgementSource); TransactionSynchronizationManager.setActualTransactionActive(true); try { - assertThatThrownBy(() -> guardedAcknowledgementRepository.acknowledge(acknowledgementReadback)) + assertThatThrownBy( + () -> guardedAcknowledgementRepository.acknowledge(acknowledgementReadback)) .isInstanceOf(IllegalStateException.class) .hasMessage( "Issuer binding-local acknowledgement is unavailable: Issuer acknowledgement owner cannot join an ambient SQL transaction"); @@ -583,7 +585,8 @@ void projectsOrdinaryNewAgainstInstalledAnchorAndReusesExactPendingOperation() t TransactionSynchronizationManager.initSynchronization(); try { assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); - assertThatThrownBy(() -> guardedAcknowledgementRepository.acknowledge(acknowledgementReadback)) + assertThatThrownBy( + () -> guardedAcknowledgementRepository.acknowledge(acknowledgementReadback)) .isInstanceOf(IllegalStateException.class) .hasMessage( "Issuer binding-local acknowledgement is unavailable: Issuer acknowledgement owner cannot join an ambient SQL transaction"); @@ -604,7 +607,8 @@ void projectsOrdinaryNewAgainstInstalledAnchorAndReusesExactPendingOperation() t var callerOwnedAcknowledgementRepository = new CanonicalGameplayIssuerBindingLocalAcknowledgementRepository( callerTransaction, acknowledgementSource); - assertThatThrownBy(() -> callerOwnedAcknowledgementRepository.acknowledge(acknowledgementReadback)) + assertThatThrownBy( + () -> callerOwnedAcknowledgementRepository.acknowledge(acknowledgementReadback)) .isInstanceOf(IllegalStateException.class) .hasMessage( "Issuer binding-local acknowledgement is unavailable: Issuer acknowledgement owner cannot join a jOOQ transaction"); @@ -724,7 +728,8 @@ void projectsOrdinaryNewAgainstInstalledAnchorAndReusesExactPendingOperation() t currentState.set( new CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState( checkpointShape(BigInteger.valueOf(8)), incarnation)); - assertThatThrownBy(() -> restartedAcknowledgementRepository.acknowledge(acknowledgementReadback)) + assertThatThrownBy( + () -> restartedAcknowledgementRepository.acknowledge(acknowledgementReadback)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("differs from the installed anchor"); assertThat(restartedAcknowledgementRepository.readHistorical(first.operationId()).exactBytes()) diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayProtectedIncarnationReceiverPostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayProtectedIncarnationReceiverPostgresIntegrationTest.java index ecf09a2edc..87a72d2747 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayProtectedIncarnationReceiverPostgresIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayProtectedIncarnationReceiverPostgresIntegrationTest.java @@ -457,31 +457,39 @@ void initialOpenReadbackExpiredDuringSqlLockWaitCannotCompleteOriginal(String he var login = fixture.originalLogin(); var holder = Fixture.dataSource(fixture.schema).getConnection(); var acceptanceConnection = Fixture.dataSource(fixture.schema).getConnection()) { - var repository = spy( - new CanonicalGameplayAccountInitialBarrierInitializerRepository(fixture.dsl, trustedClock)); + var repository = + spy( + new CanonicalGameplayAccountInitialBarrierInitializerRepository( + fixture.dsl, trustedClock)); AtomicReference captured = new AtomicReference<>(); - org.mockito.Mockito.doAnswer(invocation -> { - captured.set(invocation.getArgument(1)); - throw new IllegalStateException("controlled capture before SQL completion"); - }) - .when(repository).acceptOpenReadback(eq(fixture.original.requestId()), any()); - var owner = fixture.initialOwner( - physical.ownerClient(), repository, - RedisScriptCatalog.fromContributions( - List.of(new CanonicalGameplayAccountInitialBarrierRedisScriptContribution())), - trustedClock); - assertThat(owner.initializeOnce( - fixture.original, login, fixture.tenantId, fixture.namespaceId)) + org.mockito.Mockito.doAnswer( + invocation -> { + captured.set(invocation.getArgument(1)); + throw new IllegalStateException("controlled capture before SQL completion"); + }) + .when(repository) + .acceptOpenReadback(eq(fixture.original.requestId()), any()); + var owner = + fixture.initialOwner( + physical.ownerClient(), + repository, + RedisScriptCatalog.fromContributions( + List.of(new CanonicalGameplayAccountInitialBarrierRedisScriptContribution())), + trustedClock); + assertThat( + owner.initializeOnce(fixture.original, login, fixture.tenantId, fixture.namespaceId)) .isInstanceOf(CanonicalGameplayAccountInitialOpenProof.Refused.class); var readback = java.util.Objects.requireNonNull(captured.get()); assertThat(trustedMillis.get()) - .isGreaterThanOrEqualTo(Math.max( - readback.beforeIncarnation().issuedAtEpochMillis(), - readback.afterIncarnation().issuedAtEpochMillis())) - .isLessThan(Math.min( - readback.beforeIncarnation().expiresAtEpochMillis(), - readback.afterIncarnation().expiresAtEpochMillis())); + .isGreaterThanOrEqualTo( + Math.max( + readback.beforeIncarnation().issuedAtEpochMillis(), + readback.afterIncarnation().issuedAtEpochMillis())) + .isLessThan( + Math.min( + readback.beforeIncarnation().expiresAtEpochMillis(), + readback.afterIncarnation().expiresAtEpochMillis())); assertThat(fixture.initialRepository.readCurrent(fixture.original.requestId()).state()) .isEqualTo( CanonicalGameplayAccountInitialBarrierInitializerRepository.State.DISPATCH_POSSIBLE); @@ -490,10 +498,12 @@ void initialOpenReadbackExpiredDuringSqlLockWaitCannotCompleteOriginal(String he assertThat(retainedPhysical).isEqualTo(readback.barrierFields()); DSLContext holderDsl = DSL.using(holder, SQLDialect.POSTGRES); DSLContext acceptanceDsl = DSL.using(acceptanceConnection, SQLDialect.POSTGRES); - int holderPid = java.util.Objects.requireNonNull( - holderDsl.fetchSingle("SELECT pg_backend_pid()").get(0, Integer.class)); - int acceptancePid = java.util.Objects.requireNonNull( - acceptanceDsl.fetchSingle("SELECT pg_backend_pid()").get(0, Integer.class)); + int holderPid = + java.util.Objects.requireNonNull( + holderDsl.fetchSingle("SELECT pg_backend_pid()").get(0, Integer.class)); + int acceptancePid = + java.util.Objects.requireNonNull( + acceptanceDsl.fetchSingle("SELECT pg_backend_pid()").get(0, Integer.class)); var acceptanceRepository = new CanonicalGameplayAccountInitialBarrierInitializerRepository( acceptanceDsl, trustedClock); @@ -505,16 +515,22 @@ void initialOpenReadbackExpiredDuringSqlLockWaitCannotCompleteOriginal(String he } else { holderDsl.fetchSingle( "SELECT account_id FROM game_session_canonical_account_coverage_control" - + " WHERE account_id = ? FOR UPDATE", fixture.accountId); + + " WHERE account_id = ? FOR UPDATE", + fixture.accountId); } try (var executor = Executors.newSingleThreadExecutor()) { try { - var acceptance = executor.submit( - () -> acceptanceRepository.acceptOpenReadback(fixture.original.requestId(), readback)); + var acceptance = + executor.submit( + () -> + acceptanceRepository.acceptOpenReadback( + fixture.original.requestId(), readback)); awaitInitialBackendBlockedBy(fixture.dsl, acceptancePid, holderPid); - trustedMillis.set(Math.max( - readback.beforeIncarnation().expiresAtEpochMillis(), - readback.afterIncarnation().expiresAtEpochMillis()) + 1L); + trustedMillis.set( + Math.max( + readback.beforeIncarnation().expiresAtEpochMillis(), + readback.afterIncarnation().expiresAtEpochMillis()) + + 1L); holder.rollback(); assertThatThrownBy(() -> acceptance.get(5L, TimeUnit.SECONDS)) .hasStackTraceContaining( @@ -1465,11 +1481,7 @@ private CanonicalGameplayAccountInitialBarrierRedisOwner initialOwner( Duration.ofSeconds(30)); var receiver = new CanonicalGameplayProtectedIncarnationReceiver( - repository, - tenantTags, - new ControlledSigner(keyPair), - configuration, - trustedClock); + repository, tenantTags, new ControlledSigner(keyPair), configuration, trustedClock); return new CanonicalGameplayAccountInitialBarrierRedisOwner( client, catalog, repository, tenantTags, receiver); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalAcknowledgementCodecTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalAcknowledgementCodecTest.java index 8fef593149..547748b9eb 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalAcknowledgementCodecTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalAcknowledgementCodecTest.java @@ -44,7 +44,8 @@ void roundTripsGenerationBeyondJsonExactIntegerRange() throws Exception { byte[] encoded = CanonicalGameplayIssuerBindingLocalAcknowledgementCodec.encode(fixture(LARGE)); var decoded = CanonicalGameplayIssuerBindingLocalAcknowledgementCodec.decode(encoded); - assertThat(JSON.readTree(encoded).path("issuerBindingLocalAcknowledgementGeneration").textValue()) + assertThat( + JSON.readTree(encoded).path("issuerBindingLocalAcknowledgementGeneration").textValue()) .isEqualTo(LARGE.toString()); assertThat(decoded.issuerBindingLocalAcknowledgementGeneration()).isEqualTo(LARGE); assertThat(CanonicalGameplayIssuerBindingLocalAcknowledgementCodec.encode(decoded)) From 46c0b514c6ba0c2fbc0c6489106600e12cd8e9e3 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 29 Oct 2026 11:29:17 +1300 Subject: [PATCH 24/26] fix: record bounded initial barrier uncertainty diagnostics --- ...meplayAccountInitialBarrierRedisOwner.java | 9 ++++ ...nationReceiverPostgresIntegrationTest.java | 42 +++++++++++++++---- 2 files changed, 43 insertions(+), 8 deletions(-) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierRedisOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierRedisOwner.java index 4eb5ea395f..97b0fb1d8e 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierRedisOwner.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierRedisOwner.java @@ -24,9 +24,13 @@ import net.firedevops.firemud.gamesession.dto.CanonicalGameplayLoginResult; import net.firedevops.firemud.gamesession.dto.InitialGameplayLoginAttemptCoordinates; import net.firedevops.firemud.gamesession.service.CanonicalGameplayAccountInitialBarrierRedisScriptContribution; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** Explicit manual owner for a create-once INITIAL OPEN barrier and exact current readback. */ final class CanonicalGameplayAccountInitialBarrierRedisOwner { + private static final Logger logger = + LoggerFactory.getLogger(CanonicalGameplayAccountInitialBarrierRedisOwner.class); private static final String PRINCIPAL = "gamesession_coord_app"; private static final String KEY_PREFIX = "session:game:account-admission:"; private static final int MAX_SCRIPT_BYTES = 32 * 1024; @@ -133,6 +137,11 @@ CanonicalGameplayAccountInitialOpenProof initializeOnce( tryCreateOnce(prepared, commands, sha); } } catch (RuntimeException possibleDispatchOrSourceFailure) { + logger.warn( + "Initial Account OPEN create attempt did not complete originalRequestId={} initializerId={} failureType={}", + snapshot.originalRequestId(), + snapshot.initializerId(), + possibleDispatchOrSourceFailure.getClass().getName()); // Never create a replacement initializer or repeat a possibly dispatched write. A positive // exact readback can still finish the original receipt; absence remains explicit uncertainty. } diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayProtectedIncarnationReceiverPostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayProtectedIncarnationReceiverPostgresIntegrationTest.java index 87a72d2747..456651a736 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayProtectedIncarnationReceiverPostgresIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayProtectedIncarnationReceiverPostgresIntegrationTest.java @@ -10,6 +10,10 @@ import static org.mockito.Mockito.spy; import static org.mockito.Mockito.when; +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.read.ListAppender; import com.google.protobuf.ByteString; import io.lettuce.core.AclSetuserArgs; import io.lettuce.core.RedisClient; @@ -55,6 +59,7 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; +import org.slf4j.LoggerFactory; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.testcontainers.containers.GenericContainer; import org.testcontainers.containers.PostgreSQLContainer; @@ -190,6 +195,12 @@ void remotePreflightFailuresRetainNeverDispatchedOriginalForValidRetry() throws @Test void lostDispatchClaimReplyLeavesMissingAccountOpenUncertainWithoutAnotherCreate() throws Exception { + String sensitiveMessage = "secret-dispatch-claim-reply-token-and-source-93746"; + Logger logger = + (Logger) LoggerFactory.getLogger(CanonicalGameplayAccountInitialBarrierRedisOwner.class); + ListAppender appender = new ListAppender<>(); + appender.start(); + logger.addAppender(appender); try (Fixture.InitialFixture fixture = Fixture.InitialFixture.open(); InitialRedisFixture physical = InitialRedisFixture.open(); var login = fixture.originalLogin()) { @@ -197,7 +208,7 @@ void lostDispatchClaimReplyLeavesMissingAccountOpenUncertainWithoutAnotherCreate org.mockito.Mockito.doAnswer( invocation -> { invocation.callRealMethod(); - throw new IllegalStateException("controlled loss after dispatch claim committed"); + throw new IllegalStateException(sensitiveMessage); }) .when(repository) .recordDispatchPossible(any(), any()); @@ -223,6 +234,27 @@ void lostDispatchClaimReplyLeavesMissingAccountOpenUncertainWithoutAnotherCreate assertThat(fixture.initialTargetPostimage()).isEqualTo(retained); assertThat(physical.connection.sync().exists(key)).isZero(); org.mockito.Mockito.verify(repository).recordDispatchPossible(any(), any()); + assertThat(appender.list).hasSize(1); + ILoggingEvent event = appender.list.getFirst(); + assertThat(event.getLevel()).isEqualTo(Level.WARN); + assertThat(event.getFormattedMessage()) + .isEqualTo( + "Initial Account OPEN create attempt did not complete originalRequestId=" + + snapshot.originalRequestId() + + " initializerId=" + + snapshot.initializerId() + + " failureType=" + + IllegalStateException.class.getName()) + .doesNotContain(sensitiveMessage); + assertThat(event.getArgumentArray()) + .containsExactly( + snapshot.originalRequestId(), + snapshot.initializerId(), + IllegalStateException.class.getName()); + assertThat(event.getThrowableProxy()).isNull(); + } finally { + logger.detachAppender(appender); + appender.stop(); } } @@ -1295,13 +1327,7 @@ private static InitialFixture open() throws Exception { private static InitialFixture open(BigInteger sourceControlEpoch) throws Exception { String schema = "gs_initial_incarnation_" + UUID.randomUUID().toString().replace("-", ""); - DriverManagerDataSource dataSource = new DriverManagerDataSource(); - dataSource.setDriverClassName("org.postgresql.Driver"); - String jdbcUrl = postgres.getJdbcUrl(); - String separator = jdbcUrl.contains("?") ? "&" : "?"; - dataSource.setUrl(jdbcUrl + separator + "currentSchema=" + schema); - dataSource.setUsername(postgres.getUsername()); - dataSource.setPassword(postgres.getPassword()); + DriverManagerDataSource dataSource = Fixture.dataSource(schema); Flyway.configure() .dataSource(dataSource) .schemas(schema) From 1eca27d97c3de361fb9bfc39f70410d6a35f3351 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 29 Oct 2026 16:20:21 +1300 Subject: [PATCH 25/26] Apply canonical capacity regression spacing --- .../CanonicalGameplayIssuerLocalCapacityIntegrationTest.java | 1 - 1 file changed, 1 deletion(-) diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLocalCapacityIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLocalCapacityIntegrationTest.java index 5e6edb7292..a94f2133dd 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLocalCapacityIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLocalCapacityIntegrationTest.java @@ -481,7 +481,6 @@ void seededReleaseCompletesWithoutPublishingTheOriginalAcknowledgement() { } } - @Test void actualReleaseReadbackPersistsAndReloadsWithMoreThan513PhysicalFields() throws Exception { try (var fixture = newFixture(BigInteger.valueOf(8), BigInteger.ONE, 250)) { From c04d6844699e93bad609c6ed8c6112d196c9f84a Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 30 Oct 2026 01:45:31 +1300 Subject: [PATCH 26/26] Keep issuer upgrade fixtures at their historical frontier and allow positive fsync latency --- ...eplayAdmissionAbortCompositionFixture.java | 45 ++++++++++++++++++- ...ssionBarrierRepositoryIntegrationTest.java | 7 ++- ...eplayLoginContextRedisIntegrationTest.java | 5 ++- 3 files changed, 53 insertions(+), 4 deletions(-) diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionAbortCompositionFixture.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionAbortCompositionFixture.java index 26eba4df09..f3d5e5f406 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionAbortCompositionFixture.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionAbortCompositionFixture.java @@ -145,6 +145,49 @@ public CanonicalGameplayAdmissionAbortCompositionFixture( MigrationVersion migrationTarget, BiConsumer afterBootstrap) { + this( + accountDataSource, + accountCandidate, + issuerRedisClient, + seedBootstrapMemberCount, + migrationTarget, + afterBootstrap, + true); + } + + /** + * Keeps the actual V1047-era owners at their historical schema until the caller upgrades it. + * Later-schema composition tests retain the normal after-bootstrap upgrade behavior. + */ + static CanonicalGameplayAdmissionAbortCompositionFixture atHistoricalIssuerAdmissionFrontier( + DriverManagerDataSource accountDataSource, + Candidate accountCandidate, + RedisClient issuerRedisClient, + MigrationVersion migrationTarget) { + Objects.requireNonNull(migrationTarget, "migrationTarget"); + if (!migrationTarget.equals(MigrationVersion.fromVersion("1047")) + && !migrationTarget.equals(MigrationVersion.fromVersion("1047.1"))) { + throw new IllegalArgumentException("Historical issuer admission requires V1047 or V1047.1"); + } + return new CanonicalGameplayAdmissionAbortCompositionFixture( + accountDataSource, + accountCandidate, + issuerRedisClient, + 0, + migrationTarget, + (data, intent) -> {}, + false); + } + + private CanonicalGameplayAdmissionAbortCompositionFixture( + DriverManagerDataSource accountDataSource, + Candidate accountCandidate, + RedisClient issuerRedisClient, + int seedBootstrapMemberCount, + MigrationVersion migrationTarget, + BiConsumer + afterBootstrap, + boolean upgradeAfterBootstrap) { if (seedBootstrapMemberCount < 0 || seedBootstrapMemberCount > 256) { throw new IllegalArgumentException("Bootstrap fixture member count must be within [0, 256]"); } @@ -240,7 +283,7 @@ public CanonicalGameplayAdmissionAbortCompositionFixture( new CanonicalGameplayIssuerBootstrapCoverageOwner(dsl, partitionOwner, issuerSource) .completeInitialBootstrap(bootstrapIntent.operationId(), bootstrapRequestId); Objects.requireNonNull(afterBootstrap, "afterBootstrap").accept(dataSource, bootstrapIntent); - if (migrationTarget != null) { + if (migrationTarget != null && upgradeAfterBootstrap) { upgradeWithDefaultGameSessionMigrations(MigrationVersion.LATEST, dataSource); } new CanonicalGameplayIssuerAdmissionControlRepository(dsl) diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepositoryIntegrationTest.java index b7adaa6115..a211c7a1a9 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepositoryIntegrationTest.java @@ -1498,8 +1498,11 @@ private FixtureState fixtureState(MigrationVersion migrationTarget) { accountDataSource.setUsername(POSTGRES.getUsername()); accountDataSource.setPassword(POSTGRES.getPassword()); fixture = - new CanonicalGameplayAdmissionAbortCompositionFixture( - accountDataSource, candidate, ownerClient, 0, migrationTarget); + migrationTarget == null + ? new CanonicalGameplayAdmissionAbortCompositionFixture( + accountDataSource, candidate, ownerClient, 0) + : CanonicalGameplayAdmissionAbortCompositionFixture.atHistoricalIssuerAdmissionFrontier( + accountDataSource, candidate, ownerClient, migrationTarget); Candidate actualCandidate = fixture.candidate(); CanonicalGameplayBindingIdentity identity = identity(actualCandidate); fixture.publish(controlledLeaseEvidence(identity, fixture.generation(), fixture.target())); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextRedisIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextRedisIntegrationTest.java index 7d2c646fe8..10147d37af 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextRedisIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextRedisIntegrationTest.java @@ -301,7 +301,10 @@ void exactInstallAndRetryUsePhysicalAcknowledgementsIndependentReadbackAndNoSecr var result = validatedResult(original, UUID.randomUUID()); var qualification = new ControlledAuthority(); var provider = new TracedProvider(writer); - var client = client(provider, qualification, 1); + // A positive durability proof allows replica fsync under shared-runner load. + // Insufficient-acknowledgement cases keep their separate short failure deadline. + var client = + client(provider, qualification, new AcknowledgementPolicy(Profile.REPLICATED, 1, 1, 3_000)); var installed = InitialGameplayLoginContextState.installed(original, result); provider.expectedReadback = installed.encode(); var firstInstall = client.install(original, result);