From 887f5728718c40f25504f4c99b681bbd7f2b7d14 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 16:09:14 +1300 Subject: [PATCH 1/3] feat(common): define bounded StartSession operator action digest contract --- .../start-session-action-schema.md | 48 ++ .../tests/test_start_session_action_digest.py | 311 +++++++++ .../common/operator/MutationDigestV1.java | 299 +++++++++ .../operator/StartSessionOperatorAction.java | 143 +++++ .../StartSessionOperatorActionCodec.java | 605 ++++++++++++++++++ .../StartSessionOperatorActionCodecTest.java | 225 +++++++ ...rt-session-mutation-digest-v1-vectors.json | 167 +++++ 7 files changed, 1798 insertions(+) create mode 100644 design/architecture/microservices/game-session-service/start-session-action-schema.md create mode 100644 dev-tools/tests/test_start_session_action_digest.py create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/MutationDigestV1.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/StartSessionOperatorAction.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/StartSessionOperatorActionCodec.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/operator/StartSessionOperatorActionCodecTest.java create mode 100644 services/common-platform-core/src/test/resources/operator/start-session-mutation-digest-v1-vectors.json diff --git a/design/architecture/microservices/game-session-service/start-session-action-schema.md b/design/architecture/microservices/game-session-service/start-session-action-schema.md new file mode 100644 index 0000000000..b3b3432495 --- /dev/null +++ b/design/architecture/microservices/game-session-service/start-session-action-schema.md @@ -0,0 +1,48 @@ +# StartSession Operator Action Schema + +## Normative contract + +This document defines the StartSession action-family schema `firemud.game-session.start-session`, version `1`, owned by `game-session-service`. It defines the digest input shape for the `StartSession` operator action. It does not make the external operator route routable or establish an authorization decision. + +The request is a JSON object whose declared member order is `actionFamilySchemaId`, `actionFamilySchemaVersion`, `scope`, `target`, `expectedVersion`, `mutation`, and `auditReason`. `expectedVersion` is absent for this creation action and must not appear in the JSON request, including as `null`. Its absence remains an explicit seventh field in the canonical digest preimage. All other top-level members are required. + +| Member | Required shape and constraint | +| --- | --- | +| `actionFamilySchemaId` | String exactly `firemud.game-session.start-session`. | +| `actionFamilySchemaVersion` | String exactly `1`. | +| `scope` | Object with exactly `tenantId`, then `targetNamespace`. | +| `scope.tenantId` | Canonical lowercase, hyphenated, non-nil UUID. | +| `scope.targetNamespace` | Kubernetes workload namespace label: 1–63 lowercase ASCII letters or digits, with internal hyphens allowed and no leading or trailing hyphen. | +| `target` | Object with exactly `gameTemplateId`, then `ownerAccountId`. | +| `target.gameTemplateId` | JSON string matching `[1-9][0-9]*`, within the current owner's signed `long` range. JSON numbers and strings with a sign, leading zero, decimal point, or exponent are rejected. | +| `target.ownerAccountId` | Canonical lowercase, hyphenated, non-nil Account UUID. Private legacy identifier mappings remain the receiver's responsibility. | +| `expectedVersion` | Explicitly absent for StartSession creation. Any supplied value, including `null`, is rejected. | +| `mutation` | Object with the optional member `clientIp`. | +| `mutation.clientIp` | Absent or a string whose NFC-normalized UTF-8 encoding is at most 128 bytes. Empty string is distinct from absence. `null` and all other types are rejected. No address parsing or ownership claim is implied. | +| `auditReason` | Required string, nonblank after NFC normalization, at most 1,000 normalized UTF-8 bytes. | + +JSON object members must appear in the declared order. Duplicate raw keys, keys colliding after NFC normalization, unknown or missing members, wrong JSON types, malformed Unicode, invalid UTF-8, and trailing tokens are rejected before a digest is returned. Object and array values use the recursive typed grammar from [ADR 0047, Bounded Owner Delegation](../../decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md#bounded-owner-delegation); no generic JSON canonicalization is a substitute. + +The schema uses these shared parser and encoding bounds: + +| Limit | Maximum | +| --- | ---: | +| Raw UTF-8 JSON input | 16 KiB | +| Composite nesting depth | 8 | +| Members in one object | 16 | +| Elements in one array | 64 | +| NFC-normalized string or object-key bytes | 4,096 | +| Raw or canonical numeric bytes | 128 | +| Numeric scale | 128 | +| Canonical segment payload | 8,192 bytes | +| Complete `mutationDigest/v1` preimage | 32 KiB | + +## Digest inputs and exclusions + +The SHA-256 preimage follows ADR 0047's exact `mutationDigest/v1` framing. The schema pair and these typed fields are included in the ADR-defined order: `scope`, `target`, absent `expectedVersion`, `mutation`, and `auditReason`. The `mutation` object always declares one member, `clientIp`; if it is omitted from JSON, the digest still includes that member in its declared position with type `absent` and presence `0`. An empty string is encoded as a present `string` and therefore has a different digest. + +The target owner is fixed to `game-session-service` for this schema and is carried separately in the ADR 0048 execution tuple; it is not a digest field. `controlPlaneRequestId`, any separately tagged action-family request identity, reservation owner and claim fence, transport credentials, opaque authorization references, actor assertions, and Account authority evidence are outside these seven grammar fields and are compared at their respective boundaries under [ADR 0047](../../decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md#bounded-owner-delegation) and [ADR 0048](../../decisions/adr-0048-durable-idempotent-operator-write-execution.md#one-correlated-execution). + +The action contains no runtime version or patch input. It does not assert current ownership or authority. Game Design selects a launch descriptor under its independently authorized operation; the Game Session owner performs its separate domain and execution checks. + +The shared Java implementation exposes `StartSessionOperatorActionCodec.decode(byte[])`, `canonicalPreimage(...)`, and `mutationDigest(...)`, plus the immutable typed action accessors. Shared Java and Python conformance vectors are stored in [the common vector fixture](../../../../services/common-platform-core/src/test/resources/operator/start-session-mutation-digest-v1-vectors.json). diff --git a/dev-tools/tests/test_start_session_action_digest.py b/dev-tools/tests/test_start_session_action_digest.py new file mode 100644 index 0000000000..93a94b9a2e --- /dev/null +++ b/dev-tools/tests/test_start_session_action_digest.py @@ -0,0 +1,311 @@ +#!/usr/bin/env python3 +"""Standard-library conformance checks for StartSession mutationDigest/v1 vectors.""" + +import hashlib +import json +import re +import unicodedata +import unittest +from dataclasses import dataclass +from pathlib import Path + + +ROOT = Path(__file__).resolve().parents[2] +FIXTURE = ( + ROOT + / "services/common-platform-core/src/test/resources/operator/" + / "start-session-mutation-digest-v1-vectors.json" +) +SCHEMA_ID = "firemud.game-session.start-session" +SCHEMA_VERSION = "1" +TOP_LEVEL_ORDER = [ + "actionFamilySchemaId", + "actionFamilySchemaVersion", + "scope", + "target", + "expectedVersion", + "mutation", + "auditReason", +] +UUID_PATTERN = re.compile(r"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\Z") +NAMESPACE_PATTERN = re.compile(r"[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\Z") +NUMBER_SOURCE = re.compile(r"-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?\Z") +NUMBER_CANONICAL = re.compile(r"0|-?(?:[1-9][0-9]*(?:\.[0-9]*[1-9])?|0\.[0-9]*[1-9])\Z") + + +@dataclass(frozen=True) +class RawNumber: + lexeme: str + + +@dataclass(frozen=True) +class RawObject: + members: list + + +def reject_constant(_value): + raise ValueError("non-finite numeric value") + + +def parse_json(raw): + if len(raw) > 16 * 1_024: + raise ValueError("raw JSON exceeds its byte limit") + source = raw.decode("utf-8", "strict") + return json.loads( + source, + parse_int=RawNumber, + parse_float=RawNumber, + parse_constant=reject_constant, + object_pairs_hook=lambda pairs: RawObject(pairs), + ) + + +def scalar_string(value, byte_limit=4_096): + if not isinstance(value, str): + raise ValueError("string value required") + if any(0xD800 <= ord(character) <= 0xDFFF for character in value): + raise ValueError("malformed Unicode") + normalized = unicodedata.normalize("NFC", value) + encoded = normalized.encode("utf-8", "strict") + if len(encoded) > byte_limit: + raise ValueError("normalized string exceeds its byte limit") + return normalized + + +def segment(payload): + if len(payload) > 8_192: + raise ValueError("segment exceeds its byte limit") + return str(len(payload)).encode("ascii") + b":" + payload + + +def decimal_value(raw): + lexeme = raw.lexeme + encoded = lexeme.encode("ascii", "strict") + if len(encoded) > 128 or not NUMBER_SOURCE.fullmatch(lexeme): + raise ValueError("numeric source is invalid or too long") + fraction = lexeme.partition(".")[2] + if len(fraction) > 128: + raise ValueError("numeric scale exceeds its limit") + negative = lexeme.startswith("-") + unsigned = lexeme[1:] if negative else lexeme + integer, separator, fraction = unsigned.partition(".") + fraction = fraction.rstrip("0") if separator else "" + nonzero = any(digit != "0" for digit in integer + fraction) + if not nonzero: + canonical = "0" + elif fraction: + canonical = ("-" if negative else "") + integer + "." + fraction + else: + canonical = ("-" if negative else "") + integer + canonical_bytes = canonical.encode("ascii") + if len(canonical_bytes) > 128 or not NUMBER_CANONICAL.fullmatch(canonical): + raise ValueError("canonical number exceeds its limit") + return canonical_bytes + + +def encoded_value(value, depth=0): + if depth > 8: + raise ValueError("composite nesting is too deep") + if value is ABSENT: + return segment(b"absent") + b"0" + segment(b"") + if value is None: + return segment(b"null") + b"1" + segment(b"") + if isinstance(value, str): + payload = scalar_string(value).encode("utf-8") + return segment(b"string") + b"1" + segment(payload) + if isinstance(value, RawNumber): + return segment(b"number") + b"1" + segment(decimal_value(value)) + if isinstance(value, bool): + return segment(b"boolean") + b"1" + segment(b"true" if value else b"false") + if isinstance(value, RawObject): + if len(value.members) > 16: + raise ValueError("object exceeds its member limit") + normalized_members = [] + seen = set() + for raw_key, member_value in value.members: + key = scalar_string(raw_key).encode("utf-8") + if key in seen: + raise ValueError("duplicate or normalized-colliding object key") + seen.add(key) + normalized_members.append((key, member_value)) + payload = segment(str(len(normalized_members)).encode("ascii")) + for key, member_value in normalized_members: + payload += segment(key) + encoded_value(member_value, depth + 1) + return segment(b"object") + b"1" + segment(payload) + if isinstance(value, list): + if len(value) > 64: + raise ValueError("array exceeds its element limit") + payload = segment(str(len(value)).encode("ascii")) + for item in value: + payload += encoded_value(item, depth + 1) + return segment(b"array") + b"1" + segment(payload) + raise ValueError("unsupported typed JSON value") + + +ABSENT = object() + + +def ordered_members(value, declared_order, optional=()): + if not isinstance(value, RawObject): + raise ValueError("object value required") + if len(value.members) > 16: + raise ValueError("object exceeds its member limit") + members = {} + actual_order = [] + for raw_key, member_value in value.members: + key = scalar_string(raw_key) + if key in members: + raise ValueError("duplicate or normalized-colliding object key") + members[key] = member_value + actual_order.append(key) + if any(key not in declared_order for key in actual_order): + raise ValueError("unknown object member") + expected_order = [key for key in declared_order if key in members or key not in optional] + if actual_order != expected_order: + raise ValueError("missing or out-of-order object member") + return members + + +def canonical_uuid(value, label): + normalized = scalar_string(value) + if not UUID_PATTERN.fullmatch(normalized) or normalized == "00000000-0000-0000-0000-000000000000": + raise ValueError(f"{label} is not a canonical non-nil UUID") + return normalized + + +def action_preimage(raw): + root = parse_json(raw) + members = ordered_members(root, TOP_LEVEL_ORDER, optional={"expectedVersion"}) + if members.get("actionFamilySchemaId") != SCHEMA_ID: + raise ValueError("wrong schema id") + if members.get("actionFamilySchemaVersion") != SCHEMA_VERSION: + raise ValueError("wrong schema version") + if "expectedVersion" in members: + raise ValueError("expectedVersion must be absent") + + scope = ordered_members(members["scope"], ["tenantId", "targetNamespace"]) + tenant_id = canonical_uuid(scope["tenantId"], "tenantId") + namespace = scalar_string(scope["targetNamespace"]) + if len(namespace) > 63 or not NAMESPACE_PATTERN.fullmatch(namespace): + raise ValueError("invalid workload namespace") + + target = ordered_members(members["target"], ["gameTemplateId", "ownerAccountId"]) + template_id = scalar_string(target["gameTemplateId"]) + if not re.fullmatch(r"[1-9][0-9]*", template_id): + raise ValueError("gameTemplateId must be a positive canonical decimal string") + if len(template_id) > 19 or ( + len(template_id) == 19 and template_id > "9223372036854775807" + ): + raise ValueError("gameTemplateId exceeds the current owner long range") + owner_id = canonical_uuid(target["ownerAccountId"], "ownerAccountId") + + mutation = ordered_members(members["mutation"], ["clientIp"], optional={"clientIp"}) + if "clientIp" not in mutation: + client_ip = ABSENT + else: + client_ip = mutation["clientIp"] + if not isinstance(client_ip, str): + raise ValueError("clientIp must be an absent or string value") + client_ip = scalar_string(client_ip, 128) + + audit_reason = scalar_string(members["auditReason"], 1_000) + if not audit_reason or all(character.isspace() for character in audit_reason): + raise ValueError("auditReason must not be blank") + + values = [ + ("actionFamilySchemaId", SCHEMA_ID), + ("actionFamilySchemaVersion", SCHEMA_VERSION), + ( + "scope", + RawObject( + [ + ("tenantId", tenant_id), + ("targetNamespace", namespace), + ] + ), + ), + ( + "target", + RawObject( + [ + ("gameTemplateId", template_id), + ("ownerAccountId", owner_id), + ] + ), + ), + ("expectedVersion", ABSENT), + ("mutation", RawObject([("clientIp", client_ip)])), + ("auditReason", audit_reason), + ] + result = segment(b"mutationDigest/v1") + for name, typed_value in values: + result += segment(name.encode("utf-8")) + encoded_value(typed_value) + if len(result) > 32 * 1_024: + raise ValueError("preimage exceeds its byte limit") + return result + + +def raw_vector_bytes(vector): + if "rawHex" in vector: + return bytes.fromhex(vector["rawHex"]) + return vector["input"].encode("utf-8", "strict") + + +class StartSessionMutationDigestVectorTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.fixture = json.loads(FIXTURE.read_text(encoding="utf-8")) + + def test_action_vectors(self): + results = {} + for vector in self.fixture["vectors"]: + with self.subTest(vector=vector["name"]): + raw = raw_vector_bytes(vector) + if not vector["accepted"]: + with self.assertRaises((ValueError, UnicodeError, json.JSONDecodeError)): + action_preimage(raw) + continue + preimage = action_preimage(raw) + digest = hashlib.sha256(preimage).hexdigest() + self.assertEqual(preimage.hex(), vector["preimageHex"]) + self.assertEqual(digest, vector["digest"]) + results[vector["name"]] = digest + + self.assertNotEqual(results["base"], results["changed-target"]) + self.assertNotEqual(results["base"], results["changed-scope"]) + self.assertNotEqual(results["base"], results["changed-audit-reason"]) + self.assertNotEqual(results["client-ip-absent"], results["client-ip-empty"]) + self.assertEqual(results["unicode-composed"], results["unicode-decomposed"]) + + def test_generic_value_grammar_vectors(self): + encodings = {} + for vector in self.fixture["grammarVectors"]: + with self.subTest(vector=vector["name"]): + if vector["kind"] == "numberLexeme": + if not vector["accepted"]: + with self.assertRaises((ValueError, UnicodeError)): + encoded_value(RawNumber(vector["rawLexeme"])) + continue + canonical = encoded_value(RawNumber(vector["rawLexeme"])) + self.assertEqual(canonical.hex(), vector["canonicalValueHex"]) + encodings[vector["name"]] = canonical.hex() + continue + if vector["kind"] == "reject": + with self.assertRaises((ValueError, UnicodeError, json.JSONDecodeError)): + encoded_value(parse_json(vector["rawValue"].encode("utf-8"))) + continue + if vector["kind"] == "absent": + canonical = encoded_value(ABSENT) + else: + canonical = encoded_value(parse_json(vector["rawValue"].encode("utf-8"))) + self.assertEqual(canonical.hex(), vector["canonicalValueHex"]) + encodings[vector["name"]] = canonical.hex() + + self.assertNotEqual(encodings["absent"], encodings["null"]) + self.assertNotEqual(encodings["number-one"], encodings["string-one"]) + self.assertEqual(encodings["number-signed-zero"], encodings["number-zero"]) + self.assertEqual(encodings["unicode-key-composed"], encodings["unicode-key-decomposed"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/MutationDigestV1.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/MutationDigestV1.java new file mode 100644 index 0000000000..1da36c7cbe --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/MutationDigestV1.java @@ -0,0 +1,299 @@ +package net.firedevops.firemud.common.operator; + +import java.io.ByteArrayOutputStream; +import java.math.BigDecimal; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.text.Normalizer; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.regex.Pattern; + +/** Package-private implementation of the ADR 0047 mutationDigest/v1 byte grammar. */ +final class MutationDigestV1 { + static final int MAX_NORMALIZED_STRING_BYTES = 4_096; + static final int MAX_NUMERIC_BYTES = 128; + static final int MAX_NUMERIC_SCALE = 128; + static final int MAX_SEGMENT_BYTES = 8_192; + static final int MAX_PREIMAGE_BYTES = 32 * 1_024; + + private static final String DOMAIN = "mutationDigest/v1"; + private static final Pattern NUMBER_SOURCE = Pattern.compile("-?(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?"); + private static final Pattern NUMBER_CANONICAL = + Pattern.compile("0|-?(?:[1-9][0-9]*(?:\\.[0-9]*[1-9])?|0\\.[0-9]*[1-9])"); + + private MutationDigestV1() {} + + static byte[] preimage(StartSessionOperatorAction action) { + Objects.requireNonNull(action, "action is required"); + ByteArrayOutputStream output = new ByteArrayOutputStream(); + writeSegment(output, utf8(DOMAIN)); + writeField(output, "actionFamilySchemaId", string(action.actionFamilySchemaId())); + writeField(output, "actionFamilySchemaVersion", string(action.actionFamilySchemaVersion())); + writeField( + output, + "scope", + object( + List.of( + member("tenantId", string(action.scope().tenantId().toString())), + member("targetNamespace", string(action.scope().targetNamespace()))))); + writeField( + output, + "target", + object( + List.of( + member("gameTemplateId", string(Long.toString(action.target().gameTemplateId()))), + member("ownerAccountId", string(action.target().ownerAccountId().toString()))))); + writeField(output, "expectedVersion", absent()); + Value clientIp = + action.mutation().clientIp() instanceof StartSessionOperatorAction.AbsentClientIp + ? absent() + : string( + ((StartSessionOperatorAction.StringClientIp) action.mutation().clientIp()).value()); + writeField(output, "mutation", object(List.of(member("clientIp", clientIp)))); + writeField(output, "auditReason", string(action.auditReason())); + byte[] preimage = output.toByteArray(); + if (preimage.length > MAX_PREIMAGE_BYTES) { + throw invalid("canonical preimage exceeds its byte limit"); + } + return preimage; + } + + static String sha256Hex(byte[] preimage) { + Objects.requireNonNull(preimage, "preimage is required"); + if (preimage.length > MAX_PREIMAGE_BYTES) { + throw invalid("canonical preimage exceeds its byte limit"); + } + try { + byte[] digest = MessageDigest.getInstance("SHA-256").digest(preimage); + StringBuilder hex = new StringBuilder(digest.length * 2); + for (byte value : digest) { + hex.append(Character.forDigit((value >>> 4) & 0x0f, 16)); + hex.append(Character.forDigit(value & 0x0f, 16)); + } + return hex.toString(); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + static Value absent() { + return new ScalarValue("absent", false, new byte[0]); + } + + static Value nullValue() { + return new ScalarValue("null", true, new byte[0]); + } + + static Value string(String value) { + String normalized = normalize(value, MAX_NORMALIZED_STRING_BYTES, "string"); + return new ScalarValue("string", true, utf8(normalized)); + } + + static Value number(String rawLexeme) { + Objects.requireNonNull(rawLexeme, "number lexeme is required"); + byte[] rawBytes = utf8(rawLexeme); + if (rawBytes.length > MAX_NUMERIC_BYTES || !NUMBER_SOURCE.matcher(rawLexeme).matches()) { + throw invalid("number lexeme is invalid or exceeds its byte limit"); + } + int decimalPoint = rawLexeme.indexOf('.'); + if (decimalPoint >= 0 && rawLexeme.length() - decimalPoint - 1 > MAX_NUMERIC_SCALE) { + throw invalid("number scale exceeds its limit"); + } + BigDecimal decimal; + try { + decimal = new BigDecimal(rawLexeme); + } catch (NumberFormatException exception) { + throw invalid("number lexeme is invalid"); + } + String canonical = decimal.signum() == 0 ? "0" : decimal.stripTrailingZeros().toPlainString(); + byte[] canonicalBytes = utf8(canonical); + if (canonicalBytes.length > MAX_NUMERIC_BYTES + || !NUMBER_CANONICAL.matcher(canonical).matches()) { + throw invalid("canonical number exceeds its byte limit"); + } + return new ScalarValue("number", true, canonicalBytes); + } + + static Value bool(boolean value) { + return new ScalarValue("boolean", true, utf8(value ? "true" : "false")); + } + + static Value object(List members) { + return new ObjectValue(members); + } + + static Value array(List values) { + return new ArrayValue(values); + } + + static Member member(String key, Value value) { + return new Member(key, value); + } + + static byte[] encodedValue(Value value) { + ByteArrayOutputStream output = new ByteArrayOutputStream(); + writeValue(output, value); + return output.toByteArray(); + } + + static Value normalizeObject(List rawMembers) { + Objects.requireNonNull(rawMembers, "object members are required"); + if (rawMembers.size() > 16) { + throw invalid("object exceeds its member limit"); + } + List normalizedMembers = new ArrayList<>(rawMembers.size()); + List seenKeys = new ArrayList<>(rawMembers.size()); + for (Member member : rawMembers) { + String key = normalize(member.key(), MAX_NORMALIZED_STRING_BYTES, "object key"); + if (seenKeys.contains(key)) { + throw invalid("object contains a duplicate or normalized-colliding key"); + } + seenKeys.add(key); + normalizedMembers.add(new Member(key, member.value())); + } + return new ObjectValue(normalizedMembers); + } + + private static void writeField(ByteArrayOutputStream output, String name, Value value) { + writeSegment(output, utf8(name)); + writeValue(output, value); + if (output.size() > MAX_PREIMAGE_BYTES) { + throw invalid("canonical preimage exceeds its byte limit"); + } + } + + private static void writeValue(ByteArrayOutputStream output, Value value) { + Objects.requireNonNull(value, "typed value is required"); + String type; + boolean present; + byte[] payload; + if (value instanceof ScalarValue scalar) { + type = scalar.type(); + present = scalar.present(); + payload = scalar.payload(); + } else if (value instanceof ObjectValue object) { + type = "object"; + present = true; + payload = objectPayload(object.members()); + } else if (value instanceof ArrayValue array) { + type = "array"; + present = true; + payload = arrayPayload(array.values()); + } else { + throw invalid("unsupported typed value"); + } + writeSegment(output, utf8(type)); + output.write(present ? '1' : '0'); + writeSegment(output, payload); + } + + private static byte[] objectPayload(List members) { + if (members.size() > 16) { + throw invalid("object exceeds its member limit"); + } + ByteArrayOutputStream output = new ByteArrayOutputStream(); + writeSegment(output, utf8(Integer.toString(members.size()))); + for (Member member : members) { + writeSegment(output, utf8(member.key())); + writeValue(output, member.value()); + } + return boundedPayload(output); + } + + private static byte[] arrayPayload(List values) { + if (values.size() > 64) { + throw invalid("array exceeds its element limit"); + } + ByteArrayOutputStream output = new ByteArrayOutputStream(); + writeSegment(output, utf8(Integer.toString(values.size()))); + for (Value value : values) { + writeValue(output, value); + } + return boundedPayload(output); + } + + private static byte[] boundedPayload(ByteArrayOutputStream output) { + if (output.size() > MAX_SEGMENT_BYTES) { + throw invalid("canonical segment exceeds its byte limit"); + } + return output.toByteArray(); + } + + private static void writeSegment(ByteArrayOutputStream output, byte[] bytes) { + if (bytes.length > MAX_SEGMENT_BYTES) { + throw invalid("canonical segment exceeds its byte limit"); + } + output.writeBytes(Integer.toString(bytes.length).getBytes(StandardCharsets.US_ASCII)); + output.write(':'); + output.writeBytes(bytes); + } + + private static String normalize(String value, int byteLimit, String label) { + Objects.requireNonNull(value, label + " is required"); + requireUnicodeScalars(value, label); + String normalized = Normalizer.normalize(value, Normalizer.Form.NFC); + requireUnicodeScalars(normalized, label); + if (utf8(normalized).length > byteLimit) { + throw invalid(label + " exceeds its normalized UTF-8 byte limit"); + } + return normalized; + } + + private static void requireUnicodeScalars(String value, String label) { + for (int index = 0; index < value.length(); index++) { + char current = value.charAt(index); + if (Character.isHighSurrogate(current)) { + if (index + 1 >= value.length() || !Character.isLowSurrogate(value.charAt(index + 1))) { + throw invalid(label + " contains malformed Unicode"); + } + index++; + } else if (Character.isLowSurrogate(current)) { + throw invalid(label + " contains malformed Unicode"); + } + } + } + + private static byte[] utf8(String value) { + return value.getBytes(StandardCharsets.UTF_8); + } + + private static IllegalArgumentException invalid(String message) { + return new IllegalArgumentException(message); + } + + sealed interface Value permits ScalarValue, ObjectValue, ArrayValue {} + + record ScalarValue(String type, boolean present, byte[] payload) implements Value { + ScalarValue { + Objects.requireNonNull(type); + payload = payload.clone(); + } + + @Override + public byte[] payload() { + return payload.clone(); + } + } + + record Member(String key, Value value) { + Member { + Objects.requireNonNull(key); + Objects.requireNonNull(value); + } + } + + record ObjectValue(List members) implements Value { + ObjectValue { + members = List.copyOf(members); + } + } + + record ArrayValue(List values) implements Value { + ArrayValue { + values = List.copyOf(values); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/StartSessionOperatorAction.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/StartSessionOperatorAction.java new file mode 100644 index 0000000000..59a09e72da --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/StartSessionOperatorAction.java @@ -0,0 +1,143 @@ +package net.firedevops.firemud.common.operator; + +import java.nio.charset.StandardCharsets; +import java.text.Normalizer; +import java.util.Objects; +import java.util.UUID; +import java.util.regex.Pattern; + +/** Immutable typed action covered by the StartSession operator schema. */ +public record StartSessionOperatorAction( + String actionFamilySchemaId, + String actionFamilySchemaVersion, + Scope scope, + Target target, + ExpectedVersion expectedVersion, + Mutation mutation, + String auditReason) { + + public static final String ACTION_FAMILY_SCHEMA_ID = "firemud.game-session.start-session"; + public static final String ACTION_FAMILY_SCHEMA_VERSION = "1"; + public static final String ACTION_FAMILY = "StartSession"; + public static final String OWNER_SERVICE = "game-session-service"; + + private static final Pattern WORKLOAD_NAMESPACE = + Pattern.compile("[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?"); + private static final UUID NIL_UUID = new UUID(0L, 0L); + + public StartSessionOperatorAction { + if (!ACTION_FAMILY_SCHEMA_ID.equals(actionFamilySchemaId)) { + throw new IllegalArgumentException("unsupported actionFamilySchemaId"); + } + if (!ACTION_FAMILY_SCHEMA_VERSION.equals(actionFamilySchemaVersion)) { + throw new IllegalArgumentException("unsupported actionFamilySchemaVersion"); + } + Objects.requireNonNull(scope, "scope is required"); + Objects.requireNonNull(target, "target is required"); + Objects.requireNonNull(expectedVersion, "expectedVersion is required"); + if (expectedVersion != ExpectedVersion.ABSENT) { + throw new IllegalArgumentException( + "expectedVersion must be absent for StartSession creation"); + } + Objects.requireNonNull(mutation, "mutation is required"); + auditReason = normalizedString(auditReason, "auditReason", 1_000); + if (isUnicodeBlank(auditReason)) { + throw new IllegalArgumentException("auditReason must not be blank"); + } + } + + public enum ExpectedVersion { + ABSENT + } + + public String actionFamily() { + return ACTION_FAMILY; + } + + /** Returns the immutable ADR 0048 target owner, which is compared outside the digest tuple. */ + public String targetOwner() { + return OWNER_SERVICE; + } + + public record Scope(UUID tenantId, String targetNamespace) { + public Scope { + Objects.requireNonNull(tenantId, "tenantId is required"); + if (NIL_UUID.equals(tenantId)) { + throw new IllegalArgumentException("tenantId must not be nil"); + } + Objects.requireNonNull(targetNamespace, "targetNamespace is required"); + if (targetNamespace.length() > 63 || !WORKLOAD_NAMESPACE.matcher(targetNamespace).matches()) { + throw new IllegalArgumentException("targetNamespace must be a valid workload namespace"); + } + } + } + + public record Target(long gameTemplateId, UUID ownerAccountId) { + public Target { + if (gameTemplateId <= 0) { + throw new IllegalArgumentException("gameTemplateId must be positive"); + } + Objects.requireNonNull(ownerAccountId, "ownerAccountId is required"); + if (NIL_UUID.equals(ownerAccountId)) { + throw new IllegalArgumentException("ownerAccountId must not be nil"); + } + } + } + + public record Mutation(ClientIp clientIp) { + public Mutation { + Objects.requireNonNull(clientIp, "clientIp presence is required"); + } + } + + /** The action schema accepts either an absent clientIp member or a string value. */ + public sealed interface ClientIp permits AbsentClientIp, StringClientIp { + static ClientIp absent() { + return new AbsentClientIp(); + } + + static ClientIp of(String value) { + return new StringClientIp(value); + } + } + + public record AbsentClientIp() implements ClientIp {} + + public record StringClientIp(String value) implements ClientIp { + public StringClientIp { + value = normalizedString(value, "clientIp", 128); + } + } + + private static String normalizedString(String value, String fieldName, int byteLimit) { + Objects.requireNonNull(value, fieldName + " is required"); + requireUnicodeScalars(value, fieldName); + String normalized = Normalizer.normalize(value, Normalizer.Form.NFC); + requireUnicodeScalars(normalized, fieldName); + if (normalized.getBytes(StandardCharsets.UTF_8).length > byteLimit) { + throw new IllegalArgumentException(fieldName + " exceeds its normalized UTF-8 byte limit"); + } + return normalized; + } + + private static void requireUnicodeScalars(String value, String fieldName) { + for (int index = 0; index < value.length(); index++) { + char current = value.charAt(index); + if (Character.isHighSurrogate(current)) { + if (index + 1 >= value.length() || !Character.isLowSurrogate(value.charAt(index + 1))) { + throw new IllegalArgumentException(fieldName + " contains malformed Unicode"); + } + index++; + } else if (Character.isLowSurrogate(current)) { + throw new IllegalArgumentException(fieldName + " contains malformed Unicode"); + } + } + } + + private static boolean isUnicodeBlank(String value) { + return value + .codePoints() + .allMatch( + codePoint -> Character.isWhitespace(codePoint) || Character.isSpaceChar(codePoint)); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/StartSessionOperatorActionCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/StartSessionOperatorActionCodec.java new file mode 100644 index 0000000000..ed4552f151 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/StartSessionOperatorActionCodec.java @@ -0,0 +1,605 @@ +package net.firedevops.firemud.common.operator; + +import java.nio.ByteBuffer; +import java.nio.CharBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.text.Normalizer; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import java.util.regex.Pattern; + +/** Strict token-preserving JSON codec and digest entry point for StartSession operator actions. */ +public final class StartSessionOperatorActionCodec { + public static final int MAX_RAW_BYTES = 16 * 1_024; + public static final int MAX_NESTING_DEPTH = 8; + public static final int MAX_OBJECT_MEMBERS = 16; + public static final int MAX_ARRAY_ELEMENTS = 64; + public static final int MAX_NORMALIZED_STRING_BYTES = + MutationDigestV1.MAX_NORMALIZED_STRING_BYTES; + public static final int MAX_NUMERIC_BYTES = MutationDigestV1.MAX_NUMERIC_BYTES; + public static final int MAX_NUMERIC_SCALE = MutationDigestV1.MAX_NUMERIC_SCALE; + public static final int MAX_SEGMENT_BYTES = MutationDigestV1.MAX_SEGMENT_BYTES; + public static final int MAX_PREIMAGE_BYTES = MutationDigestV1.MAX_PREIMAGE_BYTES; + + private static final Pattern UUID_PATTERN = + Pattern.compile("[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"); + private static final List TOP_LEVEL_FIELDS = + List.of( + "actionFamilySchemaId", + "actionFamilySchemaVersion", + "scope", + "target", + "expectedVersion", + "mutation", + "auditReason"); + + private StartSessionOperatorActionCodec() {} + + /** Decodes only the declared StartSession schema and rejects every unsupported shape. */ + public static StartSessionOperatorAction decode(byte[] rawJson) { + JsonValue root = new StrictJsonParser(rawJson).parseDocument(); + if (!(root instanceof JsonObject object)) { + throw invalid("StartSession action must be a JSON object"); + } + Map members = + orderedMembers(object, TOP_LEVEL_FIELDS, Set.of("expectedVersion")); + String schemaId = requiredString(members.get("actionFamilySchemaId"), "actionFamilySchemaId"); + String schemaVersion = + requiredString(members.get("actionFamilySchemaVersion"), "actionFamilySchemaVersion"); + if (!StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID.equals(schemaId) + || !StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION.equals(schemaVersion)) { + throw invalid("unsupported StartSession action-family schema pair"); + } + if (members.containsKey("expectedVersion")) { + throw invalid("expectedVersion must be absent for StartSession creation"); + } + StartSessionOperatorAction.Scope scope = readScope(members.get("scope")); + StartSessionOperatorAction.Target target = readTarget(members.get("target")); + StartSessionOperatorAction.Mutation mutation = readMutation(members.get("mutation")); + String auditReason = requiredString(members.get("auditReason"), "auditReason"); + return new StartSessionOperatorAction( + schemaId, + schemaVersion, + scope, + target, + StartSessionOperatorAction.ExpectedVersion.ABSENT, + mutation, + auditReason); + } + + /** Returns the exact ADR 0047 mutationDigest/v1 preimage for one typed action. */ + public static byte[] canonicalPreimage(StartSessionOperatorAction action) { + return MutationDigestV1.preimage(Objects.requireNonNull(action, "action is required")); + } + + /** Decodes an action and returns its exact ADR 0047 mutationDigest/v1 preimage. */ + public static byte[] canonicalPreimage(byte[] rawJson) { + return canonicalPreimage(decode(rawJson)); + } + + /** Returns the lowercase hexadecimal SHA-256 digest for one typed action. */ + public static String mutationDigest(StartSessionOperatorAction action) { + return MutationDigestV1.sha256Hex(canonicalPreimage(action)); + } + + /** Decodes an action and returns its lowercase hexadecimal SHA-256 digest. */ + public static String mutationDigest(byte[] rawJson) { + return mutationDigest(decode(rawJson)); + } + + /* Test bridge for the recursive value grammar. It is not an action-schema decoder. */ + static byte[] canonicalGrammarValueForTest(byte[] rawJson) { + JsonValue parsed = new StrictJsonParser(rawJson).parseDocument(); + return MutationDigestV1.encodedValue(toGrammarValue(parsed)); + } + + static byte[] absentGrammarValueForTest() { + return MutationDigestV1.encodedValue(MutationDigestV1.absent()); + } + + static byte[] canonicalNumberLexemeForTest(String rawLexeme) { + return MutationDigestV1.encodedValue(MutationDigestV1.number(rawLexeme)); + } + + private static StartSessionOperatorAction.Scope readScope(JsonValue value) { + JsonObject object = requireObject(value, "scope"); + Map members = + orderedMembers(object, List.of("tenantId", "targetNamespace"), Set.of()); + UUID tenantId = canonicalUuid(requiredString(members.get("tenantId"), "tenantId"), "tenantId"); + String namespace = requiredString(members.get("targetNamespace"), "targetNamespace"); + return new StartSessionOperatorAction.Scope(tenantId, namespace); + } + + private static StartSessionOperatorAction.Target readTarget(JsonValue value) { + JsonObject object = requireObject(value, "target"); + Map members = + orderedMembers(object, List.of("gameTemplateId", "ownerAccountId"), Set.of()); + JsonValue templateValue = members.get("gameTemplateId"); + if (!(templateValue instanceof JsonString templateIdValue)) { + throw invalid("gameTemplateId must be a positive canonical decimal string"); + } + String templateIdText = + normalizeString(templateIdValue.value(), MAX_NORMALIZED_STRING_BYTES, "gameTemplateId"); + if (!templateIdText.matches("[1-9][0-9]*")) { + throw invalid("gameTemplateId must be a positive canonical decimal string"); + } + long gameTemplateId; + try { + gameTemplateId = Long.parseLong(templateIdText); + } catch (NumberFormatException exception) { + throw invalid("gameTemplateId exceeds the current owner long range"); + } + UUID ownerAccountId = + canonicalUuid( + requiredString(members.get("ownerAccountId"), "ownerAccountId"), "ownerAccountId"); + return new StartSessionOperatorAction.Target(gameTemplateId, ownerAccountId); + } + + private static StartSessionOperatorAction.Mutation readMutation(JsonValue value) { + JsonObject object = requireObject(value, "mutation"); + Map members = + orderedMembers(object, List.of("clientIp"), Set.of("clientIp")); + JsonValue clientIp = members.get("clientIp"); + if (clientIp == null) { + return new StartSessionOperatorAction.Mutation(StartSessionOperatorAction.ClientIp.absent()); + } + if (clientIp instanceof JsonNull) { + throw invalid("clientIp may be absent or a string, but not null"); + } + if (!(clientIp instanceof JsonString string)) { + throw invalid("clientIp must be a string"); + } + String normalized = normalizeString(string.value(), 128, "clientIp"); + return new StartSessionOperatorAction.Mutation( + StartSessionOperatorAction.ClientIp.of(normalized)); + } + + private static String requiredString(JsonValue value, String fieldName) { + if (!(value instanceof JsonString string)) { + throw invalid(fieldName + " must be a string"); + } + return normalizeString(string.value(), MAX_NORMALIZED_STRING_BYTES, fieldName); + } + + private static UUID canonicalUuid(String value, String fieldName) { + if (!UUID_PATTERN.matcher(value).matches()) { + throw invalid(fieldName + " must be a canonical lowercase UUID"); + } + UUID uuid; + try { + uuid = UUID.fromString(value); + } catch (IllegalArgumentException exception) { + throw invalid(fieldName + " must be a canonical lowercase UUID"); + } + if (uuid.getMostSignificantBits() == 0L && uuid.getLeastSignificantBits() == 0L) { + throw invalid(fieldName + " must not be nil"); + } + return uuid; + } + + private static JsonObject requireObject(JsonValue value, String fieldName) { + if (!(value instanceof JsonObject object)) { + throw invalid(fieldName + " must be an object"); + } + return object; + } + + private static Map orderedMembers( + JsonObject object, List declaredOrder, Set optionalMembers) { + if (object.members().size() > MAX_OBJECT_MEMBERS) { + throw invalid("object exceeds its member limit"); + } + Map normalizedMembers = new LinkedHashMap<>(); + for (JsonMember member : object.members()) { + String key = normalizeString(member.key().value(), MAX_NORMALIZED_STRING_BYTES, "object key"); + if (normalizedMembers.putIfAbsent(key, member.value()) != null) { + throw invalid("object contains a duplicate or normalized-colliding member"); + } + if (!declaredOrder.contains(key)) { + throw invalid("object contains an unknown member"); + } + } + List expectedOrder = + declaredOrder.stream() + .filter(key -> normalizedMembers.containsKey(key) || !optionalMembers.contains(key)) + .toList(); + if (!new ArrayList<>(normalizedMembers.keySet()).equals(expectedOrder)) { + throw invalid("object members are missing or out of declared order"); + } + return normalizedMembers; + } + + private static MutationDigestV1.Value toGrammarValue(JsonValue value) { + if (value instanceof JsonString string) { + return MutationDigestV1.string(string.value()); + } + if (value instanceof JsonNumber number) { + return MutationDigestV1.number(number.lexeme()); + } + if (value instanceof JsonBoolean bool) { + return MutationDigestV1.bool(bool.value()); + } + if (value instanceof JsonNull) { + return MutationDigestV1.nullValue(); + } + if (value instanceof JsonArray array) { + return MutationDigestV1.array( + array.values().stream().map(StartSessionOperatorActionCodec::toGrammarValue).toList()); + } + if (value instanceof JsonObject object) { + List members = new ArrayList<>(object.members().size()); + for (JsonMember member : object.members()) { + String key = + normalizeString(member.key().value(), MAX_NORMALIZED_STRING_BYTES, "object key"); + members.add(MutationDigestV1.member(key, toGrammarValue(member.value()))); + } + return MutationDigestV1.normalizeObject(members); + } + throw invalid("unsupported JSON value"); + } + + private static String normalizeString(String value, int maxUtf8Bytes, String fieldName) { + requireUnicodeScalars(value, fieldName); + String normalized = Normalizer.normalize(value, Normalizer.Form.NFC); + requireUnicodeScalars(normalized, fieldName); + if (normalized.getBytes(StandardCharsets.UTF_8).length > maxUtf8Bytes) { + throw invalid(fieldName + " exceeds its normalized UTF-8 byte limit"); + } + return normalized; + } + + private static void requireUnicodeScalars(String value, String fieldName) { + for (int index = 0; index < value.length(); index++) { + char current = value.charAt(index); + if (Character.isHighSurrogate(current)) { + if (index + 1 >= value.length() || !Character.isLowSurrogate(value.charAt(index + 1))) { + throw invalid(fieldName + " contains malformed Unicode"); + } + index++; + } else if (Character.isLowSurrogate(current)) { + throw invalid(fieldName + " contains malformed Unicode"); + } + } + } + + private static IllegalArgumentException invalid(String message) { + return new IllegalArgumentException(message); + } + + private sealed interface JsonValue + permits JsonString, JsonNumber, JsonBoolean, JsonNull, JsonObject, JsonArray { + byte[] rawToken(); + } + + private record JsonString(String value, byte[] rawToken) implements JsonValue { + private JsonString { + rawToken = rawToken.clone(); + } + } + + private record JsonNumber(String lexeme, byte[] rawToken) implements JsonValue { + private JsonNumber { + rawToken = rawToken.clone(); + } + } + + private record JsonBoolean(boolean value, byte[] rawToken) implements JsonValue { + private JsonBoolean { + rawToken = rawToken.clone(); + } + } + + private record JsonNull(byte[] rawToken) implements JsonValue { + private JsonNull { + rawToken = rawToken.clone(); + } + } + + private record JsonMember(JsonString key, JsonValue value) {} + + private record JsonObject(List members, byte[] rawToken) implements JsonValue { + private JsonObject { + members = List.copyOf(members); + rawToken = rawToken.clone(); + } + } + + private record JsonArray(List values, byte[] rawToken) implements JsonValue { + private JsonArray { + values = List.copyOf(values); + rawToken = rawToken.clone(); + } + } + + /** Small bounded parser that retains source tokens and object occurrence order. */ + private static final class StrictJsonParser { + private final byte[] input; + private final String source; + private final int[] byteOffsets; + private int position; + + private StrictJsonParser(byte[] input) { + Objects.requireNonNull(input, "raw JSON is required"); + if (input.length > MAX_RAW_BYTES) { + throw invalid("raw JSON exceeds its byte limit"); + } + this.input = input.clone(); + try { + CharBuffer decoded = + StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(this.input)); + this.source = decoded.toString(); + } catch (CharacterCodingException exception) { + throw invalid("raw JSON is not valid UTF-8"); + } + this.byteOffsets = computeByteOffsets(this.source, this.input.length); + } + + private JsonValue parseDocument() { + skipWhitespace(); + JsonValue value = parseValue(0); + skipWhitespace(); + if (position != source.length()) { + throw invalid("raw JSON contains trailing tokens"); + } + return value; + } + + private JsonValue parseValue(int parentDepth) { + if (position >= source.length()) { + throw invalid("raw JSON ended before a value"); + } + char next = source.charAt(position); + if (next == '"') { + return parseString(); + } + if (next == '{') { + if (parentDepth + 1 > MAX_NESTING_DEPTH) { + throw invalid("raw JSON exceeds its nesting-depth limit"); + } + return parseObject(parentDepth + 1); + } + if (next == '[') { + if (parentDepth + 1 > MAX_NESTING_DEPTH) { + throw invalid("raw JSON exceeds its nesting-depth limit"); + } + return parseArray(parentDepth + 1); + } + if (next == 't') { + return parseLiteral("true", new JsonBoolean(true, new byte[0])); + } + if (next == 'f') { + return parseLiteral("false", new JsonBoolean(false, new byte[0])); + } + if (next == 'n') { + return parseLiteral("null", new JsonNull(new byte[0])); + } + return parseNumber(); + } + + private JsonValue parseLiteral(String literal, JsonValue placeholder) { + int start = position; + if (!source.startsWith(literal, position)) { + throw invalid("raw JSON contains an invalid token"); + } + position += literal.length(); + byte[] raw = rawToken(start, position); + if (placeholder instanceof JsonBoolean bool) { + return new JsonBoolean(bool.value(), raw); + } + return new JsonNull(raw); + } + + private JsonNumber parseNumber() { + int start = position; + while (position < source.length() && !isValueDelimiter(source.charAt(position))) { + position++; + } + if (start == position) { + throw invalid("raw JSON contains an invalid value token"); + } + byte[] raw = rawToken(start, position); + if (raw.length > MAX_NUMERIC_BYTES) { + throw invalid("numeric token exceeds its byte limit"); + } + return new JsonNumber(source.substring(start, position), raw); + } + + private JsonString parseString() { + int start = position; + position++; + StringBuilder value = new StringBuilder(); + while (position < source.length()) { + char current = source.charAt(position++); + if (current == '"') { + byte[] raw = rawToken(start, position); + String decoded = value.toString(); + requireUnicodeScalars(decoded, "string"); + return new JsonString(decoded, raw); + } + if (current == '\\') { + if (position >= source.length()) { + throw invalid("raw JSON ends inside a string escape"); + } + char escaped = source.charAt(position++); + switch (escaped) { + case '"' -> value.append('"'); + case '\\' -> value.append('\\'); + case '/' -> value.append('/'); + case 'b' -> value.append('\b'); + case 'f' -> value.append('\f'); + case 'n' -> value.append('\n'); + case 'r' -> value.append('\r'); + case 't' -> value.append('\t'); + case 'u' -> appendUnicodeEscape(value); + default -> throw invalid("raw JSON contains an invalid string escape"); + } + } else { + if (current < 0x20) { + throw invalid("raw JSON string contains an unescaped control character"); + } + value.append(current); + } + } + throw invalid("raw JSON string is unterminated"); + } + + private void appendUnicodeEscape(StringBuilder value) { + char first = readHexCodeUnit(); + if (Character.isHighSurrogate(first)) { + if (position + 1 >= source.length() + || source.charAt(position) != '\\' + || source.charAt(position + 1) != 'u') { + throw invalid("raw JSON string contains an unpaired surrogate"); + } + position += 2; + char second = readHexCodeUnit(); + if (!Character.isLowSurrogate(second)) { + throw invalid("raw JSON string contains an unpaired surrogate"); + } + value.append(first).append(second); + } else if (Character.isLowSurrogate(first)) { + throw invalid("raw JSON string contains an unpaired surrogate"); + } else { + value.append(first); + } + } + + private char readHexCodeUnit() { + if (position + 4 > source.length()) { + throw invalid("raw JSON string contains a short Unicode escape"); + } + int value = 0; + for (int index = 0; index < 4; index++) { + char digit = source.charAt(position++); + int hex = Character.digit(digit, 16); + if (hex < 0 || digit > 0x7f) { + throw invalid("raw JSON string contains an invalid Unicode escape"); + } + value = (value << 4) | hex; + } + return (char) value; + } + + private JsonObject parseObject(int depth) { + int start = position++; + skipWhitespace(); + List members = new ArrayList<>(); + if (consume('}')) { + return new JsonObject(members, rawToken(start, position)); + } + while (true) { + if (position >= source.length() || source.charAt(position) != '"') { + throw invalid("raw JSON object member key must be a string"); + } + if (members.size() >= MAX_OBJECT_MEMBERS) { + throw invalid("raw JSON object exceeds its member limit"); + } + JsonString key = parseString(); + skipWhitespace(); + require(':'); + skipWhitespace(); + JsonValue value = parseValue(depth); + members.add(new JsonMember(key, value)); + skipWhitespace(); + if (consume('}')) { + return new JsonObject(members, rawToken(start, position)); + } + require(','); + skipWhitespace(); + } + } + + private JsonArray parseArray(int depth) { + int start = position++; + skipWhitespace(); + List values = new ArrayList<>(); + if (consume(']')) { + return new JsonArray(values, rawToken(start, position)); + } + while (true) { + if (values.size() >= MAX_ARRAY_ELEMENTS) { + throw invalid("raw JSON array exceeds its element limit"); + } + values.add(parseValue(depth)); + skipWhitespace(); + if (consume(']')) { + return new JsonArray(values, rawToken(start, position)); + } + require(','); + skipWhitespace(); + } + } + + private byte[] rawToken(int start, int end) { + return Arrays.copyOfRange(input, byteOffsets[start], byteOffsets[end]); + } + + private void skipWhitespace() { + while (position < source.length()) { + char value = source.charAt(position); + if (value != ' ' && value != '\t' && value != '\r' && value != '\n') { + return; + } + position++; + } + } + + private boolean consume(char expected) { + if (position < source.length() && source.charAt(position) == expected) { + position++; + return true; + } + return false; + } + + private void require(char expected) { + if (!consume(expected)) { + throw invalid("raw JSON punctuation or member order is invalid"); + } + } + + private static boolean isValueDelimiter(char value) { + return value == ',' + || value == ']' + || value == '}' + || value == ' ' + || value == '\t' + || value == '\r' + || value == '\n'; + } + + private static int[] computeByteOffsets(String source, int expectedBytes) { + int[] offsets = new int[source.length() + 1]; + int characterIndex = 0; + int byteIndex = 0; + while (characterIndex < source.length()) { + int codePoint = source.codePointAt(characterIndex); + int characterCount = Character.charCount(codePoint); + int width = codePoint <= 0x7f ? 1 : codePoint <= 0x7ff ? 2 : codePoint <= 0xffff ? 3 : 4; + offsets[characterIndex] = byteIndex; + if (characterCount == 2) { + offsets[characterIndex + 1] = byteIndex; + } + characterIndex += characterCount; + byteIndex += width; + offsets[characterIndex] = byteIndex; + } + if (byteIndex != expectedBytes) { + throw invalid("raw JSON UTF-8 framing is inconsistent"); + } + return offsets; + } + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/operator/StartSessionOperatorActionCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/operator/StartSessionOperatorActionCodecTest.java new file mode 100644 index 0000000000..de35ef6b9e --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/operator/StartSessionOperatorActionCodecTest.java @@ -0,0 +1,225 @@ +package net.firedevops.firemud.common.operator; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.util.Collections; +import org.junit.jupiter.api.Test; + +class StartSessionOperatorActionCodecTest { + private static final String VECTOR_RESOURCE = + "/operator/start-session-mutation-digest-v1-vectors.json"; + private static final ObjectMapper JSON = new ObjectMapper(); + + @Test + void matchesSharedActionVectors() throws IOException { + JsonNode vectors = fixture().path("vectors"); + String baseDigest = null; + String changedTargetDigest = null; + String changedScopeDigest = null; + String changedReasonDigest = null; + String composedDigest = null; + String decomposedDigest = null; + String absentClientIpDigest = null; + String emptyClientIpDigest = null; + + for (JsonNode vector : vectors) { + byte[] raw = rawVectorBytes(vector); + String name = vector.path("name").asText(); + if (!vector.path("accepted").asBoolean()) { + assertThatThrownBy(() -> StartSessionOperatorActionCodec.decode(raw)) + .as("vector %s", name) + .isInstanceOf(IllegalArgumentException.class); + continue; + } + + StartSessionOperatorAction action = StartSessionOperatorActionCodec.decode(raw); + byte[] preimage = StartSessionOperatorActionCodec.canonicalPreimage(action); + String digest = StartSessionOperatorActionCodec.mutationDigest(action); + assertThat(hex(preimage)) + .as("preimage for %s", name) + .isEqualTo(vector.path("preimageHex").asText()); + assertThat(digest).as("digest for %s", name).isEqualTo(vector.path("digest").asText()); + switch (name) { + case "base" -> baseDigest = digest; + case "changed-target" -> changedTargetDigest = digest; + case "changed-scope" -> changedScopeDigest = digest; + case "changed-audit-reason" -> changedReasonDigest = digest; + case "client-ip-absent" -> absentClientIpDigest = digest; + case "client-ip-empty" -> emptyClientIpDigest = digest; + case "unicode-composed" -> composedDigest = digest; + case "unicode-decomposed" -> decomposedDigest = digest; + default -> { + // Individual golden values above prove the remaining mutation vectors. + } + } + } + + assertThat(absentClientIpDigest).isNotEqualTo(emptyClientIpDigest); + assertThat(composedDigest).isEqualTo(decomposedDigest); + assertThat(baseDigest) + .isNotEqualTo(absentClientIpDigest) + .isNotEqualTo(changedTargetDigest) + .isNotEqualTo(changedScopeDigest) + .isNotEqualTo(changedReasonDigest); + } + + @Test + void matchesSharedGenericValueGrammarVectors() throws IOException { + java.util.Map encodings = new java.util.HashMap<>(); + for (JsonNode vector : fixture().path("grammarVectors")) { + String name = vector.path("name").asText(); + String kind = vector.path("kind").asText(); + if ("numberLexeme".equals(kind)) { + String rawLexeme = vector.path("rawLexeme").asText(); + if (!vector.path("accepted").asBoolean()) { + assertThatThrownBy( + () -> StartSessionOperatorActionCodec.canonicalNumberLexemeForTest(rawLexeme)) + .as("numeric lexeme vector %s", name) + .isInstanceOf(IllegalArgumentException.class); + continue; + } + String encoded = + hex(StartSessionOperatorActionCodec.canonicalNumberLexemeForTest(rawLexeme)); + assertThat(encoded) + .as("numeric lexeme vector %s", name) + .isEqualTo(vector.path("canonicalValueHex").asText()); + encodings.put(name, encoded); + continue; + } + if ("reject".equals(kind)) { + byte[] raw = vector.path("rawValue").asText().getBytes(StandardCharsets.UTF_8); + assertThatThrownBy(() -> StartSessionOperatorActionCodec.canonicalGrammarValueForTest(raw)) + .as("grammar vector %s", name) + .isInstanceOf(IllegalArgumentException.class); + continue; + } + + byte[] encoded; + if ("absent".equals(kind)) { + encoded = StartSessionOperatorActionCodec.absentGrammarValueForTest(); + } else { + byte[] raw = vector.path("rawValue").asText().getBytes(StandardCharsets.UTF_8); + encoded = StartSessionOperatorActionCodec.canonicalGrammarValueForTest(raw); + } + String encodedHex = hex(encoded); + assertThat(encodedHex) + .as("canonical value for %s", name) + .isEqualTo(vector.path("canonicalValueHex").asText()); + encodings.put(name, encodedHex); + } + + assertThat(encodings.get("absent")).isNotEqualTo(encodings.get("null")); + assertThat(encodings.get("number-one")).isNotEqualTo(encodings.get("string-one")); + assertThat(encodings.get("number-signed-zero")).isEqualTo(encodings.get("number-zero")); + assertThat(encodings.get("unicode-key-composed")) + .isEqualTo(encodings.get("unicode-key-decomposed")); + } + + @Test + void exposesOnlyTypedImmutableStartSessionFields() throws IOException { + JsonNode base = findVector("base"); + StartSessionOperatorAction action = + StartSessionOperatorActionCodec.decode(rawVectorBytes(base)); + + assertThat(StartSessionOperatorAction.OWNER_SERVICE).isEqualTo("game-session-service"); + assertThat(action.targetOwner()).isEqualTo("game-session-service"); + assertThat(action.actionFamilySchemaId()).isEqualTo("firemud.game-session.start-session"); + assertThat(action.actionFamilySchemaVersion()).isEqualTo("1"); + assertThat(action.expectedVersion()) + .isEqualTo(StartSessionOperatorAction.ExpectedVersion.ABSENT); + assertThat(action.scope().tenantId().toString()) + .isEqualTo("22222222-2222-4222-8222-222222222222"); + assertThat(action.target().gameTemplateId()).isEqualTo(42L); + assertThat(action.mutation().clientIp()) + .isInstanceOf(StartSessionOperatorAction.StringClientIp.class); + assertThat(action.auditReason()).isEqualTo("scheduled launch"); + } + + @Test + void rejectsRawUtf8AndActionSpecificOversizeInputs() throws IOException { + assertThatThrownBy( + () -> + StartSessionOperatorActionCodec.decode( + new byte[] {'{', '"', (byte) 0xff, '"', ':', '1', '}'})) + .isInstanceOf(IllegalArgumentException.class); + + byte[] oversizedRaw = new byte[StartSessionOperatorActionCodec.MAX_RAW_BYTES + 1]; + assertThatThrownBy(() -> StartSessionOperatorActionCodec.decode(oversizedRaw)) + .isInstanceOf(IllegalArgumentException.class); + + String base = findVector("base").path("input").asText(); + String oversizedReason = base.replace("scheduled launch", "x".repeat(1_001)); + assertThatThrownBy( + () -> + StartSessionOperatorActionCodec.decode( + oversizedReason.getBytes(StandardCharsets.UTF_8))) + .isInstanceOf(IllegalArgumentException.class); + + String oversizedClientIp = base.replace("192.0.2.1", "x".repeat(129)); + assertThatThrownBy( + () -> + StartSessionOperatorActionCodec.decode( + oversizedClientIp.getBytes(StandardCharsets.UTF_8))) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void rejectsObjectMemberAndArrayElementLimitViolations() { + String tooManyMembers = "{" + String.join(",", Collections.nCopies(17, "\"k\":0")) + "}"; + assertThatThrownBy( + () -> + StartSessionOperatorActionCodec.canonicalGrammarValueForTest( + tooManyMembers.getBytes(StandardCharsets.UTF_8))) + .isInstanceOf(IllegalArgumentException.class); + + String tooManyElements = "[" + String.join(",", Collections.nCopies(65, "0")) + "]"; + assertThatThrownBy( + () -> + StartSessionOperatorActionCodec.canonicalGrammarValueForTest( + tooManyElements.getBytes(StandardCharsets.UTF_8))) + .isInstanceOf(IllegalArgumentException.class); + + String tooDeep = "[".repeat(9) + "0" + "]".repeat(9); + assertThatThrownBy( + () -> + StartSessionOperatorActionCodec.canonicalGrammarValueForTest( + tooDeep.getBytes(StandardCharsets.UTF_8))) + .isInstanceOf(IllegalArgumentException.class); + } + + private static JsonNode fixture() throws IOException { + try (InputStream stream = + StartSessionOperatorActionCodecTest.class.getResourceAsStream(VECTOR_RESOURCE)) { + if (stream == null) { + throw new IOException("missing shared StartSession digest vector resource"); + } + return JSON.readTree(stream); + } + } + + private static JsonNode findVector(String name) throws IOException { + for (JsonNode vector : fixture().path("vectors")) { + if (name.equals(vector.path("name").asText())) { + return vector; + } + } + throw new IOException("missing vector: " + name); + } + + private static byte[] rawVectorBytes(JsonNode vector) { + if (vector.has("rawHex")) { + return java.util.HexFormat.of().parseHex(vector.path("rawHex").asText()); + } + return vector.path("input").asText().getBytes(StandardCharsets.UTF_8); + } + + private static String hex(byte[] bytes) { + return java.util.HexFormat.of().formatHex(bytes); + } +} diff --git a/services/common-platform-core/src/test/resources/operator/start-session-mutation-digest-v1-vectors.json b/services/common-platform-core/src/test/resources/operator/start-session-mutation-digest-v1-vectors.json new file mode 100644 index 0000000000..a1874220fa --- /dev/null +++ b/services/common-platform-core/src/test/resources/operator/start-session-mutation-digest-v1-vectors.json @@ -0,0 +1,167 @@ +{ + "schemaId": "firemud.game-session.start-session", + "schemaVersion": "1", + "vectors": [ + { + "name": "base", + "accepted": true, + "input": "{\"actionFamilySchemaId\":\"firemud.game-session.start-session\",\"actionFamilySchemaVersion\":\"1\",\"scope\":{\"tenantId\":\"22222222-2222-4222-8222-222222222222\",\"targetNamespace\":\"firemud\"},\"target\":{\"gameTemplateId\":\"42\",\"ownerAccountId\":\"33333333-3333-4333-8333-333333333333\"},\"mutation\":{\"clientIp\":\"192.0.2.1\"},\"auditReason\":\"scheduled launch\"}", + "preimageHex": "31373a6d75746174696f6e4469676573742f763132303a616374696f6e46616d696c79536368656d614964363a737472696e673133343a666972656d75642e67616d652d73657373696f6e2e73746172742d73657373696f6e32353a616374696f6e46616d696c79536368656d6156657273696f6e363a737472696e6731313a31353a73636f7065363a6f626a6563743139373a313a32383a74656e616e744964363a737472696e673133363a32323232323232322d323232322d343232322d383232322d32323232323232323232323231353a7461726765744e616d657370616365363a737472696e6731373a666972656d7564363a746172676574363a6f626a6563743139383a313a3231343a67616d6554656d706c6174654964363a737472696e6731323a343231343a6f776e65724163636f756e744964363a737472696e673133363a33333333333333332d333333332d343333332d383333332d33333333333333333333333331353a657870656374656456657273696f6e363a616273656e7430303a383a6d75746174696f6e363a6f626a6563743133333a313a31383a636c69656e744970363a737472696e6731393a3139322e302e322e3131313a6175646974526561736f6e363a737472696e673131363a7363686564756c6564206c61756e6368", + "digest": "f81e35e943d51078a1d1c5eb7f3175bedbd7e704f55fe7b450050b852dd62e29" + }, + { + "name": "changed-target", + "accepted": true, + "input": "{\"actionFamilySchemaId\":\"firemud.game-session.start-session\",\"actionFamilySchemaVersion\":\"1\",\"scope\":{\"tenantId\":\"22222222-2222-4222-8222-222222222222\",\"targetNamespace\":\"firemud\"},\"target\":{\"gameTemplateId\":\"43\",\"ownerAccountId\":\"33333333-3333-4333-8333-333333333333\"},\"mutation\":{\"clientIp\":\"192.0.2.1\"},\"auditReason\":\"scheduled launch\"}", + "preimageHex": "31373a6d75746174696f6e4469676573742f763132303a616374696f6e46616d696c79536368656d614964363a737472696e673133343a666972656d75642e67616d652d73657373696f6e2e73746172742d73657373696f6e32353a616374696f6e46616d696c79536368656d6156657273696f6e363a737472696e6731313a31353a73636f7065363a6f626a6563743139373a313a32383a74656e616e744964363a737472696e673133363a32323232323232322d323232322d343232322d383232322d32323232323232323232323231353a7461726765744e616d657370616365363a737472696e6731373a666972656d7564363a746172676574363a6f626a6563743139383a313a3231343a67616d6554656d706c6174654964363a737472696e6731323a343331343a6f776e65724163636f756e744964363a737472696e673133363a33333333333333332d333333332d343333332d383333332d33333333333333333333333331353a657870656374656456657273696f6e363a616273656e7430303a383a6d75746174696f6e363a6f626a6563743133333a313a31383a636c69656e744970363a737472696e6731393a3139322e302e322e3131313a6175646974526561736f6e363a737472696e673131363a7363686564756c6564206c61756e6368", + "digest": "5c736b3aa5c0772f0edef9fbf00a60b585ab99cccf774cb08196f7eb5cca346d" + }, + { + "name": "changed-scope", + "accepted": true, + "input": "{\"actionFamilySchemaId\":\"firemud.game-session.start-session\",\"actionFamilySchemaVersion\":\"1\",\"scope\":{\"tenantId\":\"44444444-4444-4444-8444-444444444444\",\"targetNamespace\":\"firemud\"},\"target\":{\"gameTemplateId\":\"42\",\"ownerAccountId\":\"33333333-3333-4333-8333-333333333333\"},\"mutation\":{\"clientIp\":\"192.0.2.1\"},\"auditReason\":\"scheduled launch\"}", + "preimageHex": "31373a6d75746174696f6e4469676573742f763132303a616374696f6e46616d696c79536368656d614964363a737472696e673133343a666972656d75642e67616d652d73657373696f6e2e73746172742d73657373696f6e32353a616374696f6e46616d696c79536368656d6156657273696f6e363a737472696e6731313a31353a73636f7065363a6f626a6563743139373a313a32383a74656e616e744964363a737472696e673133363a34343434343434342d343434342d343434342d383434342d34343434343434343434343431353a7461726765744e616d657370616365363a737472696e6731373a666972656d7564363a746172676574363a6f626a6563743139383a313a3231343a67616d6554656d706c6174654964363a737472696e6731323a343231343a6f776e65724163636f756e744964363a737472696e673133363a33333333333333332d333333332d343333332d383333332d33333333333333333333333331353a657870656374656456657273696f6e363a616273656e7430303a383a6d75746174696f6e363a6f626a6563743133333a313a31383a636c69656e744970363a737472696e6731393a3139322e302e322e3131313a6175646974526561736f6e363a737472696e673131363a7363686564756c6564206c61756e6368", + "digest": "cdb171f110e99654085d935f9dd0c9d0dd46877272976080b01f84320ec45008" + }, + { + "name": "changed-audit-reason", + "accepted": true, + "input": "{\"actionFamilySchemaId\":\"firemud.game-session.start-session\",\"actionFamilySchemaVersion\":\"1\",\"scope\":{\"tenantId\":\"22222222-2222-4222-8222-222222222222\",\"targetNamespace\":\"firemud\"},\"target\":{\"gameTemplateId\":\"42\",\"ownerAccountId\":\"33333333-3333-4333-8333-333333333333\"},\"mutation\":{\"clientIp\":\"192.0.2.1\"},\"auditReason\":\"operator launch\"}", + "preimageHex": "31373a6d75746174696f6e4469676573742f763132303a616374696f6e46616d696c79536368656d614964363a737472696e673133343a666972656d75642e67616d652d73657373696f6e2e73746172742d73657373696f6e32353a616374696f6e46616d696c79536368656d6156657273696f6e363a737472696e6731313a31353a73636f7065363a6f626a6563743139373a313a32383a74656e616e744964363a737472696e673133363a32323232323232322d323232322d343232322d383232322d32323232323232323232323231353a7461726765744e616d657370616365363a737472696e6731373a666972656d7564363a746172676574363a6f626a6563743139383a313a3231343a67616d6554656d706c6174654964363a737472696e6731323a343231343a6f776e65724163636f756e744964363a737472696e673133363a33333333333333332d333333332d343333332d383333332d33333333333333333333333331353a657870656374656456657273696f6e363a616273656e7430303a383a6d75746174696f6e363a6f626a6563743133333a313a31383a636c69656e744970363a737472696e6731393a3139322e302e322e3131313a6175646974526561736f6e363a737472696e673131353a6f70657261746f72206c61756e6368", + "digest": "43ac8a4e4c8618c090ed7cd298a223e42dffca4519c7a1c38509b8cc1eb16867" + }, + { + "name": "client-ip-absent", + "accepted": true, + "input": "{\"actionFamilySchemaId\":\"firemud.game-session.start-session\",\"actionFamilySchemaVersion\":\"1\",\"scope\":{\"tenantId\":\"22222222-2222-4222-8222-222222222222\",\"targetNamespace\":\"firemud\"},\"target\":{\"gameTemplateId\":\"42\",\"ownerAccountId\":\"33333333-3333-4333-8333-333333333333\"},\"mutation\":{},\"auditReason\":\"scheduled launch\"}", + "preimageHex": "31373a6d75746174696f6e4469676573742f763132303a616374696f6e46616d696c79536368656d614964363a737472696e673133343a666972656d75642e67616d652d73657373696f6e2e73746172742d73657373696f6e32353a616374696f6e46616d696c79536368656d6156657273696f6e363a737472696e6731313a31353a73636f7065363a6f626a6563743139373a313a32383a74656e616e744964363a737472696e673133363a32323232323232322d323232322d343232322d383232322d32323232323232323232323231353a7461726765744e616d657370616365363a737472696e6731373a666972656d7564363a746172676574363a6f626a6563743139383a313a3231343a67616d6554656d706c6174654964363a737472696e6731323a343231343a6f776e65724163636f756e744964363a737472696e673133363a33333333333333332d333333332d343333332d383333332d33333333333333333333333331353a657870656374656456657273696f6e363a616273656e7430303a383a6d75746174696f6e363a6f626a6563743132343a313a31383a636c69656e744970363a616273656e7430303a31313a6175646974526561736f6e363a737472696e673131363a7363686564756c6564206c61756e6368", + "digest": "01b67879242b7213c9dd9dafbed8a4ed5cbec72ba671d9a04c263bf3b52e3195" + }, + { + "name": "client-ip-empty", + "accepted": true, + "input": "{\"actionFamilySchemaId\":\"firemud.game-session.start-session\",\"actionFamilySchemaVersion\":\"1\",\"scope\":{\"tenantId\":\"22222222-2222-4222-8222-222222222222\",\"targetNamespace\":\"firemud\"},\"target\":{\"gameTemplateId\":\"42\",\"ownerAccountId\":\"33333333-3333-4333-8333-333333333333\"},\"mutation\":{\"clientIp\":\"\"},\"auditReason\":\"scheduled launch\"}", + "preimageHex": "31373a6d75746174696f6e4469676573742f763132303a616374696f6e46616d696c79536368656d614964363a737472696e673133343a666972656d75642e67616d652d73657373696f6e2e73746172742d73657373696f6e32353a616374696f6e46616d696c79536368656d6156657273696f6e363a737472696e6731313a31353a73636f7065363a6f626a6563743139373a313a32383a74656e616e744964363a737472696e673133363a32323232323232322d323232322d343232322d383232322d32323232323232323232323231353a7461726765744e616d657370616365363a737472696e6731373a666972656d7564363a746172676574363a6f626a6563743139383a313a3231343a67616d6554656d706c6174654964363a737472696e6731323a343231343a6f776e65724163636f756e744964363a737472696e673133363a33333333333333332d333333332d343333332d383333332d33333333333333333333333331353a657870656374656456657273696f6e363a616273656e7430303a383a6d75746174696f6e363a6f626a6563743132343a313a31383a636c69656e744970363a737472696e6731303a31313a6175646974526561736f6e363a737472696e673131363a7363686564756c6564206c61756e6368", + "digest": "880d0f5718ce3f1150d559b6e1df62bbe22249cfb95774b3040715be29966ec1" + }, + { + "name": "unicode-composed", + "accepted": true, + "input": "{\"actionFamilySchemaId\":\"firemud.game-session.start-session\",\"actionFamilySchemaVersion\":\"1\",\"scope\":{\"tenantId\":\"22222222-2222-4222-8222-222222222222\",\"targetNamespace\":\"firemud\"},\"target\":{\"gameTemplateId\":\"42\",\"ownerAccountId\":\"33333333-3333-4333-8333-333333333333\"},\"mutation\":{\"clientIp\":\"192.0.2.1\"},\"auditReason\":\"caf\\u00e9 launch\"}", + "preimageHex": "31373a6d75746174696f6e4469676573742f763132303a616374696f6e46616d696c79536368656d614964363a737472696e673133343a666972656d75642e67616d652d73657373696f6e2e73746172742d73657373696f6e32353a616374696f6e46616d696c79536368656d6156657273696f6e363a737472696e6731313a31353a73636f7065363a6f626a6563743139373a313a32383a74656e616e744964363a737472696e673133363a32323232323232322d323232322d343232322d383232322d32323232323232323232323231353a7461726765744e616d657370616365363a737472696e6731373a666972656d7564363a746172676574363a6f626a6563743139383a313a3231343a67616d6554656d706c6174654964363a737472696e6731323a343231343a6f776e65724163636f756e744964363a737472696e673133363a33333333333333332d333333332d343333332d383333332d33333333333333333333333331353a657870656374656456657273696f6e363a616273656e7430303a383a6d75746174696f6e363a6f626a6563743133333a313a31383a636c69656e744970363a737472696e6731393a3139322e302e322e3131313a6175646974526561736f6e363a737472696e673131323a636166c3a9206c61756e6368", + "digest": "7dd8d54b05c485e62d580b1b31bbdc0d6e5634d0caaf234a643d1cc46a5dab09" + }, + { + "name": "unicode-decomposed", + "accepted": true, + "input": "{\"actionFamilySchemaId\":\"firemud.game-session.start-session\",\"actionFamilySchemaVersion\":\"1\",\"scope\":{\"tenantId\":\"22222222-2222-4222-8222-222222222222\",\"targetNamespace\":\"firemud\"},\"target\":{\"gameTemplateId\":\"42\",\"ownerAccountId\":\"33333333-3333-4333-8333-333333333333\"},\"mutation\":{\"clientIp\":\"192.0.2.1\"},\"auditReason\":\"cafe\\u0301 launch\"}", + "preimageHex": "31373a6d75746174696f6e4469676573742f763132303a616374696f6e46616d696c79536368656d614964363a737472696e673133343a666972656d75642e67616d652d73657373696f6e2e73746172742d73657373696f6e32353a616374696f6e46616d696c79536368656d6156657273696f6e363a737472696e6731313a31353a73636f7065363a6f626a6563743139373a313a32383a74656e616e744964363a737472696e673133363a32323232323232322d323232322d343232322d383232322d32323232323232323232323231353a7461726765744e616d657370616365363a737472696e6731373a666972656d7564363a746172676574363a6f626a6563743139383a313a3231343a67616d6554656d706c6174654964363a737472696e6731323a343231343a6f776e65724163636f756e744964363a737472696e673133363a33333333333333332d333333332d343333332d383333332d33333333333333333333333331353a657870656374656456657273696f6e363a616273656e7430303a383a6d75746174696f6e363a6f626a6563743133333a313a31383a636c69656e744970363a737472696e6731393a3139322e302e322e3131313a6175646974526561736f6e363a737472696e673131323a636166c3a9206c61756e6368", + "digest": "7dd8d54b05c485e62d580b1b31bbdc0d6e5634d0caaf234a643d1cc46a5dab09" + }, + { + "name": "client-ip-null", + "accepted": false, + "input": "{\"actionFamilySchemaId\":\"firemud.game-session.start-session\",\"actionFamilySchemaVersion\":\"1\",\"scope\":{\"tenantId\":\"22222222-2222-4222-8222-222222222222\",\"targetNamespace\":\"firemud\"},\"target\":{\"gameTemplateId\":\"42\",\"ownerAccountId\":\"33333333-3333-4333-8333-333333333333\"},\"mutation\":{\"clientIp\":null},\"auditReason\":\"scheduled launch\"}" + }, + { + "name": "expected-version-null", + "accepted": false, + "input": "{\"actionFamilySchemaId\":\"firemud.game-session.start-session\",\"actionFamilySchemaVersion\":\"1\",\"scope\":{\"tenantId\":\"22222222-2222-4222-8222-222222222222\",\"targetNamespace\":\"firemud\"},\"target\":{\"gameTemplateId\":\"42\",\"ownerAccountId\":\"33333333-3333-4333-8333-333333333333\"},\"expectedVersion\":null,\"mutation\":{\"clientIp\":\"192.0.2.1\"},\"auditReason\":\"scheduled launch\"}" + }, + { + "name": "expected-version-present", + "accepted": false, + "input": "{\"actionFamilySchemaId\":\"firemud.game-session.start-session\",\"actionFamilySchemaVersion\":\"1\",\"scope\":{\"tenantId\":\"22222222-2222-4222-8222-222222222222\",\"targetNamespace\":\"firemud\"},\"target\":{\"gameTemplateId\":\"42\",\"ownerAccountId\":\"33333333-3333-4333-8333-333333333333\"},\"expectedVersion\":1,\"mutation\":{\"clientIp\":\"192.0.2.1\"},\"auditReason\":\"scheduled launch\"}" + }, + { + "name": "wrong-type-client-ip", + "accepted": false, + "input": "{\"actionFamilySchemaId\":\"firemud.game-session.start-session\",\"actionFamilySchemaVersion\":\"1\",\"scope\":{\"tenantId\":\"22222222-2222-4222-8222-222222222222\",\"targetNamespace\":\"firemud\"},\"target\":{\"gameTemplateId\":\"42\",\"ownerAccountId\":\"33333333-3333-4333-8333-333333333333\"},\"mutation\":{\"clientIp\":7},\"auditReason\":\"scheduled launch\"}" + }, + { + "name": "duplicate-root-key", + "accepted": false, + "input": "{\"actionFamilySchemaId\":\"firemud.game-session.start-session\",\"actionFamilySchemaId\":\"firemud.game-session.start-session\",\"actionFamilySchemaVersion\":\"1\",\"scope\":{\"tenantId\":\"22222222-2222-4222-8222-222222222222\",\"targetNamespace\":\"firemud\"},\"target\":{\"gameTemplateId\":\"42\",\"ownerAccountId\":\"33333333-3333-4333-8333-333333333333\"},\"mutation\":{},\"auditReason\":\"scheduled launch\"}" + }, + { + "name": "normalized-key-collision", + "accepted": false, + "input": "{\"actionFamilySchemaId\":\"firemud.game-session.start-session\",\"actionFamilySchemaVersion\":\"1\",\"scope\":{\"tenantId\":\"22222222-2222-4222-8222-222222222222\",\"targetNamespace\":\"firemud\"},\"target\":{\"gameTemplateId\":\"42\",\"ownerAccountId\":\"33333333-3333-4333-8333-333333333333\"},\"mutation\":{\"t\\u00e9\":\"x\",\"te\\u0301\":\"y\"},\"auditReason\":\"scheduled launch\"}" + }, + { + "name": "unknown-member", + "accepted": false, + "input": "{\"actionFamilySchemaId\":\"firemud.game-session.start-session\",\"actionFamilySchemaVersion\":\"1\",\"scope\":{\"tenantId\":\"22222222-2222-4222-8222-222222222222\",\"targetNamespace\":\"firemud\"},\"target\":{\"gameTemplateId\":\"42\",\"ownerAccountId\":\"33333333-3333-4333-8333-333333333333\"},\"mutation\":{\"clientIp\":\"192.0.2.1\",\"extra\":true},\"auditReason\":\"scheduled launch\"}" + }, + { + "name": "missing-audit-reason", + "accepted": false, + "input": "{\"actionFamilySchemaId\":\"firemud.game-session.start-session\",\"actionFamilySchemaVersion\":\"1\",\"scope\":{\"tenantId\":\"22222222-2222-4222-8222-222222222222\",\"targetNamespace\":\"firemud\"},\"target\":{\"gameTemplateId\":\"42\",\"ownerAccountId\":\"33333333-3333-4333-8333-333333333333\"},\"mutation\":{}}" + }, + { + "name": "wrong-scope-member-order", + "accepted": false, + "input": "{\"actionFamilySchemaId\":\"firemud.game-session.start-session\",\"actionFamilySchemaVersion\":\"1\",\"scope\":{\"targetNamespace\":\"firemud\",\"tenantId\":\"22222222-2222-4222-8222-222222222222\"},\"target\":{\"gameTemplateId\":\"42\",\"ownerAccountId\":\"33333333-3333-4333-8333-333333333333\"},\"mutation\":{},\"auditReason\":\"scheduled launch\"}" + }, + { + "name": "malformed-unicode", + "accepted": false, + "input": "{\"actionFamilySchemaId\":\"firemud.game-session.start-session\",\"actionFamilySchemaVersion\":\"1\",\"scope\":{\"tenantId\":\"22222222-2222-4222-8222-222222222222\",\"targetNamespace\":\"firemud\"},\"target\":{\"gameTemplateId\":\"42\",\"ownerAccountId\":\"33333333-3333-4333-8333-333333333333\"},\"mutation\":{},\"auditReason\":\"\\uD800\"}" + }, + { + "name": "invalid-utf8", + "accepted": false, + "rawHex": "7b22616374696f6e46616d696c79536368656d614964223a22666972656d75642e67616d652d73657373696f6e2e73746172742d73657373696f6e222c22616374696f6e46616d696c79536368656d6156657273696f6e223a2231222c2273636f7065223a7b2274656e616e744964223a2232323232323232322d323232322d343232322d383232322d323232323232323232323232222c227461726765744e616d657370616365223a22666972656d7564227d2c22746172676574223a7b2267616d6554656d706c6174654964223a223432222c226f776e65724163636f756e744964223a2233333333333333332d333333332d343333332d383333332d333333333333333333333333227d2c226d75746174696f6e223a7b22636c69656e744970223a223139322e302e322e31227d2c226175646974526561736f6e223a22ff227d" + }, + { + "name": "numeric-template-id-rejected", + "accepted": false, + "input": "{\"actionFamilySchemaId\":\"firemud.game-session.start-session\",\"actionFamilySchemaVersion\":\"1\",\"scope\":{\"tenantId\":\"22222222-2222-4222-8222-222222222222\",\"targetNamespace\":\"firemud\"},\"target\":{\"gameTemplateId\":42,\"ownerAccountId\":\"33333333-3333-4333-8333-333333333333\"},\"mutation\":{},\"auditReason\":\"scheduled launch\"}" + }, + { + "name": "non-canonical-template-id-string", + "accepted": false, + "input": "{\"actionFamilySchemaId\":\"firemud.game-session.start-session\",\"actionFamilySchemaVersion\":\"1\",\"scope\":{\"tenantId\":\"22222222-2222-4222-8222-222222222222\",\"targetNamespace\":\"firemud\"},\"target\":{\"gameTemplateId\":\"042\",\"ownerAccountId\":\"33333333-3333-4333-8333-333333333333\"},\"mutation\":{},\"auditReason\":\"scheduled launch\"}" + }, + { + "name": "template-id-overflow-rejected", + "accepted": false, + "input": "{\"actionFamilySchemaId\":\"firemud.game-session.start-session\",\"actionFamilySchemaVersion\":\"1\",\"scope\":{\"tenantId\":\"22222222-2222-4222-8222-222222222222\",\"targetNamespace\":\"firemud\"},\"target\":{\"gameTemplateId\":\"9223372036854775808\",\"ownerAccountId\":\"33333333-3333-4333-8333-333333333333\"},\"mutation\":{},\"auditReason\":\"scheduled launch\"}" + }, + { + "name": "nil-owner-account-id", + "accepted": false, + "input": "{\"actionFamilySchemaId\":\"firemud.game-session.start-session\",\"actionFamilySchemaVersion\":\"1\",\"scope\":{\"tenantId\":\"22222222-2222-4222-8222-222222222222\",\"targetNamespace\":\"firemud\"},\"target\":{\"gameTemplateId\":\"42\",\"ownerAccountId\":\"00000000-0000-0000-0000-000000000000\"},\"mutation\":{},\"auditReason\":\"scheduled launch\"}" + } + ], + "grammarVectors": [ + {"name": "absent", "kind": "absent", "canonicalValueHex": "363a616273656e7430303a"}, + {"name": "null", "kind": "raw", "rawValue": "null", "canonicalValueHex": "343a6e756c6c31303a"}, + {"name": "number-one", "kind": "raw", "rawValue": "1", "canonicalValueHex": "363a6e756d62657231313a31"}, + {"name": "string-one", "kind": "raw", "rawValue": "\"1\"", "canonicalValueHex": "363a737472696e6731313a31"}, + {"name": "number-ten-trailing-zeroes", "kind": "raw", "rawValue": "10.000", "canonicalValueHex": "363a6e756d62657231323a3130"}, + {"name": "number-negative-decimal", "kind": "raw", "rawValue": "-12.3400", "canonicalValueHex": "363a6e756d62657231363a2d31322e3334"}, + {"name": "number-signed-zero", "kind": "raw", "rawValue": "-0.00", "canonicalValueHex": "363a6e756d62657231313a30"}, + {"name": "number-zero", "kind": "raw", "rawValue": "0", "canonicalValueHex": "363a6e756d62657231313a30"}, + {"name": "array-order", "kind": "raw", "rawValue": "[1,\"1\",null]", "canonicalValueHex": "353a61727261793133363a313a33363a6e756d62657231313a31363a737472696e6731313a31343a6e756c6c31303a"}, + {"name": "unicode-key-composed", "kind": "raw", "rawValue": "{\"\\u00e9\":\"x\"}", "canonicalValueHex": "363a6f626a6563743131393a313a31323ac3a9363a737472696e6731313a78"}, + {"name": "unicode-key-decomposed", "kind": "raw", "rawValue": "{\"e\\u0301\":\"x\"}", "canonicalValueHex": "363a6f626a6563743131393a313a31323ac3a9363a737472696e6731313a78"}, + {"name": "malformed-surrogate-rejected", "kind": "reject", "rawValue": "\"\\uD800\""}, + {"name": "nesting-depth-rejected", "kind": "reject", "rawValue": "[[[[[[[[[0]]]]]]]]]"}, + {"name": "duplicate-object-key-rejected", "kind": "reject", "rawValue": "{\"a\":1,\"a\":2}"}, + {"name": "normalized-object-key-collision-rejected", "kind": "reject", "rawValue": "{\"\\u00e9\":1,\"e\\u0301\":2}"}, + {"name": "number-space-prefix-rejected", "kind": "numberLexeme", "accepted": false, "rawLexeme": " 1"}, + {"name": "number-space-suffix-rejected", "kind": "numberLexeme", "accepted": false, "rawLexeme": "1 "}, + {"name": "number-trailing-point-rejected", "kind": "numberLexeme", "accepted": false, "rawLexeme": "1."}, + {"name": "number-leading-point-rejected", "kind": "numberLexeme", "accepted": false, "rawLexeme": ".5"}, + {"name": "number-nan-rejected", "kind": "numberLexeme", "accepted": false, "rawLexeme": "NaN"}, + {"name": "number-infinity-rejected", "kind": "numberLexeme", "accepted": false, "rawLexeme": "Infinity"}, + {"name": "number-negative-infinity-rejected", "kind": "numberLexeme", "accepted": false, "rawLexeme": "-Infinity"}, + {"name": "number-exponent-lexeme-rejected", "kind": "numberLexeme", "accepted": false, "rawLexeme": "1e3"}, + {"name": "number-plus-lexeme-rejected", "kind": "numberLexeme", "accepted": false, "rawLexeme": "+1"}, + {"name": "number-leading-zero-lexeme-rejected", "kind": "numberLexeme", "accepted": false, "rawLexeme": "01"}, + {"name": "number-exponent-rejected", "kind": "reject", "rawValue": "1e3"}, + {"name": "number-plus-rejected", "kind": "reject", "rawValue": "+1"}, + {"name": "number-leading-zero-rejected", "kind": "reject", "rawValue": "01"} + ] +} From ef22087afdd2b67ecc63b4cd01a2ec70b8a33dcc Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 19:01:17 +1300 Subject: [PATCH 2/3] feat: preserve committed Account actor proof and StartSession reservation --- .../start-session-action-schema.md | 4 + .../platform-operations-and-delivery.md | 2 + services/account-service/build.gradle.kts | 1 + .../config/AccountJwtJwksApiBinding.java | 1260 +++++ .../AccountJwtReadinessTrustBinding.java | 480 ++ ...ountJwtSignerMaterializerTrustBinding.java | 404 ++ .../AccountJwtValidatorInventoryBinding.java | 842 ++++ ...tControlUiCommittedIssuanceRepository.java | 280 ++ ...ountGameplayDelegationPendingIdentity.java | 36 + .../AccountJwtJwksPublicationRepository.java | 1315 +++++ .../AccountJwtReadinessProbeRepository.java | 4246 +++++++++++++++++ ...ccountJwtSignerDesiredStateRepository.java | 4178 ++++++++++++++++ ...ccountJwtValidatorInventoryRepository.java | 280 ++ .../AccountControlUiCurrentActorVerifier.java | 848 ++++ .../AccountControlUiRegistryReader.java | 212 + ...tCoordinationPinnedConnectionProvider.java | 14 + .../AccountJwtJwksConfigMapClient.java | 704 +++ .../session/AccountJwtJwksTrustedSource.java | 761 +++ ...AccountJwtReadinessProbeOwnerSelector.java | 165 + ...untJwtReadinessReceiverInvocationPort.java | 593 +++ .../AccountJwtValidatorInventorySource.java | 1290 +++++ .../AccountMountedJwtSignerBundle.java | 1269 +++++ ..._account_jwt_readiness_per_pod_closure.sql | 777 +++ ...t_jwt_signer_promotion_receipt_binding.sql | 126 + .../V41__account_jwt_signer_desired_state.sql | 405 ++ ...nt_jwt_signer_materialization_readback.sql | 327 ++ .../V43__account_jwt_jwks_prepublication.sql | 600 +++ .../V45__account_jwt_readiness_probes.sql | 466 ++ ...account_jwt_signer_promotion_lifecycle.sql | 570 +++ ...t_jwt_readiness_single_delivery_claims.sql | 125 + ...ount_jwt_validator_inventory_snapshots.sql | 67 + ..._account_control_ui_committed_issuance.sql | 119 + ...ttedIssuanceRepositoryIntegrationTest.java | 595 +++ .../AccountJwtJwksApiTransportTest.java | 772 +++ ...countJwtJwksPublicationRepositoryTest.java | 226 + ...ccountJwtReadinessProbeRepositoryTest.java | 133 + ...ntJwtSignerDesiredStateRepositoryTest.java | 748 +++ ...ountControlUiCurrentActorVerifierTest.java | 890 ++++ .../AccountControlUiRegistryReaderTest.java | 160 + .../AccountJwtJwksConfigMapClientTest.java | 591 +++ .../AccountJwtJwksTrustedSourceTest.java | 677 +++ ...ssionPreAuthorizationReservationTuple.java | 381 ++ ...nPreAuthorizationReservationTupleTest.java | 134 + .../ControlUiJwtProfileValidator.java | 102 + ...essionAccountDelegationRegistryRecord.java | 891 ++++ .../PlayerBootstrapJwtProfileValidator.java | 39 + .../ControlUiJwtProfileValidatorTest.java | 219 + ...ionPreAuthorizationReservationService.java | 360 ++ ...ssionPreAuthorizationReservationTuple.java | 139 + ...PreAuthorizationReservationRepository.java | 415 ++ ...session_pre_authorization_reservations.sql | 27 + ...ionReservationPostgresIntegrationTest.java | 252 + ...reAuthorizationReservationServiceTest.java | 164 + ...nPreAuthorizationReservationTupleTest.java | 171 + 54 files changed, 30852 insertions(+) create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountJwtJwksApiBinding.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountJwtReadinessTrustBinding.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountJwtSignerMaterializerTrustBinding.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountJwtValidatorInventoryBinding.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountControlUiCommittedIssuanceRepository.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationPendingIdentity.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtJwksPublicationRepository.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtReadinessProbeRepository.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtSignerDesiredStateRepository.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtValidatorInventoryRepository.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiCurrentActorVerifier.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiRegistryReader.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountCoordinationPinnedConnectionProvider.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksConfigMapClient.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksTrustedSource.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessProbeOwnerSelector.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessReceiverInvocationPort.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtValidatorInventorySource.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountMountedJwtSignerBundle.java create mode 100644 services/account-service/src/main/resources/db/migration/V100__account_jwt_readiness_per_pod_closure.sql create mode 100644 services/account-service/src/main/resources/db/migration/V104__account_jwt_signer_promotion_receipt_binding.sql create mode 100644 services/account-service/src/main/resources/db/migration/V41__account_jwt_signer_desired_state.sql create mode 100644 services/account-service/src/main/resources/db/migration/V42__account_jwt_signer_materialization_readback.sql create mode 100644 services/account-service/src/main/resources/db/migration/V43__account_jwt_jwks_prepublication.sql create mode 100644 services/account-service/src/main/resources/db/migration/V45__account_jwt_readiness_probes.sql create mode 100644 services/account-service/src/main/resources/db/migration/V49__account_jwt_signer_promotion_lifecycle.sql create mode 100644 services/account-service/src/main/resources/db/migration/V50__account_jwt_readiness_single_delivery_claims.sql create mode 100644 services/account-service/src/main/resources/db/migration/V52__account_jwt_validator_inventory_snapshots.sql create mode 100644 services/account-service/src/main/resources/db/migration/V74__account_control_ui_committed_issuance.sql create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountControlUiCommittedIssuanceRepositoryIntegrationTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountJwtJwksApiTransportTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountJwtJwksPublicationRepositoryTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountJwtReadinessProbeRepositoryTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountJwtSignerDesiredStateRepositoryTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiCurrentActorVerifierTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiRegistryReaderTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksConfigMapClientTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksTrustedSourceTest.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/StartSessionPreAuthorizationReservationTuple.java create mode 100644 services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/operator/StartSessionPreAuthorizationReservationTupleTest.java create mode 100644 services/common-security/src/main/java/net/firedevops/firemud/common/security/ControlUiJwtProfileValidator.java create mode 100644 services/common-security/src/main/java/net/firedevops/firemud/common/security/GameSessionAccountDelegationRegistryRecord.java create mode 100644 services/common-security/src/main/java/net/firedevops/firemud/common/security/PlayerBootstrapJwtProfileValidator.java create mode 100644 services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/ControlUiJwtProfileValidatorTest.java create mode 100644 services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/operator/StartSessionPreAuthorizationReservationService.java create mode 100644 services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/operator/StartSessionPreAuthorizationReservationTuple.java create mode 100644 services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/repository/StartSessionPreAuthorizationReservationRepository.java create mode 100644 services/logging-admin-service/src/main/resources/db/migration/V2__start_session_pre_authorization_reservations.sql create mode 100644 services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/StartSessionPreAuthorizationReservationPostgresIntegrationTest.java create mode 100644 services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/operator/StartSessionPreAuthorizationReservationServiceTest.java create mode 100644 services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/operator/StartSessionPreAuthorizationReservationTupleTest.java diff --git a/design/architecture/microservices/game-session-service/start-session-action-schema.md b/design/architecture/microservices/game-session-service/start-session-action-schema.md index b3b3432495..467529e809 100644 --- a/design/architecture/microservices/game-session-service/start-session-action-schema.md +++ b/design/architecture/microservices/game-session-service/start-session-action-schema.md @@ -1,5 +1,9 @@ # StartSession Operator Action Schema +## Implementation status + +The shared typed action, digest codec, and pre-authorization reservation tuple are implemented. Logging & Admin has durable reservation, claim expiry, and read-only recovery-claim seams; Account has read-only verification of existing committed tenant-scoped control-ui issuance against its protected signer/registry and current membership evidence. These are prerequisites, not an executable StartSession route. Account operator-reference issuance/redemption, post-authorization owner handoff, canonical Game Session consumption, and physical cross-service proof remain incomplete. No external route or runtime activation is enabled by this boundary. + ## Normative contract This document defines the StartSession action-family schema `firemud.game-session.start-session`, version `1`, owned by `game-session-service`. It defines the digest input shape for the `StartSession` operator action. It does not make the external operator route routable or establish an authorization decision. diff --git a/design/project-management/implementation-tracking/platform-operations-and-delivery.md b/design/project-management/implementation-tracking/platform-operations-and-delivery.md index 05eba37107..f667aa3b22 100644 --- a/design/project-management/implementation-tracking/platform-operations-and-delivery.md +++ b/design/project-management/implementation-tracking/platform-operations-and-delivery.md @@ -88,6 +88,8 @@ The exact source-run publication handoff is implemented locally in the runtime p ## Operator Write Boundary Status +The StartSession prerequisite now includes the shared action/digest and pre-authorization tuple, Logging & Admin's durable reservation/claim/recovery seams, and Account's read-only current tenant-scoped control-ui actor verification. It does not issue or redeem operator references, forward owner mutations, or provide canonical Game Session execution. The [StartSession schema owner](../../architecture/microservices/game-session-service/start-session-action-schema.md#implementation-status) records this partial boundary; physical reservation/authority integration, owner handoff, and live launch proof remain open. + The tracker separates implemented fail-closed ingress stubs from supported durable operator workflows and the target external ingress contract. Game Session `/sessions*` routes remain internal/owner-local. Logging & Admin feature-flag and scoped tick ingress stubs remain externally unavailable because they do not currently forward and the complete [ADR 0048](../../architecture/decisions/adr-0048-durable-idempotent-operator-write-execution.md) owner-write gate is not implemented or proved. Moderation and appeal implementation status remains owned by the [Logging & Admin moderation policies](../../architecture/microservices/logging-admin-service/moderation-policies.md) contract; quota overrides, broader remediation, external session-lifecycle forwarding, and other unproved owner mutations remain gated or target-only. ## Canonical Design Sources diff --git a/services/account-service/build.gradle.kts b/services/account-service/build.gradle.kts index 1a362013eb..388e86ce55 100644 --- a/services/account-service/build.gradle.kts +++ b/services/account-service/build.gradle.kts @@ -12,6 +12,7 @@ firemudJooq { } dependencies { + implementation("com.fasterxml.jackson.core:jackson-databind") implementation(libs.spring.boot.starter.mail) implementation(libs.argon2) implementation(libs.stripe.java) diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountJwtJwksApiBinding.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountJwtJwksApiBinding.java new file mode 100644 index 0000000000..f92fc8418f --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountJwtJwksApiBinding.java @@ -0,0 +1,1260 @@ +package net.firedevops.firemud.accountservice.config; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.net.IDN; +import java.net.Proxy; +import java.net.ProxySelector; +import java.net.SocketAddress; +import java.net.URI; +import java.net.URLEncoder; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.nio.ByteBuffer; +import java.nio.channels.SeekableByteChannel; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.LinkOption; +import java.nio.file.Path; +import java.nio.file.StandardOpenOption; +import java.nio.file.attribute.BasicFileAttributes; +import java.nio.file.attribute.PosixFilePermission; +import java.security.KeyStore; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.security.cert.Certificate; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.time.Duration; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.concurrent.atomic.AtomicReference; +import java.util.regex.Pattern; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLParameters; +import javax.net.ssl.TrustManagerFactory; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; + +/** + * Independently protected, default-inactive trust for Account's fixed public-JWKS Kubernetes + * ConfigMap calls. This is deliberately not a Spring component: lifecycle wiring must opt in. + */ +public final class AccountJwtJwksApiBinding { + public static final int MAX_BINDING_BYTES = 16 * 1024; + private static final int MAX_CA_BYTES = 128 * 1024; + private static final int MAX_BEARER_BYTES = 16 * 1024; + private static final int MAX_RESPONSE_BYTES = 1024 * 1024; + private static final int MAX_REQUEST_BYTES = 1024 * 1024; + private static final String BINDING_VERSION = "account-jwt-jwks-api-binding/v1"; + private static final String ACCOUNT_SERVICE_ACCOUNT = "account-service"; + private static final Path TRUST_ROOT = Path.of("/etc/firemud/account-jwt-api"); + private static final Path TRUST_BINDING_PATH = TRUST_ROOT.resolve("binding.json"); + private static final Path TRUST_CA_PATH = TRUST_ROOT.resolve("serving-ca.pem"); + + private static final Path TOKEN_ROOT = protectedTokenRoot(); + + private static final Path TOKEN_PATH = TOKEN_ROOT.resolve("token"); + + private static final Path CANONICAL_TOKEN_ROOT = canonicalProjectedTokenRoot(); + + private static final Pattern ENVIRONMENT = + Pattern.compile("[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?"); + private static final Pattern NAMESPACE = ENVIRONMENT; + private static final Pattern CLUSTER = Pattern.compile("[A-Za-z0-9][A-Za-z0-9._:-]{0,127}"); + private static final Pattern REVISION = Pattern.compile("[A-Za-z0-9][A-Za-z0-9._:-]{0,127}"); + private static final Pattern SHA256 = Pattern.compile("[0-9a-f]{64}"); + private static final Pattern UID = + Pattern.compile("[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}"); + private static final Pattern BEARER = Pattern.compile("[!-~]{1,16384}"); + private static final Set CONFIG_FIELDS = + Set.of( + "version", + "enabled", + "configRevision", + "environmentId", + "clusterId", + "apiServerUrl", + "tlsServerName", + "servingCaPath", + "servingCaSha256", + "bearerTokenPath", + "namespace", + "expectedClusterIncarnationUid", + "expectedNamespaceUid", + "expectedApiUsername", + "bindingDigest"); + private static final JsonMapper STRICT_JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + @SuppressFBWarnings( + value = "DMI_HARDCODED_ABSOLUTE_FILENAME", + justification = + "Account's bearer credential is read only from this fixed protected projected-token root.") + private static Path protectedTokenRoot() { + return Path.of("/var/run/secrets/firemud/account-jwt-api-token"); + } + + @SuppressFBWarnings( + value = "DMI_HARDCODED_ABSOLUTE_FILENAME", + justification = + "This exact canonical root remains the only alternate projected-token mount accepted by the protected Account API boundary.") + private static Path canonicalProjectedTokenRoot() { + return Path.of("/run/secrets/firemud/account-jwt-api-token"); + } + + private final boolean enabled; + private final String protectedBindingPath; + private final Duration requestTimeout; + private final ProtectedState testProtectedState; + private final ProtectedPaths protectedPaths; + private final AtomicReference acceptedIdentity = new AtomicReference<>(); + + /** Creates an inert binding. No Spring activation or ambient Kubernetes configuration exists. */ + public AccountJwtJwksApiBinding() { + this(false, ""); + } + + /** + * Creates an explicitly selected binding. The selected file still has to authorize the exact + * Account endpoint, trust anchor, cluster/namespace incarnation, and authenticated principal. + */ + public AccountJwtJwksApiBinding(boolean enabled, String protectedBindingPath) { + this.enabled = enabled; + String configuredPath = protectedBindingPath == null ? "" : protectedBindingPath.trim(); + this.protectedBindingPath = + TRUST_BINDING_PATH.toString().equals(configuredPath) ? configuredPath : ""; + this.requestTimeout = Duration.ofSeconds(8); + this.testProtectedState = null; + this.protectedPaths = + new ProtectedPaths( + TRUST_ROOT, TRUST_BINDING_PATH, TRUST_CA_PATH, TOKEN_ROOT, TOKEN_PATH, false); + } + + private AccountJwtJwksApiBinding(Duration requestTimeout, ProtectedState testProtectedState) { + this.enabled = true; + this.protectedBindingPath = ""; + this.requestTimeout = requestTimeout; + this.testProtectedState = testProtectedState; + this.protectedPaths = null; + } + + private AccountJwtJwksApiBinding(String bindingPath, ProtectedPaths protectedPaths) { + this.enabled = true; + this.protectedBindingPath = bindingPath; + this.requestTimeout = Duration.ofSeconds(8); + this.testProtectedState = null; + this.protectedPaths = protectedPaths; + } + + static AccountJwtJwksApiBinding forProtectedFilesTest( + Path bindingPath, Path trustRoot, Path caPath, Path tokenRoot, Path tokenPath) { + Objects.requireNonNull(bindingPath, "test binding path is required"); + Objects.requireNonNull(trustRoot, "test trust root is required"); + Objects.requireNonNull(caPath, "test CA path is required"); + Objects.requireNonNull(tokenRoot, "test token root is required"); + Objects.requireNonNull(tokenPath, "test token path is required"); + Path normalizedBinding = bindingPath.toAbsolutePath().normalize(); + Path normalizedTrustRoot = trustRoot.toAbsolutePath().normalize(); + Path normalizedCa = caPath.toAbsolutePath().normalize(); + Path normalizedTokenRoot = tokenRoot.toAbsolutePath().normalize(); + Path normalizedToken = tokenPath.toAbsolutePath().normalize(); + if (!normalizedBinding.equals(normalizedTrustRoot.resolve("binding.json")) + || !normalizedCa.equals(normalizedTrustRoot.resolve("serving-ca.pem")) + || !normalizedToken.equals(normalizedTokenRoot.resolve("token"))) { + throw new IllegalArgumentException("Protected Account JWT test paths are invalid"); + } + ProtectedPaths paths = + new ProtectedPaths( + normalizedTrustRoot, + normalizedBinding, + normalizedCa, + normalizedTokenRoot, + normalizedToken, + true); + return new AccountJwtJwksApiBinding(normalizedBinding.toString(), paths); + } + + /** + * Supplies trusted in-memory binding material only to package-local transport tests. It still + * exercises the production pinned-CA HTTPS sender and cannot install a custom HTTP client. + */ + static AccountJwtJwksApiBinding forTransportTest( + ParsedBinding binding, byte[] caBytes, String bearerToken, Duration requestTimeout) { + Objects.requireNonNull(binding, "transport test binding is required"); + Objects.requireNonNull(caBytes, "transport test CA is required"); + Objects.requireNonNull(requestTimeout, "transport test timeout is required"); + if (caBytes.length == 0 + || caBytes.length > MAX_CA_BYTES + || !sha256(caBytes).equals(binding.servingCaSha256()) + || !"https".equalsIgnoreCase(binding.apiServer().getScheme()) + || binding.apiServer().getHost() == null + || !binding.apiServer().getHost().equalsIgnoreCase(binding.tlsServerName()) + || !binding + .expectedApiUsername() + .equals("system:serviceaccount:" + binding.namespace() + ":" + ACCOUNT_SERVICE_ACCOUNT) + || bearerToken == null + || !BEARER.matcher(bearerToken).matches() + || requestTimeout.isZero() + || requestTimeout.isNegative() + || requestTimeout.compareTo(Duration.ofSeconds(8)) > 0) { + throw new IllegalArgumentException("Account JWT JWKS transport test binding is invalid"); + } + byte[] caSnapshot = caBytes.clone(); + Set readOnly = Set.of(PosixFilePermission.OWNER_READ); + FileIdentity bindingIdentity = testFileIdentity("test-binding", new byte[] {1}, readOnly); + FileIdentity caIdentity = testFileIdentity("test-ca", caSnapshot, readOnly); + FileIdentity bearerIdentity = + testFileIdentity( + binding.bearerTokenPath().toString(), + bearerToken.getBytes(StandardCharsets.UTF_8), + readOnly); + TrustIdentity identity = + new TrustIdentity( + bindingIdentity, + caIdentity, + credentialPolicy(bearerIdentity), + binding.bindingDigest(), + ""); + return new AccountJwtJwksApiBinding( + requestTimeout, + new ProtectedState(binding, caSnapshot, bearerToken, identity, bearerIdentity)); + } + + /** Returns non-secret pinned endpoint and identity fields after rechecking protected files. */ + public ParsedBinding current() { + if (!enabled || protectedBindingPath.isBlank()) { + throw new BindingRejectedException(); + } + try { + return acceptCurrentProtectedState().config(); + } catch (BindingRejectedException ex) { + throw ex; + } catch (Exception ex) { + throw new BindingRejectedException(); + } + } + + /** Opens one fixed-endpoint operation with a single bounded bearer snapshot. */ + public ApiOperation beginOperation() { + if (!enabled || protectedBindingPath.isBlank()) { + throw new BindingRejectedException(); + } + try { + return new ApiOperation(acceptCurrentProtectedState()); + } catch (BindingRejectedException ex) { + throw ex; + } catch (Exception ex) { + throw new BindingRejectedException(); + } + } + + private ApiResponse send(ProtectedState credentialSnapshot, ApiCall call, byte[] requestBody) { + return send(credentialSnapshot, call, requestBody, null); + } + + private ApiResponse send( + ProtectedState credentialSnapshot, + ApiCall call, + byte[] requestBody, + String protectedInventoryPath) { + Objects.requireNonNull(call, "Kubernetes API call is required"); + if (!enabled || protectedBindingPath.isBlank() || credentialSnapshot == null) { + throw new BindingRejectedException(); + } + if (requestBody != null && requestBody.length > MAX_REQUEST_BYTES) { + throw new BindingRejectedException(); + } + validateCallBody(call, requestBody); + ProtectedState state = recheckProtectedState(); + TrustIdentity baseline = acceptedIdentity.get(); + if (!baseline.equals(credentialSnapshot.identity()) + || !credentialSnapshot.bearerIdentity().equals(state.bearerIdentity())) { + throw new BindingRejectedException(); + } + + HttpClient client; + try { + client = createHttpClient(credentialSnapshot.caBytes()); + } catch (Exception ex) { + throw new BindingRejectedException(); + } + if ((call == ApiCall.READ_VALIDATOR_DEPLOYMENT + || call == ApiCall.LIST_VALIDATOR_PODS + || call == ApiCall.READ_VALIDATOR_REPLICA_SET) + != (protectedInventoryPath != null)) { + throw new BindingRejectedException(); + } + URI uri = + credentialSnapshot + .config() + .apiServer() + .resolve( + protectedInventoryPath == null + ? call.path(credentialSnapshot.config().namespace()) + : protectedInventoryPath); + HttpRequest.Builder request = + HttpRequest.newBuilder(uri) + .timeout(requestTimeout) + .header("Accept", "application/json") + .header("Authorization", "Bearer " + credentialSnapshot.bearerToken()); + if (call == ApiCall.PATCH_JWKS_CONFIG_MAP) { + request.header("Content-Type", "application/merge-patch+json"); + } else if (call == ApiCall.REVIEW_AUTHENTICATED_PRINCIPAL) { + request.header("Content-Type", "application/json"); + } + if (requestBody == null) { + request.method(call.method(), HttpRequest.BodyPublishers.noBody()); + } else { + request.method(call.method(), HttpRequest.BodyPublishers.ofByteArray(requestBody)); + } + + // Catch changed or withdrawn trust after client construction and immediately before send. + ProtectedState beforeSend = recheckProtectedState(); + if (!baseline.equals(beforeSend.identity()) + || !credentialSnapshot.bearerIdentity().equals(beforeSend.bearerIdentity())) { + throw new BindingRejectedException(); + } + long responseDeadlineNanos = System.nanoTime() + requestTimeout.toNanos(); + try { + HttpResponse response = + client.send(request.build(), HttpResponse.BodyHandlers.ofInputStream()); + try (java.io.InputStream body = response.body()) { + ExecutorService bodyReader = + Executors.newSingleThreadExecutor( + task -> { + Thread thread = new Thread(task, "account-jwks-api-response-reader"); + thread.setDaemon(true); + return thread; + }); + Future bodyFuture = bodyReader.submit(() -> readBounded(body, MAX_RESPONSE_BYTES)); + try { + long remainingNanos = responseDeadlineNanos - System.nanoTime(); + if (remainingNanos <= 0L) { + throw new TimeoutException(); + } + return new ApiResponse( + response.statusCode(), bodyFuture.get(remainingNanos, TimeUnit.NANOSECONDS)); + } catch (TimeoutException ex) { + bodyFuture.cancel(true); + throw new IOException("Kubernetes API response exceeded its deadline"); + } finally { + bodyReader.shutdownNow(); + } + } + } catch (InterruptedException ex) { + Thread.currentThread().interrupt(); + throw new ApiTransportException(); + } catch (Exception ex) { + throw new ApiTransportException(); + } + } + + private ProtectedState recheckProtectedState() { + try { + return acceptCurrentProtectedState(); + } catch (BindingRejectedException ex) { + throw ex; + } catch (Exception ex) { + throw new BindingRejectedException(); + } + } + + /** Strict parser is exposed for deterministic format tests, not as an activation path. */ + public static ParsedBinding parseProtectedBytes(byte[] bytes) { + if (bytes == null || bytes.length == 0 || bytes.length > MAX_BINDING_BYTES) { + throw new IllegalArgumentException("Account JWT JWKS API binding is unavailable"); + } + try { + String text = decodeUtf8(bytes); + JsonNode root = STRICT_JSON.readTree(text); + if (root == null || !root.isObject() || root.size() != CONFIG_FIELDS.size()) { + throw new IllegalArgumentException("Account JWT JWKS API binding is malformed"); + } + Map supplied = new LinkedHashMap<>(); + for (Map.Entry field : root.properties()) { + if (!CONFIG_FIELDS.contains(field.getKey()) + || supplied.putIfAbsent(field.getKey(), field.getValue()) != null) { + throw new IllegalArgumentException("Account JWT JWKS API binding is malformed"); + } + } + if (!supplied.keySet().equals(CONFIG_FIELDS) + || !"true".equals(requiredText(root, "enabled", 5)) + || !BINDING_VERSION.equals(requiredText(root, "version", 80))) { + throw new IllegalArgumentException("Account JWT JWKS API binding is disabled"); + } + + String revision = requiredText(root, "configRevision", 128); + String environmentId = requiredText(root, "environmentId", 63); + String clusterId = requiredText(root, "clusterId", 128); + String namespace = requiredText(root, "namespace", 63); + String clusterUid = canonicalUid(requiredText(root, "expectedClusterIncarnationUid", 36)); + String namespaceUid = canonicalUid(requiredText(root, "expectedNamespaceUid", 36)); + String apiUsername = requiredText(root, "expectedApiUsername", 256); + if (!REVISION.matcher(revision).matches() + || !ENVIRONMENT.matcher(environmentId).matches() + || !CLUSTER.matcher(clusterId).matches() + || !NAMESPACE.matcher(namespace).matches() + || !apiUsername.equals( + "system:serviceaccount:" + namespace + ":" + ACCOUNT_SERVICE_ACCOUNT)) { + throw new IllegalArgumentException("Account JWT JWKS API binding is malformed"); + } + + URI apiServer = parseApiServer(requiredText(root, "apiServerUrl", 512)); + String tlsServerName = requiredText(root, "tlsServerName", 253); + String asciiTlsName = canonicalDnsName(tlsServerName); + if (!asciiTlsName.equalsIgnoreCase(apiServer.getHost())) { + throw new IllegalArgumentException("Account JWT JWKS API TLS name is not pinned"); + } + String caPath = requiredText(root, "servingCaPath", 1024); + String caSha256 = requiredText(root, "servingCaSha256", 64); + String tokenPath = requiredText(root, "bearerTokenPath", 1024); + if (!SHA256.matcher(caSha256).matches()) { + throw new IllegalArgumentException("Account JWT JWKS API CA pin is malformed"); + } + Path servingCaPath = absoluteProtectedPath(caPath); + Path bearerTokenPath = absoluteProtectedPath(tokenPath); + String suppliedDigest = requiredText(root, "bindingDigest", 64); + if (!SHA256.matcher(suppliedDigest).matches() + || !suppliedDigest.equals(computeBindingDigest(root))) { + throw new IllegalArgumentException("Account JWT JWKS API binding digest is invalid"); + } + return new ParsedBinding( + revision, + environmentId, + clusterId, + apiServer, + asciiTlsName, + servingCaPath, + caSha256, + bearerTokenPath, + namespace, + clusterUid, + namespaceUid, + apiUsername, + suppliedDigest); + } catch (IllegalArgumentException ex) { + throw ex; + } catch (RuntimeException ex) { + throw new IllegalArgumentException("Account JWT JWKS API binding is malformed"); + } + } + + public static String computeBindingDigest(JsonNode protectedBinding) { + if (protectedBinding == null || !protectedBinding.isObject()) { + throw new IllegalArgumentException("Account JWT JWKS API binding is malformed"); + } + try { + Map content = new LinkedHashMap<>(); + for (String field : CONFIG_FIELDS) { + if (!"bindingDigest".equals(field)) { + JsonNode value = protectedBinding.get(field); + if (value == null || !value.isValueNode()) { + throw new IllegalArgumentException("Account JWT JWKS API binding is malformed"); + } + content.put(field, value.asText()); + } + } + byte[] canonical = + Rfc8785CanonicalJson.canonicalizeUtf8(STRICT_JSON.writeValueAsString(content)); + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(canonical)); + } catch (IllegalArgumentException ex) { + throw ex; + } catch (IOException | NoSuchAlgorithmException | RuntimeException ex) { + throw new IllegalArgumentException("Account JWT JWKS API binding digest is unavailable"); + } + } + + private ProtectedState readCurrentProtectedState() throws Exception { + if (testProtectedState != null) { + return testProtectedState; + } + Path bindingPath = absoluteProtectedPath(protectedBindingPath); + if (protectedPaths == null + || !bindingPath.equals(protectedPaths.bindingPath()) + || (!protectedPaths.testOnly() + && (!bindingPath.equals(TRUST_BINDING_PATH) + || !protectedPaths.trustRoot().equals(TRUST_ROOT) + || !protectedPaths.caPath().equals(TRUST_CA_PATH) + || !protectedPaths.tokenRoot().equals(TOKEN_ROOT) + || !protectedPaths.tokenPath().equals(TOKEN_PATH)))) { + throw new BindingRejectedException(); + } + Path canonicalTokenRoot = resolveTrustedTokenRoot(protectedPaths); + if (!protectedPaths.testOnly()) { + verifyProtectedDirectoryChain(TRUST_ROOT); + verifyProtectedDirectoryChain(canonicalTokenRoot); + } + ProtectedFile bindingFile = readProtectedFile(bindingPath, MAX_BINDING_BYTES); + ParsedBinding config = parseProtectedBytes(bindingFile.bytes()); + if (!config.servingCaPath().equals(protectedPaths.caPath()) + || !config.bearerTokenPath().equals(protectedPaths.tokenPath())) { + throw new BindingRejectedException(); + } + ProtectedFile caFile = readProtectedFile(config.servingCaPath(), MAX_CA_BYTES); + ProtectedFile tokenFile = + readBearerProtectedFile(config.bearerTokenPath(), protectedPaths.tokenRoot()); + String caDigest = sha256(caFile.bytes()); + if (!caDigest.equals(config.servingCaSha256())) { + throw new BindingRejectedException(); + } + String token = decodeUtf8(tokenFile.bytes()); + if (!BEARER.matcher(token).matches()) { + throw new BindingRejectedException(); + } + TrustIdentity identity = + new TrustIdentity( + bindingFile.identity(), + caFile.identity(), + credentialPolicy(tokenFile.identity()), + config.bindingDigest(), + canonicalTokenRoot.toString()); + return new ProtectedState(config, caFile.bytes(), token, identity, tokenFile.identity()); + } + + private static CredentialPolicyIdentity credentialPolicy(FileIdentity identity) { + return new CredentialPolicyIdentity( + identity.path(), identity.ownerUid(), identity.groupId(), identity.permissions()); + } + + private ProtectedState acceptCurrentProtectedState() throws Exception { + ProtectedState state = readCurrentProtectedState(); + TrustIdentity baseline = acceptedIdentity.get(); + if (baseline == null) { + acceptedIdentity.compareAndSet(null, state.identity()); + baseline = acceptedIdentity.get(); + } + if (baseline == null || !baseline.equals(state.identity())) { + throw new BindingRejectedException(); + } + return state; + } + + private static HttpClient createHttpClient(byte[] caBytes) throws Exception { + CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); + List certificates = + List.copyOf(certificateFactory.generateCertificates(new ByteArrayInputStream(caBytes))); + if (certificates.isEmpty() || certificates.size() > 16) { + throw new BindingRejectedException(); + } + KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); + trustStore.load(null, null); + int index = 0; + for (Certificate certificate : certificates) { + if (!(certificate instanceof X509Certificate x509)) { + throw new BindingRejectedException(); + } + x509.checkValidity(); + if (x509.getBasicConstraints() < 0) { + throw new BindingRejectedException(); + } + trustStore.setCertificateEntry("account-jwks-ca-" + index++, x509); + } + TrustManagerFactory trustManagers = + TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); + trustManagers.init(trustStore); + SSLContext sslContext = SSLContext.getInstance("TLS"); + sslContext.init(null, trustManagers.getTrustManagers(), null); + SSLParameters sslParameters = new SSLParameters(); + sslParameters.setEndpointIdentificationAlgorithm("HTTPS"); + return HttpClient.newBuilder() + .connectTimeout(Duration.ofSeconds(3)) + .followRedirects(HttpClient.Redirect.NEVER) + .version(HttpClient.Version.HTTP_1_1) + .sslContext(sslContext) + .sslParameters(sslParameters) + .proxy(DIRECT_ONLY_PROXY) + .build(); + } + + private static final ProxySelector DIRECT_ONLY_PROXY = + new ProxySelector() { + @Override + public List select(URI uri) { + return List.of(Proxy.NO_PROXY); + } + + @Override + public void connectFailed(URI uri, SocketAddress address, IOException failure) { + // No proxy exists; connection failures are handled by the bounded API call. + } + }; + + private static byte[] readBounded(java.io.InputStream input, int maximumBytes) + throws IOException { + ByteArrayOutputStream output = new ByteArrayOutputStream(Math.min(maximumBytes, 8192)); + byte[] buffer = new byte[8192]; + int total = 0; + while (true) { + int count = input.read(buffer); + if (count < 0) { + return output.toByteArray(); + } + total += count; + if (total > maximumBytes) { + throw new IOException("Kubernetes API response exceeded its bound"); + } + output.write(buffer, 0, count); + } + } + + private static void validateCallBody(ApiCall call, byte[] body) { + if (call == ApiCall.PATCH_JWKS_CONFIG_MAP) { + if (body == null || body.length == 0) { + throw new BindingRejectedException(); + } + try { + JsonNode patch = STRICT_JSON.readTree(decodeUtf8(body)); + JsonNode metadata = patch == null ? null : patch.get("metadata"); + JsonNode data = patch == null ? null : patch.get("data"); + if (patch == null + || !patch.isObject() + || patch.size() != 2 + || metadata == null + || !metadata.isObject() + || metadata.size() != 2 + || !validUid(text(metadata.get("uid"))) + || !validResourceVersion(text(metadata.get("resourceVersion"))) + || data == null + || !data.isObject() + || data.size() != 2 + || !data.has("jwks.json") + || !data.has("jwt-generation.json") + || !data.get("jwks.json").isTextual() + || !data.get("jwt-generation.json").isTextual() + || data.get("jwks.json").asText().isBlank() + || data.get("jwt-generation.json").asText().isBlank()) { + throw new BindingRejectedException(); + } + JsonNode jwks = STRICT_JSON.readTree(data.get("jwks.json").asText()); + JsonNode keys = jwks == null ? null : jwks.get("keys"); + if (jwks == null + || !jwks.isObject() + || jwks.size() != 1 + || keys == null + || !keys.isArray() + || keys.isEmpty()) { + throw new BindingRejectedException(); + } + for (JsonNode key : keys) { + if (!key.isObject() + || key.has("d") + || key.has("p") + || key.has("q") + || key.has("dp") + || key.has("dq") + || key.has("qi") + || key.has("oth") + || key.has("k")) { + throw new BindingRejectedException(); + } + } + } catch (BindingRejectedException ex) { + throw ex; + } catch (RuntimeException ex) { + throw new BindingRejectedException(); + } + return; + } + if (call == ApiCall.REVIEW_AUTHENTICATED_PRINCIPAL) { + String expected = + "{\"apiVersion\":\"authentication.k8s.io/v1\",\"kind\":\"SelfSubjectReview\",\"spec\":{}}"; + if (body == null || !expected.equals(decodeUtf8(body))) { + throw new BindingRejectedException(); + } + return; + } + if (body != null) { + throw new BindingRejectedException(); + } + } + + private static ProtectedFile readProtectedFile(Path path, int maximumBytes) throws IOException { + return readProtectedFile(path, maximumBytes, false); + } + + private static ProtectedFile readBearerProtectedFile(Path configuredPath, Path trustedTokenRoot) + throws IOException { + Path absolute = configuredPath.toAbsolutePath().normalize(); + Path tokenRoot = trustedTokenRoot.toAbsolutePath().normalize(); + if (absolute.getParent() == null + || !absolute.equals(configuredPath) + || !absolute.equals(tokenRoot.resolve("token"))) { + throw new IOException("Protected Account JWT bearer file is unavailable"); + } + Path canonicalTokenRoot = tokenRoot.toRealPath(); + if (!canonicalTokenRoot.equals(tokenRoot) && !canonicalTokenRoot.equals(CANONICAL_TOKEN_ROOT)) { + throw new IOException("Protected Account JWT bearer projection root is invalid"); + } + verifyProtectedDirectory(canonicalTokenRoot); + + BasicFileAttributes linkBefore = + Files.readAttributes(absolute, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS); + if (!linkBefore.isSymbolicLink()) { + throw new IOException("Protected Account JWT bearer file is unavailable"); + } + Object linkOwner = Files.getAttribute(absolute, "unix:uid", LinkOption.NOFOLLOW_LINKS); + if (!(linkOwner instanceof Number linkUid) || linkUid.longValue() != 0L) { + throw new IOException("Protected Account JWT bearer file ownership is invalid"); + } + + Path target = absolute.toRealPath(); + Path versionDirectory = target.getParent(); + Path targetFileName = target.getFileName(); + Path versionDirectoryFileName = + versionDirectory == null ? null : versionDirectory.getFileName(); + if (!target.startsWith(canonicalTokenRoot) + || versionDirectory == null + || !canonicalTokenRoot.equals(versionDirectory.getParent()) + || targetFileName == null + || !"token".equals(targetFileName.toString()) + || versionDirectoryFileName == null + || !versionDirectoryFileName.toString().matches("\\.\\.[A-Za-z0-9._-]{1,128}")) { + throw new IOException("Protected Account JWT bearer projection is invalid"); + } + ProtectedFile targetFile = readProtectedFile(target, MAX_BEARER_BYTES, true); + Path targetAfter = absolute.toRealPath(); + BasicFileAttributes linkAfter = + Files.readAttributes(absolute, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS); + Object linkOwnerAfter = Files.getAttribute(absolute, "unix:uid", LinkOption.NOFOLLOW_LINKS); + if (!target.equals(targetAfter) + || !sameLinkAttributes(linkBefore, linkAfter) + || !(linkOwnerAfter instanceof Number linkUidAfter) + || linkUidAfter.longValue() != 0L) { + throw new IOException("Protected Account JWT bearer file changed while reading"); + } + + FileIdentity targetIdentity = targetFile.identity(); + return new ProtectedFile( + targetFile.bytes(), + new FileIdentity( + absolute.toString(), + target + "|link=" + String.valueOf(linkBefore.fileKey()), + targetIdentity.size(), + targetIdentity.modifiedMillis(), + targetIdentity.ownerUid(), + targetIdentity.groupId(), + targetIdentity.permissions(), + targetIdentity.contentSha256())); + } + + private static ProtectedFile readProtectedFile( + Path path, int maximumBytes, boolean bearerCredential) throws IOException { + Path absolute = path.toAbsolutePath().normalize(); + if (Files.isSymbolicLink(absolute) || !absolute.equals(absolute.toRealPath())) { + throw new IOException("Protected Account JWT JWKS file is unavailable"); + } + BasicFileAttributes before = + Files.readAttributes(absolute, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS); + if (!before.isRegularFile() || before.size() <= 0 || before.size() > maximumBytes) { + throw new IOException("Protected Account JWT JWKS file is unavailable"); + } + FileSecurity beforeSecurity = fileSecurity(absolute); + verifyRootOwnedAndNonWritable(absolute); + if (bearerCredential) { + verifyBearerPermissions(absolute, beforeSecurity.permissions()); + } + byte[] bytes = new byte[(int) before.size()]; + try (SeekableByteChannel channel = + Files.newByteChannel(absolute, StandardOpenOption.READ, LinkOption.NOFOLLOW_LINKS)) { + ByteBuffer buffer = ByteBuffer.wrap(bytes); + while (buffer.hasRemaining()) { + int count = channel.read(buffer); + if (count < 0) { + throw new IOException("Protected Account JWT JWKS file changed while reading"); + } + } + if (channel.read(ByteBuffer.allocate(1)) != -1) { + throw new IOException("Protected Account JWT JWKS file changed while reading"); + } + } + BasicFileAttributes after = + Files.readAttributes(absolute, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS); + FileSecurity afterSecurity = fileSecurity(absolute); + if (!sameAttributes(before, after) || !beforeSecurity.equals(afterSecurity)) { + throw new IOException("Protected Account JWT JWKS file changed while reading"); + } + verifyRootOwnedAndNonWritable(absolute); + if (bearerCredential) { + verifyBearerPermissions(absolute, afterSecurity.permissions()); + } + return new ProtectedFile( + bytes, + new FileIdentity( + absolute.toString(), + String.valueOf(before.fileKey()), + before.size(), + before.lastModifiedTime().toMillis(), + afterSecurity.ownerUid(), + afterSecurity.groupId(), + afterSecurity.permissions(), + sha256(bytes))); + } + + private static FileSecurity fileSecurity(Path file) throws IOException { + Object owner = Files.getAttribute(file, "unix:uid", LinkOption.NOFOLLOW_LINKS); + Object group = Files.getAttribute(file, "unix:gid", LinkOption.NOFOLLOW_LINKS); + if (!(owner instanceof Number ownerUid) || !(group instanceof Number groupId)) { + throw new IOException("Protected Account JWT JWKS file ownership is unavailable"); + } + return new FileSecurity( + ownerUid.longValue(), + groupId.longValue(), + Set.copyOf(Files.getPosixFilePermissions(file, LinkOption.NOFOLLOW_LINKS))); + } + + private static void verifyRootOwnedAndNonWritable(Path file) throws IOException { + Path parent = file.getParent(); + if (parent == null || Files.isSymbolicLink(file)) { + throw new IOException("Protected Account JWT JWKS file is unavailable"); + } + verifyProtectedDirectory(parent); + Object fileOwner = Files.getAttribute(file, "unix:uid", LinkOption.NOFOLLOW_LINKS); + Set fileMode = + Files.getPosixFilePermissions(file, LinkOption.NOFOLLOW_LINKS); + if (!(fileOwner instanceof Number fileUid) || fileUid.longValue() != 0L || writable(fileMode)) { + throw new IOException("Protected Account JWT JWKS file ownership is invalid"); + } + } + + private static void verifyProtectedDirectory(Path directory) throws IOException { + Path normalizedDirectory = directory.toAbsolutePath().normalize(); + Path realDirectory = normalizedDirectory.toRealPath(); + Object directoryOwner = + Files.getAttribute(realDirectory, "unix:uid", LinkOption.NOFOLLOW_LINKS); + Set directoryMode = + Files.getPosixFilePermissions(realDirectory, LinkOption.NOFOLLOW_LINKS); + if (!realDirectory.equals(normalizedDirectory) + || !Files.isDirectory(realDirectory, LinkOption.NOFOLLOW_LINKS) + || !(directoryOwner instanceof Number directoryUid) + || directoryUid.longValue() != 0L + || writableByUntrusted(directoryMode)) { + throw new IOException("Protected Account JWT JWKS directory ownership is invalid"); + } + } + + private static Path resolveTrustedTokenRoot(ProtectedPaths paths) throws IOException { + Path lexicalRoot = paths.tokenRoot().toAbsolutePath().normalize(); + Path canonicalRoot = lexicalRoot.toRealPath(); + if (paths.testOnly()) { + if (!canonicalRoot.equals(lexicalRoot)) { + throw new IOException("Protected Account JWT bearer root is unavailable"); + } + } else if (!lexicalRoot.equals(TOKEN_ROOT) + || (!canonicalRoot.equals(TOKEN_ROOT) && !canonicalRoot.equals(CANONICAL_TOKEN_ROOT))) { + throw new IOException("Protected Account JWT bearer root is unavailable"); + } + return canonicalRoot; + } + + private static void verifyProtectedDirectoryChain(Path directory) throws IOException { + Path normalized = directory.toAbsolutePath().normalize(); + Path canonical = normalized.toRealPath(); + if (!normalized.equals(canonical)) { + throw new IOException("Protected Account JWT JWKS directory ownership is invalid"); + } + for (Path current = canonical; current != null; current = current.getParent()) { + verifyProtectedDirectory(current); + } + } + + private static boolean writable(Set permissions) { + return permissions.contains(PosixFilePermission.OWNER_WRITE) + || permissions.contains(PosixFilePermission.GROUP_WRITE) + || permissions.contains(PosixFilePermission.OTHERS_WRITE); + } + + private static boolean writableByUntrusted(Set permissions) { + return permissions.contains(PosixFilePermission.GROUP_WRITE) + || permissions.contains(PosixFilePermission.OTHERS_WRITE); + } + + private static void verifyBearerPermissions(Path file, Set permissions) + throws IOException { + if (!permissions.contains(PosixFilePermission.OWNER_READ) + || !Files.isReadable(file) + || permissions.contains(PosixFilePermission.OTHERS_READ) + || permissions.contains(PosixFilePermission.OWNER_EXECUTE) + || permissions.contains(PosixFilePermission.GROUP_EXECUTE) + || permissions.contains(PosixFilePermission.OTHERS_EXECUTE)) { + throw new IOException("Protected Account JWT bearer file permissions are invalid"); + } + } + + private static boolean validUid(String value) { + return value != null && UID.matcher(value).matches(); + } + + private static boolean validResourceVersion(String value) { + return value != null && value.matches("[!-~]{1,256}"); + } + + private static boolean sameAttributes(BasicFileAttributes before, BasicFileAttributes after) { + return after.isRegularFile() + && Objects.equals(before.fileKey(), after.fileKey()) + && before.size() == after.size() + && before.lastModifiedTime().equals(after.lastModifiedTime()); + } + + private static boolean sameLinkAttributes(BasicFileAttributes before, BasicFileAttributes after) { + return before.isSymbolicLink() == after.isSymbolicLink() + && before.isRegularFile() == after.isRegularFile() + && Objects.equals(before.fileKey(), after.fileKey()) + && before.size() == after.size() + && before.lastModifiedTime().equals(after.lastModifiedTime()); + } + + private static String requiredText(JsonNode object, String field, int maximumLength) { + JsonNode value = object.get(field); + if (value == null + || !value.isTextual() + || value.asText().isEmpty() + || value.asText().length() > maximumLength) { + throw new IllegalArgumentException("Account JWT JWKS API binding is malformed"); + } + return value.asText(); + } + + private static String text(JsonNode node) { + return node != null && node.isTextual() && !node.asText().isEmpty() ? node.asText() : null; + } + + private static URI parseApiServer(String value) { + try { + URI uri = URI.create(value); + if (!"https".equalsIgnoreCase(uri.getScheme()) + || uri.getHost() == null + || uri.getPort() < 1 + || uri.getRawUserInfo() != null + || uri.getRawQuery() != null + || uri.getRawFragment() != null + || (uri.getRawPath() != null + && !uri.getRawPath().isEmpty() + && !"/".equals(uri.getRawPath()))) { + throw new IllegalArgumentException("Account JWT JWKS API endpoint is malformed"); + } + return URI.create("https://" + uri.getRawAuthority() + "/"); + } catch (IllegalArgumentException ex) { + throw new IllegalArgumentException("Account JWT JWKS API endpoint is malformed"); + } + } + + private static String canonicalDnsName(String value) { + if (value == null || value.isBlank() || value.endsWith(".")) { + throw new IllegalArgumentException("Account JWT JWKS API TLS name is malformed"); + } + try { + String ascii = + IDN.toASCII(value, IDN.USE_STD3_ASCII_RULES).toLowerCase(java.util.Locale.ROOT); + if (ascii.length() > 253 || ascii.startsWith("[") || isIpLiteral(ascii)) { + throw new IllegalArgumentException("Account JWT JWKS API TLS name is malformed"); + } + return ascii; + } catch (IllegalArgumentException ex) { + throw new IllegalArgumentException("Account JWT JWKS API TLS name is malformed"); + } + } + + private static boolean isIpLiteral(String value) { + return value.matches("[0-9.]+") || value.indexOf(':') >= 0; + } + + private static Path absoluteProtectedPath(String value) { + Path path = Path.of(value); + if (!path.isAbsolute() || !path.normalize().equals(path)) { + throw new IllegalArgumentException("Account JWT JWKS protected path is malformed"); + } + return path; + } + + private static String canonicalUid(String value) { + if (!UID.matcher(value).matches() || "00000000-0000-0000-0000-000000000000".equals(value)) { + throw new IllegalArgumentException("Account JWT JWKS API UID is malformed"); + } + return value; + } + + private static String decodeUtf8(byte[] bytes) { + try { + return StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(bytes)) + .toString(); + } catch (CharacterCodingException ex) { + throw new IllegalArgumentException("Account JWT JWKS protected file is not UTF-8"); + } + } + + private static String sha256(byte[] bytes) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (Exception ex) { + throw new IllegalStateException("Account JWT JWKS digest is unavailable"); + } + } + + private static FileIdentity testFileIdentity( + String path, byte[] bytes, Set permissions) { + return new FileIdentity( + path, "test-file-identity:" + path, bytes.length, 1L, 0L, 0L, permissions, sha256(bytes)); + } + + private record ProtectedFile(byte[] bytes, FileIdentity identity) {} + + private record FileSecurity(long ownerUid, long groupId, Set permissions) {} + + private record ProtectedState( + ParsedBinding config, + byte[] caBytes, + String bearerToken, + TrustIdentity identity, + FileIdentity bearerIdentity) {} + + private record TrustIdentity( + FileIdentity binding, + FileIdentity ca, + CredentialPolicyIdentity bearer, + String bindingDigest, + String bearerRootRealPath) {} + + private record CredentialPolicyIdentity( + String path, long ownerUid, long groupId, Set permissions) {} + + private record ProtectedPaths( + Path trustRoot, + Path bindingPath, + Path caPath, + Path tokenRoot, + Path tokenPath, + boolean testOnly) {} + + private record FileIdentity( + String path, + String fileKey, + long size, + long modifiedMillis, + long ownerUid, + long groupId, + Set permissions, + String contentSha256) {} + + public record ParsedBinding( + String configRevision, + String environmentId, + String clusterId, + URI apiServer, + String tlsServerName, + Path servingCaPath, + String servingCaSha256, + Path bearerTokenPath, + String namespace, + String expectedClusterIncarnationUid, + String expectedNamespaceUid, + String expectedApiUsername, + String bindingDigest) {} + + /** One operation-scoped credential lease; all its API calls use the same bearer snapshot. */ + public final class ApiOperation implements AutoCloseable { + private ProtectedState credentialSnapshot; + + private ApiOperation(ProtectedState credentialSnapshot) { + this.credentialSnapshot = credentialSnapshot; + } + + public ParsedBinding binding() { + if (credentialSnapshot == null) { + throw new BindingRejectedException(); + } + return credentialSnapshot.config(); + } + + public ApiResponse send(ApiCall call, byte[] requestBody) { + return AccountJwtJwksApiBinding.this.send(credentialSnapshot, call, requestBody); + } + + /** Reads one Deployment named by the independently protected validator inventory only. */ + public ApiResponse readValidatorDeployment( + AccountJwtValidatorInventoryBinding.ProtectedInventory inventory, + AccountJwtValidatorInventoryBinding.ValidatorExpectation validator) { + return AccountJwtJwksApiBinding.this.sendInventoryRead( + credentialSnapshot, ApiCall.READ_VALIDATOR_DEPLOYMENT, inventory, validator, null); + } + + /** Lists Pods only by the protected validator selector in the pinned namespace. */ + public ApiResponse listValidatorPods( + AccountJwtValidatorInventoryBinding.ProtectedInventory inventory, + AccountJwtValidatorInventoryBinding.ValidatorExpectation validator, + String continuationToken) { + return AccountJwtJwksApiBinding.this.sendInventoryRead( + credentialSnapshot, ApiCall.LIST_VALIDATOR_PODS, inventory, validator, continuationToken); + } + + /** Reads one ReplicaSet named by an observed Pod owner reference in the pinned namespace. */ + public ApiResponse readValidatorReplicaSet( + AccountJwtValidatorInventoryBinding.ProtectedInventory inventory, + AccountJwtValidatorInventoryBinding.ValidatorExpectation validator, + String replicaSetName) { + return AccountJwtJwksApiBinding.this.sendInventoryRead( + credentialSnapshot, + ApiCall.READ_VALIDATOR_REPLICA_SET, + inventory, + validator, + null, + replicaSetName); + } + + @Override + public void close() { + credentialSnapshot = null; + } + } + + private ApiResponse sendInventoryRead( + ProtectedState credentialSnapshot, + ApiCall call, + AccountJwtValidatorInventoryBinding.ProtectedInventory inventory, + AccountJwtValidatorInventoryBinding.ValidatorExpectation validator, + String continuationToken) { + return sendInventoryRead( + credentialSnapshot, call, inventory, validator, continuationToken, null); + } + + private ApiResponse sendInventoryRead( + ProtectedState credentialSnapshot, + ApiCall call, + AccountJwtValidatorInventoryBinding.ProtectedInventory inventory, + AccountJwtValidatorInventoryBinding.ValidatorExpectation validator, + String continuationToken, + String replicaSetName) { + if (credentialSnapshot == null + || inventory == null + || validator == null + || !inventory.matchesApiBinding(credentialSnapshot.config()) + || inventory.validators().stream().noneMatch(expected -> expected == validator)) { + throw new BindingRejectedException(); + } + String path; + if (call == ApiCall.READ_VALIDATOR_DEPLOYMENT) { + if (continuationToken != null) { + throw new BindingRejectedException(); + } + path = + "/apis/apps/v1/namespaces/" + + inventory.namespace() + + "/deployments/" + + validator.deploymentName(); + } else if (call == ApiCall.LIST_VALIDATOR_PODS) { + String selector = + validator.selector().entrySet().stream() + .sorted(Map.Entry.comparingByKey()) + .map(entry -> entry.getKey() + "=" + entry.getValue()) + .collect(java.util.stream.Collectors.joining(",")); + path = + "/api/v1/namespaces/" + + inventory.namespace() + + "/pods?labelSelector=" + + queryEncode(selector) + + "&limit=250"; + if (continuationToken != null && !continuationToken.isEmpty()) { + if (continuationToken.length() > 2048 + || !continuationToken.matches("[A-Za-z0-9_./+=-]{1,2048}")) { + throw new BindingRejectedException(); + } + path += "&continue=" + queryEncode(continuationToken); + } + } else if (call == ApiCall.READ_VALIDATOR_REPLICA_SET) { + if (continuationToken != null + || replicaSetName == null + || !replicaSetName.matches("[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?")) { + throw new BindingRejectedException(); + } + path = "/apis/apps/v1/namespaces/" + inventory.namespace() + "/replicasets/" + replicaSetName; + } else { + throw new BindingRejectedException(); + } + return send(credentialSnapshot, call, null, path); + } + + private static String queryEncode(String value) { + return URLEncoder.encode(value, StandardCharsets.UTF_8).replace("+", "%20"); + } + + public enum ApiCall { + REVIEW_AUTHENTICATED_PRINCIPAL("POST", "/apis/authentication.k8s.io/v1/selfsubjectreviews"), + READ_KUBE_SYSTEM_NAMESPACE("GET", "/api/v1/namespaces/kube-system"), + READ_TARGET_NAMESPACE("GET", null), + READ_JWKS_CONFIG_MAP("GET", null), + PATCH_JWKS_CONFIG_MAP("PATCH", null), + READ_VALIDATOR_DEPLOYMENT("GET", null), + LIST_VALIDATOR_PODS("GET", null), + READ_VALIDATOR_REPLICA_SET("GET", null); + + private final String method; + private final String fixedPath; + + ApiCall(String method, String fixedPath) { + this.method = method; + this.fixedPath = fixedPath; + } + + public String method() { + return method; + } + + private String path(String namespace) { + return switch (this) { + case REVIEW_AUTHENTICATED_PRINCIPAL, READ_KUBE_SYSTEM_NAMESPACE -> fixedPath; + case READ_TARGET_NAMESPACE -> "/api/v1/namespaces/" + namespace; + case READ_JWKS_CONFIG_MAP, PATCH_JWKS_CONFIG_MAP -> + "/api/v1/namespaces/" + namespace + "/configmaps/jwt-jwks"; + case READ_VALIDATOR_DEPLOYMENT, LIST_VALIDATOR_PODS, READ_VALIDATOR_REPLICA_SET -> + throw new BindingRejectedException(); + }; + } + } + + public record ApiResponse(int statusCode, byte[] body) { + public ApiResponse { + body = body == null ? new byte[0] : body.clone(); + } + + @Override + public byte[] body() { + return body.clone(); + } + } + + public static final class BindingRejectedException extends RuntimeException { + public BindingRejectedException() { + super("Account JWT JWKS API binding is unavailable or changed"); + } + } + + public static final class ApiTransportException extends RuntimeException { + public ApiTransportException() { + super("Account JWT JWKS Kubernetes API request failed"); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountJwtReadinessTrustBinding.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountJwtReadinessTrustBinding.java new file mode 100644 index 0000000000..ecd37c379a --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountJwtReadinessTrustBinding.java @@ -0,0 +1,480 @@ +package net.firedevops.firemud.accountservice.config; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.channels.SeekableByteChannel; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.LinkOption; +import java.nio.file.Path; +import java.nio.file.StandardOpenOption; +import java.nio.file.attribute.BasicFileAttributes; +import java.nio.file.attribute.PosixFilePermission; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.security.cert.CertificateException; +import java.security.cert.X509Certificate; +import java.time.Clock; +import java.util.ArrayList; +import java.util.Collection; +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.Set; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; +import tools.jackson.databind.json.JsonMapper; + +/** Independently protected, expiring trust for the non-authorizing readiness RPC only. */ +@Component +public final class AccountJwtReadinessTrustBinding { + public static final int MAX_FILE_BYTES = 8 * 1024; + private static final String VERSION = "account-jwt-readiness-trust-binding/v1"; + private static final String VALIDATOR_ID = "account-service"; + private static final String HARNESS_SERVICE_ACCOUNT = "account-jwt-readiness-harness"; + private static final Set REQUIRED_FIELDS = + Set.of( + "enabled", + "configRevision", + "environmentId", + "clusterId", + "namespace", + "expectedClusterIncarnationUid", + "expectedNamespaceUid", + "expectedPeerUri", + "peerSpkiSha256Pins", + "validatorId", + "validatorInstanceId", + "validUntilEpochSecond", + "bindingDigest"); + private static final Pattern ENVIRONMENT = + Pattern.compile("[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?"); + private static final Pattern CLUSTER = Pattern.compile("[A-Za-z0-9][A-Za-z0-9._:-]{0,127}"); + private static final Pattern REVISION = Pattern.compile("[A-Za-z0-9][A-Za-z0-9._:-]{0,127}"); + private static final Pattern INSTANCE = Pattern.compile("[A-Za-z0-9][A-Za-z0-9._:-]{0,127}"); + private static final Pattern SHA256 = Pattern.compile("[0-9a-f]{64}"); + private static final JsonMapper JSON = JsonMapper.builder().build(); + + private final boolean enabled; + private final String protectedBindingPath; + private final Clock clock; + + @Autowired + public AccountJwtReadinessTrustBinding( + @Value("${firemud.account.jwt-readiness.validation.enabled:false}") boolean enabled, + @Value("${firemud.account.jwt-readiness.validation.protected-binding-path:}") + String protectedBindingPath) { + this(enabled, protectedBindingPath, Clock.systemUTC()); + } + + AccountJwtReadinessTrustBinding(boolean enabled, String protectedBindingPath, Clock clock) { + this.enabled = enabled; + this.protectedBindingPath = protectedBindingPath == null ? "" : protectedBindingPath.trim(); + this.clock = Objects.requireNonNull(clock); + } + + /** Missing, disabled, malformed, expired, or mutable trust configuration denies access. */ + public Optional current() { + if (!enabled || protectedBindingPath.isBlank()) { + return Optional.empty(); + } + try { + return Optional.of(readProtectedFile(Path.of(protectedBindingPath), clock.instant())); + } catch (Exception ex) { + return Optional.empty(); + } + } + + static Binding parseProtectedBytes(byte[] bytes, long nowEpochSecond) { + if (bytes == null || bytes.length == 0 || bytes.length > MAX_FILE_BYTES) { + throw unavailable(); + } + Map fields = parseFields(decodeUtf8(bytes)); + if (!fields.keySet().equals(REQUIRED_FIELDS) || !"true".equals(fields.get("enabled"))) { + throw unavailable(); + } + + String environmentId = fields.get("environmentId"); + String clusterId = fields.get("clusterId"); + String namespace = fields.get("namespace"); + String clusterUid = canonicalUuid(fields.get("expectedClusterIncarnationUid")); + String namespaceUid = canonicalUuid(fields.get("expectedNamespaceUid")); + String revision = fields.get("configRevision"); + String instanceId = fields.get("validatorInstanceId"); + long validUntil = parsePositiveLong(fields.get("validUntilEpochSecond")); + if (!ENVIRONMENT.matcher(environmentId).matches() + || !CLUSTER.matcher(clusterId).matches() + || !ENVIRONMENT.matcher(namespace).matches() + || !REVISION.matcher(revision).matches() + || !INSTANCE.matcher(instanceId).matches() + || !VALIDATOR_ID.equals(fields.get("validatorId")) + || nowEpochSecond <= 0L + || nowEpochSecond >= validUntil) { + throw unavailable(); + } + + String expectedUri = fields.get("expectedPeerUri"); + if (!expectedHarnessUri(namespace, expectedUri)) { + throw unavailable(); + } + List pins = parsePins(fields.get("peerSpkiSha256Pins")); + String digest = + computeBindingDigest( + revision, + environmentId, + clusterId, + namespace, + clusterUid, + namespaceUid, + expectedUri, + pins, + instanceId, + validUntil); + if (!digest.equals(fields.get("bindingDigest"))) { + throw unavailable(); + } + return new Binding( + environmentId, + clusterId, + namespace, + clusterUid, + namespaceUid, + expectedUri, + pins, + revision, + VALIDATOR_ID, + instanceId, + validUntil, + digest); + } + + private static Binding readProtectedFile(Path path, java.time.Instant now) throws IOException { + Path absolute = path.toAbsolutePath().normalize(); + if (Files.isSymbolicLink(absolute)) { + throw new IOException("Protected readiness binding is unavailable"); + } + BasicFileAttributes before = + Files.readAttributes(absolute, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS); + if (!before.isRegularFile() || before.size() <= 0 || before.size() > MAX_FILE_BYTES) { + throw new IOException("Protected readiness binding is unavailable"); + } + verifyRootOwnedAndNonWritable(absolute); + byte[] bytes = new byte[(int) before.size()]; + try (SeekableByteChannel channel = + Files.newByteChannel(absolute, StandardOpenOption.READ, LinkOption.NOFOLLOW_LINKS)) { + ByteBuffer buffer = ByteBuffer.wrap(bytes); + while (buffer.hasRemaining()) { + if (channel.read(buffer) < 0) { + throw new IOException("Protected readiness binding changed while reading"); + } + } + if (channel.read(ByteBuffer.allocate(1)) != -1) { + throw new IOException("Protected readiness binding changed while reading"); + } + } + BasicFileAttributes after = + Files.readAttributes(absolute, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS); + if (!after.isRegularFile() + || !Objects.equals(before.fileKey(), after.fileKey()) + || before.size() != after.size() + || !before.lastModifiedTime().equals(after.lastModifiedTime())) { + throw new IOException("Protected readiness binding changed while reading"); + } + verifyRootOwnedAndNonWritable(absolute); + return parseProtectedBytes(bytes, now.getEpochSecond()); + } + + private static Map parseFields(String text) { + String[] lines = text.split("\n", -1); + int count = lines.length; + if (count > 0 && lines[count - 1].isEmpty()) { + count--; + } + Map fields = new LinkedHashMap<>(); + for (int index = 0; index < count; index++) { + String line = lines[index]; + int separator = line.indexOf('='); + if (line.isEmpty() || separator <= 0 || separator == line.length() - 1) { + throw unavailable(); + } + String key = line.substring(0, separator); + String value = line.substring(separator + 1); + if (!REQUIRED_FIELDS.contains(key) || fields.putIfAbsent(key, value) != null) { + throw unavailable(); + } + } + return fields; + } + + private static void verifyRootOwnedAndNonWritable(Path file) throws IOException { + Path parent = file.getParent(); + if (parent == null || Files.isSymbolicLink(file)) { + throw new IOException("Protected readiness binding is unavailable"); + } + Path realParent = parent.toRealPath(); + Object fileOwner = Files.getAttribute(file, "unix:uid", LinkOption.NOFOLLOW_LINKS); + Object directoryOwner = Files.getAttribute(realParent, "unix:uid", LinkOption.NOFOLLOW_LINKS); + Set fileMode = + Files.getPosixFilePermissions(file, LinkOption.NOFOLLOW_LINKS); + Set directoryMode = Files.getPosixFilePermissions(realParent); + if (!(fileOwner instanceof Number fileUid) + || fileUid.longValue() != 0L + || !(directoryOwner instanceof Number directoryUid) + || directoryUid.longValue() != 0L + || writable(fileMode) + || writable(directoryMode)) { + throw new IOException("Protected readiness binding ownership is invalid"); + } + } + + private static boolean writable(Set permissions) { + return permissions.contains(PosixFilePermission.OWNER_WRITE) + || permissions.contains(PosixFilePermission.GROUP_WRITE) + || permissions.contains(PosixFilePermission.OTHERS_WRITE); + } + + private static String decodeUtf8(byte[] bytes) { + try { + return StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(bytes)) + .toString(); + } catch (CharacterCodingException ex) { + throw unavailable(); + } + } + + private static List parsePins(String value) { + String[] parts = value.split(",", -1); + if (parts.length == 0 || parts.length > 8) { + throw unavailable(); + } + List pins = new ArrayList<>(parts.length); + for (String pin : parts) { + if (!SHA256.matcher(pin).matches() || pins.contains(pin)) { + throw unavailable(); + } + pins.add(pin); + } + return List.copyOf(pins); + } + + private static boolean expectedHarnessUri(String namespace, String uri) { + return ("spiffe://firemud/ns/" + namespace + "/sa/" + HARNESS_SERVICE_ACCOUNT).equals(uri); + } + + private static String canonicalUuid(String value) { + UUID uuid = UUID.fromString(value); + if (!uuid.toString().equals(value) || new UUID(0L, 0L).equals(uuid)) { + throw unavailable(); + } + return uuid.toString(); + } + + private static long parsePositiveLong(String value) { + try { + long result = Long.parseLong(value); + if (result <= 0L || !Long.toString(result).equals(value)) { + throw unavailable(); + } + return result; + } catch (NumberFormatException ex) { + throw unavailable(); + } + } + + public static String computeBindingDigest( + String configRevision, + String environmentId, + String clusterId, + String namespace, + String expectedClusterIncarnationUid, + String expectedNamespaceUid, + String expectedPeerUri, + List pins, + String validatorInstanceId, + long validUntilEpochSecond) { + try { + Map binding = new LinkedHashMap<>(); + binding.put("digestVersion", VERSION); + binding.put("configRevision", configRevision); + binding.put("environmentId", environmentId); + binding.put("clusterId", clusterId); + binding.put("namespace", namespace); + binding.put("expectedClusterIncarnationUid", expectedClusterIncarnationUid); + binding.put("expectedNamespaceUid", expectedNamespaceUid); + binding.put("expectedPeerUri", expectedPeerUri); + binding.put("peerSpkiSha256Pins", List.copyOf(pins)); + binding.put("validatorId", VALIDATOR_ID); + binding.put("validatorInstanceId", validatorInstanceId); + binding.put("validUntilEpochSecond", validUntilEpochSecond); + byte[] canonical = Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(binding)); + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(canonical)); + } catch (IOException | NoSuchAlgorithmException | RuntimeException ex) { + throw new IllegalStateException("Readiness binding digest is unavailable"); + } + } + + public static PeerIdentity identifyPeer(java.security.cert.Certificate[] certificates) { + if (certificates == null || certificates.length == 0) { + throw new PeerIdentityRejectedException(); + } + if (!(certificates[0] instanceof X509Certificate certificate)) { + throw new PeerIdentityRejectedException(); + } + try { + certificate.checkValidity(); + Collection> subjectAlternativeNames = certificate.getSubjectAlternativeNames(); + if (subjectAlternativeNames == null) { + throw new PeerIdentityRejectedException(); + } + String foundUri = null; + int uriCount = 0; + for (List entry : subjectAlternativeNames) { + if (entry.size() < 2 || !(entry.get(0) instanceof Integer type) || type != 6) { + continue; + } + uriCount++; + if (!(entry.get(1) instanceof String uri)) { + throw new PeerIdentityRejectedException(); + } + foundUri = uri; + } + if (uriCount != 1 || foundUri == null) { + throw new PeerIdentityRejectedException(); + } + String spki = + HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256") + .digest(certificate.getPublicKey().getEncoded())); + return new PeerIdentity(foundUri, spki); + } catch (CertificateException | NoSuchAlgorithmException ex) { + throw new PeerIdentityRejectedException(); + } + } + + private static IllegalArgumentException unavailable() { + return new IllegalArgumentException("Readiness trust binding is unavailable"); + } + + public static boolean matchesPeer( + java.security.cert.Certificate[] certificates, Binding binding) { + if (binding == null) { + return false; + } + try { + PeerIdentity peer = identifyPeer(certificates); + return binding.matches(peer); + } catch (RuntimeException rejected) { + return false; + } + } + + public record PeerIdentity(String uri, String spkiSha256) {} + + /** + * Configured per-validator-instance identity; this is not proof of pod UID or fleet inventory. + */ + public record Binding( + String environmentId, + String clusterId, + String namespace, + String expectedClusterIncarnationUid, + String expectedNamespaceUid, + String expectedPeerUri, + List peerSpkiSha256Pins, + String configRevision, + String validatorId, + String validatorInstanceId, + long validUntilEpochSecond, + String bindingDigest) { + public Binding { + Objects.requireNonNull(environmentId); + Objects.requireNonNull(clusterId); + Objects.requireNonNull(namespace); + Objects.requireNonNull(expectedClusterIncarnationUid); + Objects.requireNonNull(expectedNamespaceUid); + Objects.requireNonNull(expectedPeerUri); + peerSpkiSha256Pins = List.copyOf(peerSpkiSha256Pins); + Objects.requireNonNull(configRevision); + Objects.requireNonNull(validatorInstanceId); + Objects.requireNonNull(bindingDigest); + if (!ENVIRONMENT.matcher(environmentId).matches() + || !CLUSTER.matcher(clusterId).matches() + || !ENVIRONMENT.matcher(namespace).matches() + || !REVISION.matcher(configRevision).matches() + || !INSTANCE.matcher(validatorInstanceId).matches() + || !VALIDATOR_ID.equals(validatorId) + || peerSpkiSha256Pins.isEmpty() + || peerSpkiSha256Pins.size() > 8 + || validUntilEpochSecond <= 0L + || !SHA256.matcher(bindingDigest).matches() + || !expectedHarnessUri(namespace, expectedPeerUri) + || !peerSpkiSha256Pins.stream().allMatch(pin -> SHA256.matcher(pin).matches()) + || peerSpkiSha256Pins.stream().distinct().count() != peerSpkiSha256Pins.size()) { + throw unavailable(); + } + UUID clusterUid = UUID.fromString(expectedClusterIncarnationUid); + UUID namespaceUid = UUID.fromString(expectedNamespaceUid); + if (!clusterUid.toString().equals(expectedClusterIncarnationUid) + || !namespaceUid.toString().equals(expectedNamespaceUid) + || clusterUid.equals(new UUID(0L, 0L)) + || namespaceUid.equals(new UUID(0L, 0L))) { + throw unavailable(); + } + String expectedDigest = + computeBindingDigest( + configRevision, + environmentId, + clusterId, + namespace, + expectedClusterIncarnationUid, + expectedNamespaceUid, + expectedPeerUri, + peerSpkiSha256Pins, + validatorInstanceId, + validUntilEpochSecond); + if (!expectedDigest.equals(bindingDigest)) { + throw unavailable(); + } + } + + public boolean isCurrentAt(long nowEpochSecond) { + return nowEpochSecond > 0L && nowEpochSecond < validUntilEpochSecond; + } + + public boolean matches(PeerIdentity peer) { + if (peer == null || !expectedPeerUri.equals(peer.uri())) { + return false; + } + try { + byte[] actual = HexFormat.of().parseHex(peer.spkiSha256()); + boolean matched = false; + for (String pin : peerSpkiSha256Pins) { + matched |= MessageDigest.isEqual(actual, HexFormat.of().parseHex(pin)); + } + return matched; + } catch (IllegalArgumentException malformedPeer) { + return false; + } + } + } + + public static final class PeerIdentityRejectedException extends RuntimeException { + public PeerIdentityRejectedException() { + super("Readiness caller identity is unavailable"); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountJwtSignerMaterializerTrustBinding.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountJwtSignerMaterializerTrustBinding.java new file mode 100644 index 0000000000..71ba3c2455 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountJwtSignerMaterializerTrustBinding.java @@ -0,0 +1,404 @@ +package net.firedevops.firemud.accountservice.config; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.channels.SeekableByteChannel; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.LinkOption; +import java.nio.file.Path; +import java.nio.file.StandardOpenOption; +import java.nio.file.attribute.BasicFileAttributes; +import java.nio.file.attribute.PosixFilePermission; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.security.cert.CertificateException; +import java.security.cert.X509Certificate; +import java.util.ArrayList; +import java.util.Collection; +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.Set; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; +import tools.jackson.databind.json.JsonMapper; + +/** + * Reads the independently protected trust binding for Account's narrow JWT materializer RPCs. The + * file must be root-owned and non-writable by the Account/materializer workload. It is read again + * for every RPC so pin rotation or trust withdrawal takes effect without process restart. + */ +@Component +public final class AccountJwtSignerMaterializerTrustBinding { + public static final int MAX_FILE_BYTES = 8 * 1024; + private static final String VERSION = "account-jwt-signer-materializer-binding/v1"; + private static final Set REQUIRED_FIELDS = + Set.of( + "enabled", + "configRevision", + "environmentId", + "clusterId", + "namespace", + "expectedClusterIncarnationUid", + "expectedNamespaceUid", + "expectedPeerUri", + "peerSpkiSha256Pins", + "bindingDigest"); + private static final Pattern ENVIRONMENT = + Pattern.compile("[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?"); + private static final Pattern CLUSTER = Pattern.compile("[A-Za-z0-9][A-Za-z0-9._:-]{0,127}"); + private static final Pattern REVISION = Pattern.compile("[A-Za-z0-9][A-Za-z0-9._:-]{0,127}"); + private static final Pattern SHA256 = Pattern.compile("[0-9a-f]{64}"); + private static final JsonMapper JSON = JsonMapper.builder().build(); + + private final boolean enabled; + private final String protectedBindingPath; + + public AccountJwtSignerMaterializerTrustBinding( + @Value("${firemud.account.jwt-signer.materialization.enabled:false}") boolean enabled, + @Value("${firemud.account.jwt-signer.materialization.protected-binding-path:}") + String protectedBindingPath) { + this.enabled = enabled; + this.protectedBindingPath = protectedBindingPath == null ? "" : protectedBindingPath.trim(); + } + + /** Missing, disabled, malformed, or mutable trust configuration always means no access. */ + public Optional current() { + if (!enabled || protectedBindingPath.isBlank()) { + return Optional.empty(); + } + try { + return Optional.of(readProtectedFile(Path.of(protectedBindingPath))); + } catch (Exception ex) { + // Never expose config contents, file paths, or certificate details through RPC errors. + return Optional.empty(); + } + } + + /** Testable parser boundary; production calls still require the protected-file checks above. */ + static AccountJwtSignerMaterializerTrustBinding.Binding parseProtectedBytes(byte[] bytes) { + if (bytes == null || bytes.length == 0 || bytes.length > MAX_FILE_BYTES) { + throw new IllegalArgumentException("JWT materializer trust binding is unavailable"); + } + String text = decodeUtf8(bytes); + String[] lines = text.split("\n", -1); + int count = lines.length; + if (count > 0 && lines[count - 1].isEmpty()) { + count--; + } + Map fields = new LinkedHashMap<>(); + for (int index = 0; index < count; index++) { + String line = lines[index]; + int separator = line.indexOf('='); + if (line.isEmpty() || separator <= 0 || separator == line.length() - 1) { + throw new IllegalArgumentException("JWT materializer trust binding is malformed"); + } + String key = line.substring(0, separator); + String value = line.substring(separator + 1); + if (!REQUIRED_FIELDS.contains(key) || fields.putIfAbsent(key, value) != null) { + throw new IllegalArgumentException("JWT materializer trust binding is malformed"); + } + } + if (!fields.keySet().equals(REQUIRED_FIELDS) || !"true".equals(fields.get("enabled"))) { + throw new IllegalArgumentException("JWT materializer trust binding is disabled"); + } + + String environmentId = fields.get("environmentId"); + String clusterId = fields.get("clusterId"); + String namespace = fields.get("namespace"); + String clusterUid = canonicalUuid(fields.get("expectedClusterIncarnationUid")); + String namespaceUid = canonicalUuid(fields.get("expectedNamespaceUid")); + String revision = fields.get("configRevision"); + if (!ENVIRONMENT.matcher(environmentId).matches() + || !CLUSTER.matcher(clusterId).matches() + || !ENVIRONMENT.matcher(namespace).matches() + || !REVISION.matcher(revision).matches()) { + throw new IllegalArgumentException("JWT materializer trust binding is malformed"); + } + String expectedUri = fields.get("expectedPeerUri"); + if (!validExpectedPeerUri(namespace, expectedUri)) { + throw new IllegalArgumentException("JWT materializer workload identity is not canonical"); + } + List pins = parsePins(fields.get("peerSpkiSha256Pins")); + String digest = + computeBindingDigest( + revision, + environmentId, + clusterId, + namespace, + clusterUid, + namespaceUid, + expectedUri, + pins); + if (!digest.equals(fields.get("bindingDigest"))) { + throw new IllegalArgumentException("JWT materializer trust binding digest is invalid"); + } + return new AccountJwtSignerMaterializerTrustBinding.Binding( + environmentId, + clusterId, + namespace, + clusterUid, + namespaceUid, + expectedUri, + pins, + revision, + digest); + } + + private static Binding readProtectedFile(Path path) throws IOException { + Path absolute = path.toAbsolutePath().normalize(); + if (Files.isSymbolicLink(absolute)) { + throw new IOException("Protected Account JWT materializer binding is not a regular file"); + } + BasicFileAttributes before = + Files.readAttributes(absolute, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS); + if (!before.isRegularFile()) { + throw new IOException("Protected Account JWT materializer binding is not a regular file"); + } + verifyRootOwnedAndNonWritable(absolute); + if (before.size() <= 0 || before.size() > MAX_FILE_BYTES) { + throw new IOException("Protected Account JWT materializer binding size is invalid"); + } + byte[] bytes = new byte[(int) before.size()]; + try (SeekableByteChannel channel = + Files.newByteChannel(absolute, StandardOpenOption.READ, LinkOption.NOFOLLOW_LINKS)) { + ByteBuffer buffer = ByteBuffer.wrap(bytes); + while (buffer.hasRemaining()) { + int count = channel.read(buffer); + if (count < 0) { + throw new IOException("Protected Account JWT materializer binding changed while reading"); + } + } + if (channel.read(ByteBuffer.allocate(1)) != -1) { + throw new IOException("Protected Account JWT materializer binding changed while reading"); + } + } + BasicFileAttributes after = + Files.readAttributes(absolute, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS); + if (!after.isRegularFile() + || !Objects.equals(before.fileKey(), after.fileKey()) + || before.size() != after.size() + || !before.lastModifiedTime().equals(after.lastModifiedTime())) { + throw new IOException("Protected Account JWT materializer binding changed while reading"); + } + verifyRootOwnedAndNonWritable(absolute); + return parseProtectedBytes(bytes); + } + + private static void verifyRootOwnedAndNonWritable(Path file) throws IOException { + Path parent = file.getParent(); + if (parent == null || Files.isSymbolicLink(file)) { + throw new IOException("Protected Account JWT materializer binding is unavailable"); + } + Path realParent = parent.toRealPath(); + Object fileOwner = Files.getAttribute(file, "unix:uid", LinkOption.NOFOLLOW_LINKS); + Object directoryOwner = Files.getAttribute(realParent, "unix:uid", LinkOption.NOFOLLOW_LINKS); + Set fileMode = + Files.getPosixFilePermissions(file, LinkOption.NOFOLLOW_LINKS); + Set directoryMode = Files.getPosixFilePermissions(realParent); + if (!(fileOwner instanceof Number fileUid) + || fileUid.longValue() != 0L + || !(directoryOwner instanceof Number directoryUid) + || directoryUid.longValue() != 0L + || writable(fileMode) + || writable(directoryMode)) { + throw new IOException("Protected Account JWT materializer binding ownership is invalid"); + } + } + + private static boolean writable(Set permissions) { + return permissions.contains(PosixFilePermission.OWNER_WRITE) + || permissions.contains(PosixFilePermission.GROUP_WRITE) + || permissions.contains(PosixFilePermission.OTHERS_WRITE); + } + + private static String decodeUtf8(byte[] bytes) { + try { + return StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(bytes)) + .toString(); + } catch (CharacterCodingException ex) { + throw new IllegalArgumentException("JWT materializer trust binding is not UTF-8", ex); + } + } + + private static List parsePins(String value) { + String[] parts = value.split(",", -1); + if (parts.length == 0 || parts.length > 8) { + throw new IllegalArgumentException("JWT materializer certificate pins are malformed"); + } + List pins = new ArrayList<>(parts.length); + for (String pin : parts) { + if (!SHA256.matcher(pin).matches() || pins.contains(pin)) { + throw new IllegalArgumentException("JWT materializer certificate pins are malformed"); + } + pins.add(pin); + } + return List.copyOf(pins); + } + + private static boolean validExpectedPeerUri(String namespace, String uri) { + String prefix = "spiffe://firemud/ns/" + namespace + "/sa/"; + return uri != null + && uri.startsWith(prefix) + && ENVIRONMENT.matcher(uri.substring(prefix.length())).matches(); + } + + private static String canonicalUuid(String value) { + UUID uuid = UUID.fromString(value); + if (!uuid.toString().equals(value) || new UUID(0L, 0L).equals(uuid)) { + throw new IllegalArgumentException("JWT materializer trust UID is malformed"); + } + return uuid.toString(); + } + + public static String computeBindingDigest( + String configRevision, + String environmentId, + String clusterId, + String namespace, + String expectedClusterIncarnationUid, + String expectedNamespaceUid, + String expectedPeerUri, + List pins) { + try { + Map binding = new LinkedHashMap<>(); + binding.put("digestVersion", VERSION); + binding.put("configRevision", configRevision); + binding.put("environmentId", environmentId); + binding.put("clusterId", clusterId); + binding.put("namespace", namespace); + binding.put("expectedClusterIncarnationUid", expectedClusterIncarnationUid); + binding.put("expectedNamespaceUid", expectedNamespaceUid); + binding.put("expectedPeerUri", expectedPeerUri); + binding.put("peerSpkiSha256Pins", List.copyOf(pins)); + byte[] canonical = Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(binding)); + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(canonical)); + } catch (Exception ex) { + throw new IllegalStateException("JWT materializer trust binding digest is unavailable", ex); + } + } + + public static boolean matchesPeer( + java.security.cert.Certificate[] peerCertificates, Binding binding) { + if (peerCertificates == null || peerCertificates.length == 0 || binding == null) { + return false; + } + if (!(peerCertificates[0] instanceof X509Certificate certificate)) { + return false; + } + try { + certificate.checkValidity(); + Collection> subjectAlternativeNames = certificate.getSubjectAlternativeNames(); + if (subjectAlternativeNames == null) { + return false; + } + String foundUri = null; + int uriCount = 0; + for (List entry : subjectAlternativeNames) { + if (entry.size() < 2 || !(entry.get(0) instanceof Integer type) || type != 6) { + continue; + } + uriCount++; + if (!(entry.get(1) instanceof String uri)) { + return false; + } + foundUri = uri; + } + if (uriCount != 1 || !binding.expectedPeerUri().equals(foundUri)) { + return false; + } + byte[] spkiDigest = + MessageDigest.getInstance("SHA-256").digest(certificate.getPublicKey().getEncoded()); + byte[] configuredPin = HexFormat.of().parseHex(binding.peerSpkiSha256Pins().get(0)); + boolean matched = MessageDigest.isEqual(spkiDigest, configuredPin); + for (int index = 1; index < binding.peerSpkiSha256Pins().size(); index++) { + byte[] pin = HexFormat.of().parseHex(binding.peerSpkiSha256Pins().get(index)); + matched |= MessageDigest.isEqual(spkiDigest, pin); + } + return matched; + } catch (CertificateException | NoSuchAlgorithmException | RuntimeException ex) { + return false; + } + } + + public record Binding( + String environmentId, + String clusterId, + String namespace, + String expectedClusterIncarnationUid, + String expectedNamespaceUid, + String expectedPeerUri, + List peerSpkiSha256Pins, + String configRevision, + String bindingDigest) { + public Binding { + Objects.requireNonNull(environmentId, "Environment identity is required"); + Objects.requireNonNull(clusterId, "Cluster identity is required"); + Objects.requireNonNull(namespace, "Namespace identity is required"); + canonicalUuid(expectedClusterIncarnationUid); + canonicalUuid(expectedNamespaceUid); + Objects.requireNonNull(expectedPeerUri, "Materializer URI identity is required"); + peerSpkiSha256Pins = List.copyOf(peerSpkiSha256Pins); + if (peerSpkiSha256Pins.isEmpty() || peerSpkiSha256Pins.size() > 8) { + throw new IllegalArgumentException("JWT materializer certificate pins are unavailable"); + } + for (String pin : peerSpkiSha256Pins) { + if (!SHA256.matcher(pin).matches()) { + throw new IllegalArgumentException("JWT materializer certificate pins are malformed"); + } + } + Objects.requireNonNull(configRevision, "Materializer trust revision is required"); + if (!REVISION.matcher(configRevision).matches() || !SHA256.matcher(bindingDigest).matches()) { + throw new IllegalArgumentException("JWT materializer trust binding digest is malformed"); + } + if (peerSpkiSha256Pins.stream().distinct().count() != peerSpkiSha256Pins.size()) { + throw new IllegalArgumentException("JWT materializer certificate pins are duplicated"); + } + AccountJwtSignerDesiredStateRepository.Binding stateBinding = + new AccountJwtSignerDesiredStateRepository.Binding( + environmentId, + clusterId, + namespace, + AccountJwtSignerDesiredStateRepository.CustodyMode + .INTERIM_ACCOUNT_ONLY_MOUNTED_FALLBACK); + if (!validExpectedPeerUri(stateBinding.namespace(), expectedPeerUri)) { + throw new IllegalArgumentException("JWT materializer workload identity is not canonical"); + } + String expectedDigest = + computeBindingDigest( + configRevision, + environmentId, + clusterId, + namespace, + expectedClusterIncarnationUid, + expectedNamespaceUid, + expectedPeerUri, + peerSpkiSha256Pins); + if (!expectedDigest.equals(bindingDigest)) { + throw new IllegalArgumentException("JWT materializer trust binding digest is invalid"); + } + } + + public AccountJwtSignerDesiredStateRepository.Binding accountBinding() { + return new AccountJwtSignerDesiredStateRepository.Binding( + environmentId, + clusterId, + namespace, + AccountJwtSignerDesiredStateRepository.CustodyMode.INTERIM_ACCOUNT_ONLY_MOUNTED_FALLBACK); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountJwtValidatorInventoryBinding.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountJwtValidatorInventoryBinding.java new file mode 100644 index 0000000000..6f775620ee --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountJwtValidatorInventoryBinding.java @@ -0,0 +1,842 @@ +package net.firedevops.firemud.accountservice.config; + +import java.io.IOException; +import java.net.Inet6Address; +import java.net.InetAddress; +import java.nio.ByteBuffer; +import java.nio.channels.SeekableByteChannel; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.LinkOption; +import java.nio.file.Path; +import java.nio.file.StandardOpenOption; +import java.nio.file.attribute.BasicFileAttributes; +import java.nio.file.attribute.PosixFilePermission; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.concurrent.atomic.AtomicReference; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; + +/** + * Default-inactive, independently protected expected validator applicability and runtime pins. + * + *

This binding is an operator-installed input, never learned from Kubernetes labels, caller + * claims, a first read, or the readiness plan's partial applicability matrix. It provides no + * readiness, promotion, or per-validator acceptance authority. + */ +public final class AccountJwtValidatorInventoryBinding { + public static final int MAX_BINDING_BYTES = 32 * 1024; + public static final int MAX_RUNTIME_CONFIG_BYTES = 8 * 1024; + public static final Path PROTECTED_BINDING_PATH = + Path.of("/etc/firemud/account-jwt-api/validator-inventory.json"); + private static final Path PROTECTED_ROOT = Path.of("/etc/firemud/account-jwt-api"); + private static final String VERSION = "account-jwt-validator-inventory-binding/v2"; + private static final String RUNTIME_CONFIG_ENV = "FIREMUD_JWT_VERIFIER_CONFIG"; + private static final Set ROOT_FIELDS = + Set.of( + "version", + "enabled", + "configRevision", + "environmentId", + "clusterId", + "namespace", + "expectedClusterIncarnationUid", + "expectedNamespaceUid", + "apiBindingRevision", + "apiBindingDigest", + "validators", + "bindingDigest"); + private static final Set VALIDATOR_FIELDS = + Set.of( + "validatorId", + "deploymentName", + "deploymentUid", + "selector", + "replicas", + "containerName", + "image", + "jwksUri", + "maxCacheAgeSeconds", + "profiles", + "receiverServiceUri", + "receiverPort", + "receiverPods"); + private static final Set PROFILE_FIELDS = Set.of("tokenProfile", "audience"); + private static final Set RECEIVER_POD_FIELDS = + Set.of("podUid", "podIp", "leafSpkiSha256"); + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + private static final Pattern DNS_LABEL = Pattern.compile("[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?"); + private static final Pattern ENVIRONMENT = DNS_LABEL; + private static final Pattern CLUSTER = Pattern.compile("[A-Za-z0-9][A-Za-z0-9._:-]{0,127}"); + private static final Pattern REVISION = CLUSTER; + private static final Pattern SHA256 = Pattern.compile("[0-9a-f]{64}"); + private static final Pattern UID = + Pattern.compile("[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}"); + private static final Pattern LABEL_KEY = + Pattern.compile( + "[A-Za-z0-9](?:[A-Za-z0-9_.-]{0,61}[A-Za-z0-9])?(?:/[A-Za-z0-9](?:[A-Za-z0-9_.-]{0,61}[A-Za-z0-9])?)?"); + private static final Pattern LABEL_VALUE = + Pattern.compile("(?:[A-Za-z0-9](?:[A-Za-z0-9_.-]{0,61}[A-Za-z0-9])?)?"); + private static final Pattern PROFILE = Pattern.compile("[a-z][a-z0-9-]{0,63}"); + private static final Pattern AUDIENCE = Pattern.compile("[A-Za-z0-9][A-Za-z0-9._:/-]{0,255}"); + private static final Pattern RECEIVER_SERVICE_URI = + Pattern.compile( + "spiffe://firemud/ns/[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?/sa/[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?"); + + private final boolean enabled; + private final String configuredPath; + private final AtomicReference acceptedFile = new AtomicReference<>(); + + /** Creates a disabled binding; production composition must opt in with the one fixed path. */ + public AccountJwtValidatorInventoryBinding() { + this(false, ""); + } + + public AccountJwtValidatorInventoryBinding(boolean enabled, String protectedBindingPath) { + this.enabled = enabled; + String path = protectedBindingPath == null ? "" : protectedBindingPath.trim(); + this.configuredPath = PROTECTED_BINDING_PATH.toString().equals(path) ? path : ""; + } + + /** Returns the exact immutable protected expectations, or empty when disabled/unavailable. */ + public java.util.Optional current() { + if (!enabled || configuredPath.isBlank()) { + return java.util.Optional.empty(); + } + try { + ProtectedFile file = readProtectedFile(PROTECTED_BINDING_PATH); + ProtectedInventory parsed = parseProtectedBytes(file.bytes()); + FileIdentity existing = acceptedFile.get(); + if (existing == null) { + acceptedFile.compareAndSet(null, file.identity()); + existing = acceptedFile.get(); + } + if (!file.identity().equals(existing)) { + throw unavailable(); + } + return java.util.Optional.of(parsed); + } catch (RuntimeException | IOException failure) { + return java.util.Optional.empty(); + } + } + + static ProtectedInventory parseProtectedBytes(byte[] bytes) { + if (bytes == null || bytes.length == 0 || bytes.length > MAX_BINDING_BYTES) { + throw unavailable(); + } + try { + JsonNode root = JSON.readTree(decodeUtf8(bytes)); + requireObjectFields(root, ROOT_FIELDS); + if (!VERSION.equals(requiredText(root, "version", 96)) + || !"true".equals(requiredText(root, "enabled", 5))) { + throw unavailable(); + } + String revision = requiredText(root, "configRevision", 128); + String environmentId = requiredText(root, "environmentId", 63); + String clusterId = requiredText(root, "clusterId", 128); + String namespace = requiredText(root, "namespace", 63); + String clusterUid = canonicalUid(requiredText(root, "expectedClusterIncarnationUid", 36)); + String namespaceUid = canonicalUid(requiredText(root, "expectedNamespaceUid", 36)); + String apiRevision = requiredText(root, "apiBindingRevision", 128); + String apiDigest = requiredText(root, "apiBindingDigest", 64); + String digest = requiredText(root, "bindingDigest", 64); + if (!REVISION.matcher(revision).matches() + || !ENVIRONMENT.matcher(environmentId).matches() + || !CLUSTER.matcher(clusterId).matches() + || !DNS_LABEL.matcher(namespace).matches() + || !REVISION.matcher(apiRevision).matches() + || !SHA256.matcher(apiDigest).matches() + || !SHA256.matcher(digest).matches() + || !digest.equals(computeBindingDigest(root))) { + throw unavailable(); + } + List validators = parseValidators(root.get("validators")); + if (validators.isEmpty() || validators.size() > 32) { + throw unavailable(); + } + return new ProtectedInventory( + revision, + environmentId, + clusterId, + namespace, + clusterUid, + namespaceUid, + apiRevision, + apiDigest, + digest, + validators); + } catch (IllegalArgumentException failure) { + throw unavailable(); + } catch (RuntimeException failure) { + throw unavailable(); + } + } + + public static String computeBindingDigest(JsonNode root) { + try { + requireObjectFields(root, ROOT_FIELDS); + Map value = new LinkedHashMap<>(); + for (String field : ROOT_FIELDS) { + if (!"bindingDigest".equals(field)) { + JsonNode node = root.get(field); + value.put(field, JSON.readValue(JSON.writeValueAsString(node), Object.class)); + } + } + byte[] canonical = Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(canonical)); + } catch (IOException | NoSuchAlgorithmException | RuntimeException failure) { + throw unavailable(); + } + } + + private static List parseValidators(JsonNode node) { + if (node == null || !node.isArray() || node.isEmpty() || node.size() > 32) { + throw unavailable(); + } + List result = new ArrayList<>(); + Set ids = new LinkedHashSet<>(); + Set deployments = new LinkedHashSet<>(); + Set expectedPodUids = new LinkedHashSet<>(); + Set expectedPodIps = new LinkedHashSet<>(); + Set expectedPodSpkis = new LinkedHashSet<>(); + for (JsonNode validator : node) { + requireObjectFields(validator, VALIDATOR_FIELDS); + String id = requiredText(validator, "validatorId", 63); + String deployment = requiredText(validator, "deploymentName", 63); + String deploymentUid = canonicalUid(requiredText(validator, "deploymentUid", 36)); + String container = requiredText(validator, "containerName", 63); + String image = requiredText(validator, "image", 512); + String jwksUri = canonicalJwksUri(requiredText(validator, "jwksUri", 512)); + int replicas = exactInt(validator.get("replicas"), 1, 128); + int maximumCacheAge = exactInt(validator.get("maxCacheAgeSeconds"), 1, 300); + if (!DNS_LABEL.matcher(id).matches() + || !DNS_LABEL.matcher(deployment).matches() + || !DNS_LABEL.matcher(container).matches() + || !image.matches("[^\\s@]+@sha256:[0-9a-f]{64}") + || !ids.add(id) + || !deployments.add(deployment)) { + throw unavailable(); + } + Map selector = parseSelector(validator.get("selector")); + List profiles = parseProfiles(validator.get("profiles")); + if (profiles.isEmpty()) { + throw unavailable(); + } + List receiverPods = + parseReceiverPods(validator.get("receiverPods"), replicas); + for (ReceiverPodPin pin : receiverPods) { + // Validator workloads are distinct expected instances in this closed LOGIN matrix. A + // shared leaf key would make the TLS peer prove only possession by either Pod, not the + // exact Pod UID selected by the owner-observed inventory. + if (!expectedPodUids.add(pin.podUid()) + || !expectedPodIps.add(pin.podIp()) + || !expectedPodSpkis.add(pin.leafSpkiSha256())) { + throw unavailable(); + } + } + String runtimeConfig = canonicalRuntimeConfig(jwksUri, maximumCacheAge, profiles); + if (runtimeConfig.getBytes(StandardCharsets.UTF_8).length > MAX_RUNTIME_CONFIG_BYTES) { + throw unavailable(); + } + result.add( + new ValidatorExpectation( + id, + deployment, + deploymentUid, + selector, + replicas, + container, + image, + jwksUri, + maximumCacheAge, + profiles, + runtimeConfig, + canonicalReceiverServiceUri(requiredText(validator, "receiverServiceUri", 256)), + exactInt(validator.get("receiverPort"), 1, 65535), + receiverPods)); + } + return List.copyOf(result); + } + + private static List parseReceiverPods(JsonNode node, int replicas) { + if (node == null || !node.isArray() || node.size() != replicas || node.size() > 128) { + throw unavailable(); + } + List pins = new ArrayList<>(); + Set podUids = new LinkedHashSet<>(); + Set podIps = new LinkedHashSet<>(); + Set podSpkis = new LinkedHashSet<>(); + String previousUid = null; + for (JsonNode pod : node) { + requireObjectFields(pod, RECEIVER_POD_FIELDS); + String uid = canonicalUid(requiredText(pod, "podUid", 36)); + String ip = canonicalPodIp(requiredText(pod, "podIp", 45)); + String spki = requiredText(pod, "leafSpkiSha256", 64); + if (!SHA256.matcher(spki).matches() + || !podUids.add(uid) + || !podIps.add(ip) + || !podSpkis.add(spki) + || (previousUid != null && previousUid.compareTo(uid) >= 0)) { + throw unavailable(); + } + previousUid = uid; + pins.add(new ReceiverPodPin(uid, ip, spki)); + } + return List.copyOf(pins); + } + + private static String canonicalReceiverServiceUri(String value) { + if (!RECEIVER_SERVICE_URI.matcher(value).matches()) { + throw unavailable(); + } + return value; + } + + public static String canonicalPodIp(String value) { + if (value == null || value.isBlank() || value.indexOf('%') >= 0) { + throw unavailable(); + } + try { + if (value.indexOf(':') < 0) { + String[] components = value.split("\\.", -1); + if (components.length != 4) { + throw unavailable(); + } + for (String component : components) { + if (component.isEmpty() + || (component.length() > 1 && component.charAt(0) == '0') + || !component.matches("[0-9]{1,3}") + || Integer.parseInt(component) > 255) { + throw unavailable(); + } + } + if ("0.0.0.0".equals(value) || "255.255.255.255".equals(value)) { + throw unavailable(); + } + return value; + } + if (!value.matches("[0-9A-Fa-f:]+")) { + throw unavailable(); + } + InetAddress address = InetAddress.getByName(value); + if (!(address instanceof Inet6Address) + || !canonicalIpv6(address.getAddress()).equals(value)) { + throw unavailable(); + } + return value; + } catch (IOException | NumberFormatException failure) { + throw unavailable(); + } + } + + private static String canonicalIpv6(byte[] bytes) { + if (bytes.length != 16) { + throw unavailable(); + } + int[] groups = new int[8]; + for (int index = 0; index < groups.length; index++) { + groups[index] = + Byte.toUnsignedInt(bytes[index * 2]) << 8 | Byte.toUnsignedInt(bytes[index * 2 + 1]); + } + int bestStart = -1; + int bestLength = 1; + for (int index = 0; index < groups.length; ) { + if (groups[index] != 0) { + index++; + continue; + } + int end = index; + while (end < groups.length && groups[end] == 0) { + end++; + } + if (end - index > bestLength) { + bestStart = index; + bestLength = end - index; + } + index = end; + } + StringBuilder canonical = new StringBuilder(); + for (int index = 0; index < groups.length; ) { + if (index == bestStart) { + canonical.append("::"); + index += bestLength; + continue; + } + if (canonical.length() > 0 && canonical.charAt(canonical.length() - 1) != ':') { + canonical.append(':'); + } + canonical.append(Integer.toHexString(groups[index])); + index++; + } + return canonical.toString(); + } + + private static Map parseSelector(JsonNode node) { + if (node == null || !node.isObject() || node.isEmpty() || node.size() > 16) { + throw unavailable(); + } + Map selector = new LinkedHashMap<>(); + for (Map.Entry entry : node.properties()) { + if (!LABEL_KEY.matcher(entry.getKey()).matches() + || !entry.getValue().isTextual() + || !LABEL_VALUE.matcher(entry.getValue().asText()).matches()) { + throw unavailable(); + } + selector.put(entry.getKey(), entry.getValue().asText()); + } + return Map.copyOf(selector); + } + + private static List parseProfiles(JsonNode node) { + if (node == null || !node.isArray() || node.isEmpty() || node.size() > 32) { + throw unavailable(); + } + List profiles = new ArrayList<>(); + Set unique = new LinkedHashSet<>(); + for (JsonNode profile : node) { + requireObjectFields(profile, PROFILE_FIELDS); + String name = requiredText(profile, "tokenProfile", 64); + String audience = requiredText(profile, "audience", 256); + if (!PROFILE.matcher(name).matches() + || !AUDIENCE.matcher(audience).matches() + || !unique.add(name + "\u0000" + audience)) { + throw unavailable(); + } + profiles.add(new ProfileExpectation(name, audience)); + } + profiles.sort( + Comparator.comparing(ProfileExpectation::tokenProfile) + .thenComparing(ProfileExpectation::audience)); + return List.copyOf(profiles); + } + + private static String canonicalRuntimeConfig( + String jwksUri, int maxCacheAgeSeconds, List profiles) { + try { + List> profileValues = + profiles.stream() + .map( + profile -> + Map.of( + "tokenProfile", profile.tokenProfile(), "audience", profile.audience())) + .toList(); + Map runtime = + Map.of( + "algorithm", + "RS256", + "jwksUri", + jwksUri, + "maxCacheAgeSeconds", + maxCacheAgeSeconds, + "profiles", + profileValues); + return new String( + Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(runtime)), + StandardCharsets.UTF_8); + } catch (IOException | RuntimeException failure) { + throw unavailable(); + } + } + + private static String canonicalJwksUri(String value) { + try { + java.net.URI uri = java.net.URI.create(value); + if (!"https".equalsIgnoreCase(uri.getScheme()) + || uri.getHost() == null + || uri.getRawUserInfo() != null + || uri.getRawQuery() != null + || uri.getRawFragment() != null + || !"/.well-known/jwks.json".equals(uri.getRawPath())) { + throw unavailable(); + } + return uri.toASCIIString(); + } catch (RuntimeException failure) { + throw unavailable(); + } + } + + private static ProtectedFile readProtectedFile(Path path) throws IOException { + if (!path.equals(PROTECTED_BINDING_PATH) + || Files.isSymbolicLink(path) + || !path.equals(path.toRealPath())) { + throw unavailable(); + } + verifyProtectedDirectory(PROTECTED_ROOT); + BasicFileAttributes before = + Files.readAttributes(path, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS); + Set mode = Files.getPosixFilePermissions(path, LinkOption.NOFOLLOW_LINKS); + Object owner = Files.getAttribute(path, "unix:uid", LinkOption.NOFOLLOW_LINKS); + Object group = Files.getAttribute(path, "unix:gid", LinkOption.NOFOLLOW_LINKS); + if (!before.isRegularFile() + || before.size() <= 0 + || before.size() > MAX_BINDING_BYTES + || !(owner instanceof Number uid) + || uid.longValue() != 0L + || !(group instanceof Number gid) + || writable(mode) + || !mode.contains(PosixFilePermission.OWNER_READ) + || mode.contains(PosixFilePermission.OTHERS_READ)) { + throw unavailable(); + } + byte[] bytes = new byte[(int) before.size()]; + try (SeekableByteChannel channel = + Files.newByteChannel(path, StandardOpenOption.READ, LinkOption.NOFOLLOW_LINKS)) { + ByteBuffer buffer = ByteBuffer.wrap(bytes); + while (buffer.hasRemaining()) { + if (channel.read(buffer) < 0) { + throw unavailable(); + } + } + if (channel.read(ByteBuffer.allocate(1)) != -1) { + throw unavailable(); + } + } + BasicFileAttributes after = + Files.readAttributes(path, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS); + Set afterMode = + Files.getPosixFilePermissions(path, LinkOption.NOFOLLOW_LINKS); + Object afterOwner = Files.getAttribute(path, "unix:uid", LinkOption.NOFOLLOW_LINKS); + Object afterGroup = Files.getAttribute(path, "unix:gid", LinkOption.NOFOLLOW_LINKS); + if (!sameAttributes(before, after) + || !mode.equals(afterMode) + || !Objects.equals(owner, afterOwner) + || !Objects.equals(group, afterGroup)) { + throw unavailable(); + } + FileIdentity identity = + new FileIdentity( + String.valueOf(before.fileKey()), + before.size(), + before.lastModifiedTime().toMillis(), + uid.longValue(), + gid.longValue(), + Set.copyOf(mode), + sha256(bytes)); + return new ProtectedFile(bytes, identity); + } + + private static void verifyProtectedDirectory(Path directory) throws IOException { + if (!directory.equals(directory.toRealPath()) + || !Files.isDirectory(directory, LinkOption.NOFOLLOW_LINKS)) { + throw unavailable(); + } + Object owner = Files.getAttribute(directory, "unix:uid", LinkOption.NOFOLLOW_LINKS); + Set mode = + Files.getPosixFilePermissions(directory, LinkOption.NOFOLLOW_LINKS); + if (!(owner instanceof Number uid) + || uid.longValue() != 0L + || mode.contains(PosixFilePermission.GROUP_WRITE) + || mode.contains(PosixFilePermission.OTHERS_WRITE)) { + throw unavailable(); + } + } + + private static void requireObjectFields(JsonNode node, Set expected) { + if (node == null || !node.isObject() || node.size() != expected.size()) { + throw unavailable(); + } + for (Map.Entry field : node.properties()) { + if (!expected.contains(field.getKey()) + || field.getValue() == null + || field.getValue().isNull()) { + throw unavailable(); + } + } + } + + private static String requiredText(JsonNode node, String field, int maximumLength) { + JsonNode value = node.get(field); + if (value == null + || !value.isTextual() + || value.asText().isBlank() + || value.asText().length() > maximumLength) { + throw unavailable(); + } + return value.asText(); + } + + private static int exactInt(JsonNode node, int minimum, int maximum) { + if (node == null || !node.isIntegralNumber() || !node.canConvertToInt()) { + throw unavailable(); + } + int value = node.intValue(); + if (value < minimum || value > maximum) { + throw unavailable(); + } + return value; + } + + private static String canonicalUid(String uid) { + if (!UID.matcher(uid).matches() || uid.startsWith("00000000-")) { + throw unavailable(); + } + return uid; + } + + private static String decodeUtf8(byte[] bytes) { + try { + return StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(bytes)) + .toString(); + } catch (CharacterCodingException failure) { + throw unavailable(); + } + } + + private static String sha256(byte[] bytes) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (Exception failure) { + throw unavailable(); + } + } + + private static boolean sameAttributes(BasicFileAttributes before, BasicFileAttributes after) { + return after.isRegularFile() + && Objects.equals(before.fileKey(), after.fileKey()) + && before.size() == after.size() + && before.lastModifiedTime().equals(after.lastModifiedTime()); + } + + private static boolean writable(Set mode) { + return mode.contains(PosixFilePermission.OWNER_WRITE) + || mode.contains(PosixFilePermission.GROUP_WRITE) + || mode.contains(PosixFilePermission.OTHERS_WRITE); + } + + private static IllegalStateException unavailable() { + return new IllegalStateException( + "Protected Account validator inventory binding is unavailable"); + } + + private record FileIdentity( + String fileKey, + long size, + long modifiedMillis, + long ownerUid, + long groupId, + Set permissions, + String contentSha256) {} + + private record ProtectedFile(byte[] bytes, FileIdentity identity) {} + + /** An immutable, file-backed expected inventory; no public constructor or mutation exists. */ + public static final class ProtectedInventory { + private final String configRevision; + private final String environmentId; + private final String clusterId; + private final String namespace; + private final String expectedClusterIncarnationUid; + private final String expectedNamespaceUid; + private final String apiBindingRevision; + private final String apiBindingDigest; + private final String bindingDigest; + private final List validators; + + private ProtectedInventory( + String configRevision, + String environmentId, + String clusterId, + String namespace, + String expectedClusterIncarnationUid, + String expectedNamespaceUid, + String apiBindingRevision, + String apiBindingDigest, + String bindingDigest, + List validators) { + this.configRevision = configRevision; + this.environmentId = environmentId; + this.clusterId = clusterId; + this.namespace = namespace; + this.expectedClusterIncarnationUid = expectedClusterIncarnationUid; + this.expectedNamespaceUid = expectedNamespaceUid; + this.apiBindingRevision = apiBindingRevision; + this.apiBindingDigest = apiBindingDigest; + this.bindingDigest = bindingDigest; + this.validators = List.copyOf(validators); + } + + public boolean matchesApiBinding(AccountJwtJwksApiBinding.ParsedBinding binding) { + return binding != null + && configRevision != null + && environmentId.equals(binding.environmentId()) + && clusterId.equals(binding.clusterId()) + && namespace.equals(binding.namespace()) + && expectedClusterIncarnationUid.equals(binding.expectedClusterIncarnationUid()) + && expectedNamespaceUid.equals(binding.expectedNamespaceUid()) + && apiBindingRevision.equals(binding.configRevision()) + && apiBindingDigest.equals(binding.bindingDigest()); + } + + public String configRevision() { + return configRevision; + } + + public String environmentId() { + return environmentId; + } + + public String clusterId() { + return clusterId; + } + + public String namespace() { + return namespace; + } + + public String expectedClusterIncarnationUid() { + return expectedClusterIncarnationUid; + } + + public String expectedNamespaceUid() { + return expectedNamespaceUid; + } + + public String apiBindingRevision() { + return apiBindingRevision; + } + + public String apiBindingDigest() { + return apiBindingDigest; + } + + public String bindingDigest() { + return bindingDigest; + } + + public List validators() { + return validators; + } + } + + public static final class ValidatorExpectation { + private final String validatorId; + private final String deploymentName; + private final String deploymentUid; + private final Map selector; + private final int replicas; + private final String containerName; + private final String image; + private final String jwksUri; + private final int maxCacheAgeSeconds; + private final List profiles; + private final String canonicalRuntimeConfig; + private final String receiverServiceUri; + private final int receiverPort; + private final List receiverPods; + + private ValidatorExpectation( + String validatorId, + String deploymentName, + String deploymentUid, + Map selector, + int replicas, + String containerName, + String image, + String jwksUri, + int maxCacheAgeSeconds, + List profiles, + String canonicalRuntimeConfig, + String receiverServiceUri, + int receiverPort, + List receiverPods) { + this.validatorId = validatorId; + this.deploymentName = deploymentName; + this.deploymentUid = deploymentUid; + this.selector = Map.copyOf(selector); + this.replicas = replicas; + this.containerName = containerName; + this.image = image; + this.jwksUri = jwksUri; + this.maxCacheAgeSeconds = maxCacheAgeSeconds; + this.profiles = List.copyOf(profiles); + this.canonicalRuntimeConfig = canonicalRuntimeConfig; + this.receiverServiceUri = receiverServiceUri; + this.receiverPort = receiverPort; + this.receiverPods = List.copyOf(receiverPods); + } + + public String validatorId() { + return validatorId; + } + + public String deploymentName() { + return deploymentName; + } + + public String deploymentUid() { + return deploymentUid; + } + + public Map selector() { + return selector; + } + + public int replicas() { + return replicas; + } + + public String containerName() { + return containerName; + } + + public String image() { + return image; + } + + public String jwksUri() { + return jwksUri; + } + + public int maxCacheAgeSeconds() { + return maxCacheAgeSeconds; + } + + public List profiles() { + return profiles; + } + + public String canonicalRuntimeConfig() { + return canonicalRuntimeConfig; + } + + public String receiverServiceUri() { + return receiverServiceUri; + } + + public int receiverPort() { + return receiverPort; + } + + public List receiverPods() { + return receiverPods; + } + } + + public record ReceiverPodPin(String podUid, String podIp, String leafSpkiSha256) {} + + public record ProfileExpectation(String tokenProfile, String audience) {} +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountControlUiCommittedIssuanceRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountControlUiCommittedIssuanceRepository.java new file mode 100644 index 0000000000..f12f41ea2b --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountControlUiCommittedIssuanceRepository.java @@ -0,0 +1,280 @@ +package net.firedevops.firemud.accountservice.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import java.util.regex.Pattern; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Read-only exact lookup of immutable Account control-ui issuance evidence. */ +@Repository +public class AccountControlUiCommittedIssuanceRepository { + private static final String TABLE = "account_control_ui_issuance_operations"; + private static final Pattern TOKEN_HASH = Pattern.compile("[0-9a-f]{64}"); + private static final int MAX_CLAIMS = 16 * 1024; + private static final int MAX_SOURCE = 131072; + private static final int MAX_BUNDLE = 131072; + private static final int MAX_SIGNER_RECEIPT = 65536; + + private final DSLContext dsl; + + @SuppressFBWarnings( + value = {"EI_EXPOSE_REP2", "CT_CONSTRUCTOR_THROW"}, + justification = + "Spring injects the shared transaction-aware DSLContext; this proxyable repository only validates that dependency and acquires no resources in its constructor.") + public AccountControlUiCommittedIssuanceRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl); + } + + /** Reads only the exact still-COMMITTED issuance row in the caller's Account transaction. */ + @Transactional(propagation = Propagation.MANDATORY) + public Optional readCommitted(String tokenHash) { + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Committed Account issuance read requires an Account transaction"); + } + if (tokenHash == null || !TOKEN_HASH.matcher(tokenHash).matches()) { + throw denied(); + } + Record row = + dsl.fetchOne( + "SELECT request_id, operation_id, token_jti, account_uuid, tenant_uuid, " + + "caller_workload, caller_context_id, request_digest, claims_payload, " + + "source_payload, bundle_payload, signer_receipt, issued_at_epoch_second, " + + "expires_at_epoch_second, recovery_expires_at, status, token_hash, " + + "pending_registry, active_registry, pending_receipt, committed_at, " + + "recovery_failed_at FROM " + + TABLE + + " WHERE token_hash = ? FOR SHARE", + tokenHash); + if (row == null) { + return Optional.empty(); + } + try { + CommittedIssuance evidence = new CommittedIssuance(row); + if (!"COMMITTED".equals(evidence.status()) + || !tokenHash.equals(evidence.tokenHash()) + || evidence.recoveryFailedAt() != null + || evidence.committedAt() == null + || evidence.pendingReceipt().length == 0) { + throw denied(); + } + return Optional.of(evidence); + } catch (RuntimeException malformed) { + throw denied(); + } + } + + private static IllegalStateException denied() { + return new IllegalStateException( + "Exact committed Account control-ui issuance evidence unavailable"); + } + + private static byte[] bytes(Record row, String field, int maximum) { + byte[] value = row.get(field, byte[].class); + if (value == null || value.length == 0 || value.length > maximum) { + throw denied(); + } + return value.clone(); + } + + private static UUID uuid(Record row, String field) { + UUID value = row.get(field, UUID.class); + if (value == null || isNil(value)) { + throw denied(); + } + return value; + } + + private static boolean isNil(UUID value) { + return value.getMostSignificantBits() == 0L && value.getLeastSignificantBits() == 0L; + } + + private static long positive(Record row, String field) { + Long value = row.get(field, Long.class); + if (value == null || value <= 0L) { + throw denied(); + } + return value; + } + + private static String text(Record row, String field) { + String value = row.get(field, String.class); + if (value == null || value.isBlank()) { + throw denied(); + } + return value; + } + + private static String tokenHash(Record row) { + String value = row.get("token_hash", String.class); + if (value == null || !TOKEN_HASH.matcher(value).matches()) { + throw denied(); + } + return value; + } + + /** Defensive immutable owner row; it does not contain the compact JWT or response envelope. */ + public static final class CommittedIssuance { + private final UUID requestId; + private final UUID operationId; + private final UUID tokenJti; + private final UUID accountId; + private final UUID tenantId; + private final String callerWorkload; + private final UUID callerContextId; + private final String requestDigest; + private final byte[] claims; + private final byte[] source; + private final byte[] bundle; + private final byte[] signerReceipt; + private final long issuedAtEpochSecond; + private final long expiresAtEpochSecond; + private final String status; + private final String tokenHash; + private final byte[] pendingRegistry; + private final byte[] activeRegistry; + private final byte[] pendingReceipt; + private final java.time.OffsetDateTime committedAt; + private final java.time.OffsetDateTime recoveryFailedAt; + + private CommittedIssuance(Record row) { + requestId = uuid(row, "request_id"); + operationId = uuid(row, "operation_id"); + tokenJti = uuid(row, "token_jti"); + accountId = uuid(row, "account_uuid"); + tenantId = uuid(row, "tenant_uuid"); + callerWorkload = text(row, "caller_workload"); + callerContextId = uuid(row, "caller_context_id"); + requestDigest = digest(row, "request_digest"); + claims = bytes(row, "claims_payload", MAX_CLAIMS); + source = bytes(row, "source_payload", MAX_SOURCE); + bundle = bytes(row, "bundle_payload", MAX_BUNDLE); + signerReceipt = bytes(row, "signer_receipt", MAX_SIGNER_RECEIPT); + issuedAtEpochSecond = positive(row, "issued_at_epoch_second"); + expiresAtEpochSecond = positive(row, "expires_at_epoch_second"); + if (expiresAtEpochSecond <= issuedAtEpochSecond + || expiresAtEpochSecond - issuedAtEpochSecond > 300L) { + throw denied(); + } + status = text(row, "status"); + tokenHash = AccountControlUiCommittedIssuanceRepository.tokenHash(row); + pendingRegistry = bytes(row, "pending_registry", 32768); + activeRegistry = bytes(row, "active_registry", 32768); + pendingReceipt = bytes(row, "pending_receipt", 8192); + committedAt = row.get("committed_at", java.time.OffsetDateTime.class); + recoveryFailedAt = row.get("recovery_failed_at", java.time.OffsetDateTime.class); + } + + private static String digest(Record row, String field) { + String value = text(row, field); + if (!Pattern.matches("[0-9a-f]{64}", value)) { + throw denied(); + } + return value; + } + + public UUID requestId() { + return requestId; + } + + public UUID operationId() { + return operationId; + } + + public UUID tokenJti() { + return tokenJti; + } + + public UUID accountId() { + return accountId; + } + + public UUID tenantId() { + return tenantId; + } + + public String callerWorkload() { + return callerWorkload; + } + + public UUID callerContextId() { + return callerContextId; + } + + public String requestDigest() { + return requestDigest; + } + + public byte[] claims() { + return claims.clone(); + } + + public byte[] source() { + return source.clone(); + } + + public byte[] bundle() { + return bundle.clone(); + } + + public byte[] signerReceipt() { + return signerReceipt.clone(); + } + + public long issuedAtEpochSecond() { + return issuedAtEpochSecond; + } + + public long expiresAtEpochSecond() { + return expiresAtEpochSecond; + } + + public String status() { + return status; + } + + public String tokenHash() { + return tokenHash; + } + + public byte[] pendingRegistry() { + return pendingRegistry.clone(); + } + + public byte[] activeRegistry() { + return activeRegistry.clone(); + } + + public byte[] pendingReceipt() { + return pendingReceipt.clone(); + } + + public java.time.OffsetDateTime committedAt() { + return committedAt; + } + + public java.time.OffsetDateTime recoveryFailedAt() { + return recoveryFailedAt; + } + + public long expiryMillis() { + try { + return Math.multiplyExact(expiresAtEpochSecond, 1000L); + } catch (ArithmeticException malformed) { + throw denied(); + } + } + + @Override + public String toString() { + return "AccountControlUiCommittedIssuanceRepository.CommittedIssuance[redacted]"; + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationPendingIdentity.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationPendingIdentity.java new file mode 100644 index 0000000000..fb05ddfa81 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationPendingIdentity.java @@ -0,0 +1,36 @@ +package net.firedevops.firemud.accountservice.repository; + +import java.util.Objects; +import java.util.UUID; +import java.util.regex.Pattern; + +/** + * Immutable pending-issuance identity data; this value is not signing or authorization evidence. + */ +public record AccountGameplayDelegationPendingIdentity( + UUID operationId, + UUID requestId, + UUID accountId, + String callerWorkload, + UUID callerContextId, + String requestDigest, + UUID tokenJti, + long issuedAtEpochSecond, + long notBeforeEpochSecond, + long expiresAtEpochSecond) { + private static final Pattern SHA256 = Pattern.compile("[0-9a-f]{64}"); + + public AccountGameplayDelegationPendingIdentity { + Objects.requireNonNull(operationId); + Objects.requireNonNull(requestId); + Objects.requireNonNull(accountId); + Objects.requireNonNull(callerContextId); + Objects.requireNonNull(tokenJti); + if (requestDigest == null || !SHA256.matcher(requestDigest).matches()) { + throw new IllegalArgumentException("Request digest is malformed"); + } + if (callerWorkload == null || callerWorkload.length() > 256) { + throw new IllegalArgumentException("Caller workload is malformed"); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtJwksPublicationRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtJwksPublicationRepository.java new file mode 100644 index 0000000000..c76f1951e0 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtJwksPublicationRepository.java @@ -0,0 +1,1315 @@ +package net.firedevops.firemud.accountservice.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.ActiveSigner; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.Binding; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.GenerationRequest; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.GenerationResult; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.PreparedGenerationEvidence; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.PromotionOperationEvidence; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.TrustFence; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.databind.json.JsonMapper; + +/** + * Immutable Account-owned evidence for the fixed public JWT ConfigMap projection. + * + *

Every write re-locks the current desired-state row, generation operation, and exact generation + * result through {@link AccountJwtSignerDesiredStateRepository} before touching these rows. The + * repository records intent before external CAS, and its receipts/observations never authorize + * PREPARED, activation, token issuance, or readiness. + */ +@Repository +public class AccountJwtJwksPublicationRepository { + public static final String PUBLIC_JWKS_NAME = "jwt-jwks"; + public static final String JWKS_DATA_KEY = "jwks.json"; + public static final String GENERATION_MARKER_DATA_KEY = "jwt-generation.json"; + public static final int MAX_JWKS_BYTES = 256 * 1024; + public static final int MAX_MARKER_BYTES = 16 * 1024; + + private static final String INTENT_TABLE = "account_jwt_jwks_prepublication_intents"; + private static final String RECEIPT_TABLE = "account_jwt_jwks_publication_receipts"; + private static final String MOUNT_TABLE = "account_jwt_jwks_mount_observations"; + private static final String CUSTODY_MODE = "INTERIM_ACCOUNT_ONLY_MOUNTED_FALLBACK"; + private static final Pattern SHA256 = Pattern.compile("[0-9a-f]{64}"); + private static final Pattern RESOURCE_VERSION = Pattern.compile("[!-~]{1,256}"); + private static final JsonMapper JSON = JsonMapper.builder().build(); + + private final DSLContext dsl; + private final AccountJwtSignerDesiredStateRepository desiredStateRepository; + + @Autowired + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "The constructor only validates trusted Spring collaborators; it performs no I/O or resource acquisition and defines no finalizer.") + public AccountJwtJwksPublicationRepository( + DSLContext dsl, AccountJwtSignerDesiredStateRepository desiredStateRepository) { + this.dsl = Objects.requireNonNull(dsl, "DSLContext is required"); + this.desiredStateRepository = + Objects.requireNonNull(desiredStateRepository, "Desired-state repository is required"); + } + + /** + * Returns the current operation's immutable intent, locking its entire owner chain first. A + * missing intent stays missing; reads never create a publication request. + */ + @Transactional(propagation = Propagation.MANDATORY) + public Optional readCurrentIntent(Binding binding, TrustFence trust) { + requireAccountTransaction(); + GenerationResult result = readAndLockCurrentResult(binding, trust); + GenerationRequest request = desiredStateRepository.readCurrentGenerationRequest(binding, trust); + PrepublicationIntent intent = selectIntent(result.operationId(), true); + if (intent == null) { + return Optional.empty(); + } + verifyIntentMatches(result, request, intent); + return Optional.of(intent); + } + + /** + * Persists the exact Account-constructed public projection before remote ConfigMap CAS. Only an + * exact same-operation retry can read back the existing row; a changed prior object, public + * bytes, API trust identity, generation result, or active fence is a conflict. + */ + @Transactional(propagation = Propagation.MANDATORY) + public PrepublicationIntent recordPrepublicationIntent( + Binding binding, + TrustFence trust, + GenerationResult expectedResult, + GenerationRequest expectedRequest, + String apiBindingDigest, + String apiConfigRevision, + String configMapUid, + String expectedResourceVersion, + String expectedSnapshotDigest, + String jwksJson, + String generationMarkerJson) { + requireWritableAccountTransaction(); + Objects.requireNonNull(expectedResult, "Exact current generation result is required"); + Objects.requireNonNull(expectedRequest, "Exact current generation request is required"); + requireDigest(apiBindingDigest, "protected ConfigMap API binding digest"); + requireRevision(apiConfigRevision, "protected ConfigMap API configuration revision"); + requireUuid(configMapUid, "public ConfigMap UID"); + requireResourceVersion(expectedResourceVersion, "expected ConfigMap resourceVersion"); + requireDigest(expectedSnapshotDigest, "expected ConfigMap snapshot digest"); + requireBounded(jwksJson, MAX_JWKS_BYTES, "public JWKS"); + requireBounded(generationMarkerJson, MAX_MARKER_BYTES, "public generation marker"); + + GenerationResult currentResult = readAndLockCurrentResult(binding, trust); + GenerationRequest currentRequest = + desiredStateRepository.readCurrentGenerationRequest(binding, trust); + requireExactGeneration(expectedResult, currentResult, expectedRequest, currentRequest); + PrepublicationIntent candidate = + PrepublicationIntent.create( + currentResult, + currentRequest, + apiBindingDigest, + apiConfigRevision, + configMapUid, + expectedResourceVersion, + expectedSnapshotDigest, + jwksJson, + generationMarkerJson); + + PrepublicationIntent existing = selectIntent(currentResult.operationId(), true); + if (existing != null) { + verifyIntentMatches(currentResult, currentRequest, existing); + if (!existing.equals(candidate)) { + throw new AccountJwtSignerDesiredStateRepository.IdempotencyConflictException( + "Account JWT JWKS publication intent changed for the same operation"); + } + return existing; + } + + insertIntent(candidate); + PrepublicationIntent readback = selectIntent(currentResult.operationId(), true); + if (readback == null || !readback.equals(candidate)) { + throw new AccountJwtSignerDesiredStateRepository.QuarantinedStateException( + "Account JWT JWKS publication intent did not read back exactly"); + } + return readback; + } + + /** Returns the current operation's persisted intent and optional exact API readback receipt. */ + @Transactional(propagation = Propagation.MANDATORY) + public Optional readCurrentPublication(Binding binding, TrustFence trust) { + requireAccountTransaction(); + GenerationResult result = readAndLockCurrentResult(binding, trust); + GenerationRequest request = desiredStateRepository.readCurrentGenerationRequest(binding, trust); + PrepublicationIntent intent = selectIntent(result.operationId(), true); + if (intent == null) { + return Optional.empty(); + } + verifyIntentMatches(result, request, intent); + PublicationReceipt receipt = selectReceipt(result.operationId(), true); + if (receipt != null) { + verifyReceiptMatches(intent, receipt); + } + MountObservation mount = selectMountObservation(result.operationId(), true); + if (mount != null) { + if (receipt == null) { + throw new AccountJwtSignerDesiredStateRepository.QuarantinedStateException( + "Mounted JWKS observation has no Account publication receipt"); + } + verifyMountMatches(intent, receipt, mount); + } + return Optional.of( + new PublicationEvidence(intent, Optional.ofNullable(receipt), Optional.ofNullable(mount))); + } + + /** + * Recovery-only read of the immutable publication that authorized the exact PREPARED source + * generation. Ordinary current-publication reads remain unavailable while PREPARED. + */ + @Transactional(propagation = Propagation.MANDATORY, readOnly = true) + public PromotionPublicationEvidence readPreparedPublicationForRecovery( + Binding binding, TrustFence trust) { + requireAccountTransaction(); + PreparedGenerationEvidence prepared = + desiredStateRepository.readPreparedGenerationForRecovery(binding, trust); + GenerationResult result = prepared.generationResult(); + PrepublicationIntent intent = selectIntent(result.operationId(), false); + PublicationReceipt receipt = selectReceipt(result.operationId(), false); + MountObservation mount = selectMountObservation(result.operationId(), false); + if (intent == null || receipt == null || mount == null) { + throw new AccountJwtSignerDesiredStateRepository.PromotionPrerequisitesIncompleteException( + "Prepared generation has no exact public prepublication/readback/mount evidence"); + } + verifyPreparedIntentMatches(prepared, intent); + verifyReceiptMatches(intent, receipt); + verifyMountMatches(intent, receipt, mount); + PromotionOperationEvidence promotion = prepared.promotion(); + if (!promotion.prepublicationIntentDigest().equals(intent.intentDigest()) + || !promotion.prepublicationReceiptDigest().equals(receipt.receiptDigest()) + || !promotion.mountedObservationDigest().equals(mount.observationDigest()) + || !promotion.publicConfigMapUid().equals(intent.configMapUid()) + || !promotion.expectedPublicResourceVersion().equals(receipt.observedResourceVersion()) + || !promotion.apiBindingDigest().equals(intent.apiBindingDigest()) + || !promotion.apiConfigRevision().equals(intent.apiConfigRevision()) + || !promotion.expectedPublicJwksJson().equals(intent.jwksJson())) { + throw new AccountJwtSignerDesiredStateRepository.QuarantinedStateException( + "Prepared promotion no longer matches its immutable prepublication evidence"); + } + return new PromotionPublicationEvidence(intent, receipt, mount); + } + + /** + * Persists only an exact GET readback from the protected CAS client. No Kubernetes response body, + * bearer token, or private key is stored. + */ + @Transactional(propagation = Propagation.MANDATORY) + public PublicationReceipt recordPublicationReceipt( + Binding binding, + TrustFence trust, + UUID operationId, + String apiBindingDigest, + String apiConfigRevision, + String configMapUid, + String returnedResourceVersion, + String jwksJson, + String generationMarkerJson) { + requireWritableAccountTransaction(); + Objects.requireNonNull(operationId, "Account JWT signer operation ID is required"); + requireDigest(apiBindingDigest, "protected ConfigMap API binding digest"); + requireRevision(apiConfigRevision, "protected ConfigMap API configuration revision"); + requireUuid(configMapUid, "public ConfigMap UID"); + requireResourceVersion(returnedResourceVersion, "observed ConfigMap resourceVersion"); + requireBounded(jwksJson, MAX_JWKS_BYTES, "public JWKS"); + requireBounded(generationMarkerJson, MAX_MARKER_BYTES, "public generation marker"); + + GenerationResult result = readAndLockCurrentResult(binding, trust); + if (!result.operationId().equals(operationId)) { + throw new AccountJwtSignerDesiredStateRepository.StaleGenerationOperationException( + "Account JWT JWKS receipt is not for the current generation operation"); + } + GenerationRequest request = desiredStateRepository.readCurrentGenerationRequest(binding, trust); + PrepublicationIntent intent = selectIntent(operationId, true); + if (intent == null) { + throw new AccountJwtSignerDesiredStateRepository.QuarantinedStateException( + "Account JWT JWKS publication intent is missing"); + } + verifyIntentMatches(result, request, intent); + if (!intent.apiBindingDigest().equals(apiBindingDigest) + || !intent.apiConfigRevision().equals(apiConfigRevision) + || !intent.configMapUid().equals(configMapUid) + || !intent.jwksJson().equals(jwksJson) + || !intent.generationMarkerJson().equals(generationMarkerJson)) { + throw new AccountJwtSignerDesiredStateRepository.BindingMismatchException( + "Account JWT JWKS readback does not match the protected publication intent"); + } + + PublicationReceipt candidate = PublicationReceipt.create(intent, returnedResourceVersion); + PublicationReceipt existing = selectReceipt(operationId, true); + if (existing != null) { + verifyReceiptMatches(intent, existing); + if (!existing.equals(candidate)) { + throw new AccountJwtSignerDesiredStateRepository.IdempotencyConflictException( + "Account JWT JWKS readback changed for the same operation"); + } + return existing; + } + insertReceipt(candidate); + PublicationReceipt readback = selectReceipt(operationId, true); + if (readback == null || !readback.equals(candidate)) { + throw new AccountJwtSignerDesiredStateRepository.QuarantinedStateException( + "Account JWT JWKS receipt did not read back exactly"); + } + return readback; + } + + /** + * Records a local mounted private/public correspondence result only after the exact same + * operation has a persisted API publication receipt. This observation remains non-authorizing. + */ + @Transactional(propagation = Propagation.MANDATORY) + public MountObservation recordMountedCorrespondence( + Binding binding, + TrustFence trust, + UUID operationId, + String generationMarkerDigest, + String mountedPublicDataDigest, + String localPublicKeyFingerprint) { + requireWritableAccountTransaction(); + Objects.requireNonNull(operationId, "Account JWT signer operation ID is required"); + requireDigest(generationMarkerDigest, "mounted generation marker digest"); + requireDigest(mountedPublicDataDigest, "mounted public projection digest"); + requireDigest(localPublicKeyFingerprint, "mounted public-key fingerprint"); + + GenerationResult result = readAndLockCurrentResult(binding, trust); + if (!result.operationId().equals(operationId)) { + throw new AccountJwtSignerDesiredStateRepository.StaleGenerationOperationException( + "Mounted JWT correspondence is not for the current generation operation"); + } + PrepublicationIntent intent = selectIntent(operationId, true); + PublicationReceipt receipt = selectReceipt(operationId, true); + if (intent == null || receipt == null) { + throw new AccountJwtSignerDesiredStateRepository.QuarantinedStateException( + "Mounted JWT correspondence has no Account publication receipt"); + } + GenerationRequest request = desiredStateRepository.readCurrentGenerationRequest(binding, trust); + verifyIntentMatches(result, request, intent); + verifyReceiptMatches(intent, receipt); + if (!intent.generationMarkerDigest().equals(generationMarkerDigest) + || !intent.publicDataDigest().equals(mountedPublicDataDigest) + || !result.publicKeyFingerprint().equals(localPublicKeyFingerprint)) { + throw new AccountJwtSignerDesiredStateRepository.BindingMismatchException( + "Mounted JWT correspondence does not match Account's exact publication"); + } + + MountObservation candidate = MountObservation.create(intent, receipt); + MountObservation existing = selectMountObservation(operationId, true); + if (existing != null) { + verifyMountMatches(intent, receipt, existing); + if (!existing.equals(candidate)) { + throw new AccountJwtSignerDesiredStateRepository.IdempotencyConflictException( + "Mounted JWT correspondence changed for the same operation"); + } + return existing; + } + insertMountObservation(candidate, binding); + MountObservation readback = selectMountObservation(operationId, true); + if (readback == null || !readback.equals(candidate)) { + throw new AccountJwtSignerDesiredStateRepository.QuarantinedStateException( + "Mounted JWT correspondence did not read back exactly"); + } + return readback; + } + + private GenerationResult readAndLockCurrentResult(Binding binding, TrustFence trust) { + GenerationResult result = desiredStateRepository.readCurrentGenerationResult(binding, trust); + GenerationRequest request = desiredStateRepository.readCurrentGenerationRequest(binding, trust); + if (request.phase() + != AccountJwtSignerDesiredStateRepository.GenerationPhase.GENERATION_RECORDED + || !request.operationId().equals(result.operationId()) + || !request.operationDigest().equals(result.operationDigest()) + || !request.generationReceiptDigest().equals(result.receiptDigest()) + || !request.publicKeyFingerprint().equals(result.publicKeyFingerprint()) + || !request.publicJwkJson().equals(result.publicJwkJson()) + || !request.trustFence().equals(trust)) { + throw new AccountJwtSignerDesiredStateRepository.QuarantinedStateException( + "Account JWT publication is not bound to a complete current generation result"); + } + return result; + } + + private static void requireExactGeneration( + GenerationResult expectedResult, + GenerationResult currentResult, + GenerationRequest expectedRequest, + GenerationRequest currentRequest) { + if (!expectedResult.equals(currentResult) || !expectedRequest.equals(currentRequest)) { + throw new AccountJwtSignerDesiredStateRepository.StaleGenerationOperationException( + "Account JWT publication candidate is not the exact current generation result"); + } + } + + private PrepublicationIntent selectIntent(UUID operationId, boolean lock) { + Record row = + dsl.fetchOne( + "SELECT operation_id, environment_id, cluster_id, kubernetes_namespace, custody_mode, " + + "operation_digest, generation_request_digest, generation_receipt_digest, " + + "desired_state_version, expected_cluster_incarnation_uid, expected_namespace_uid, " + + "trust_binding_digest, trust_config_revision, api_binding_digest, api_config_revision, " + + "config_map_name, config_map_uid, expected_resource_version, expected_snapshot_digest, " + + "target_generation, target_kid, public_key_fingerprint, expected_durable_active_json, " + + "expected_published_active_json, jwks_json, generation_marker_json, public_data_digest, " + + "generation_marker_digest, intent_digest FROM " + + INTENT_TABLE + + " WHERE operation_id = ?" + + (lock ? " FOR UPDATE" : ""), + operationId); + return row == null ? null : decodeIntent(row); + } + + private PublicationReceipt selectReceipt(UUID operationId, boolean lock) { + Record row = + dsl.fetchOne( + "SELECT operation_id, environment_id, cluster_id, kubernetes_namespace, custody_mode, " + + "intent_digest, config_map_uid, expected_resource_version, " + + "observed_resource_version, public_data_digest, receipt_digest FROM " + + RECEIPT_TABLE + + " WHERE operation_id = ?" + + (lock ? " FOR UPDATE" : ""), + operationId); + return row == null ? null : decodeReceipt(row); + } + + private MountObservation selectMountObservation(UUID operationId, boolean lock) { + Record row = + dsl.fetchOne( + "SELECT operation_id, intent_digest, publication_receipt_digest, " + + "generation_marker_digest, public_data_digest, public_key_fingerprint, " + + "observation_digest FROM " + + MOUNT_TABLE + + " WHERE operation_id = ?" + + (lock ? " FOR UPDATE" : ""), + operationId); + return row == null ? null : decodeMountObservation(row); + } + + private void insertIntent(PrepublicationIntent intent) { + int inserted = + dsl.execute( + "INSERT INTO " + + INTENT_TABLE + + " (operation_id, environment_id, cluster_id, kubernetes_namespace, custody_mode, " + + "operation_digest, generation_request_digest, generation_receipt_digest, " + + "desired_state_version, expected_cluster_incarnation_uid, expected_namespace_uid, " + + "trust_binding_digest, trust_config_revision, api_binding_digest, api_config_revision, " + + "config_map_name, config_map_uid, expected_resource_version, expected_snapshot_digest, " + + "target_generation, target_kid, public_key_fingerprint, expected_durable_active_json, " + + "expected_published_active_json, jwks_json, generation_marker_json, public_data_digest, " + + "generation_marker_digest, intent_digest) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'jwt-jwks', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + intent.operationId(), + intent.binding().environmentId(), + intent.binding().clusterId(), + intent.binding().namespace(), + CUSTODY_MODE, + intent.operationDigest(), + intent.generationRequestDigest(), + intent.generationReceiptDigest(), + intent.desiredStateVersion(), + UUID.fromString(intent.trustFence().expectedClusterIncarnationUid()), + UUID.fromString(intent.trustFence().expectedNamespaceUid()), + intent.trustFence().bindingDigest(), + intent.trustFence().configRevision(), + intent.apiBindingDigest(), + intent.apiConfigRevision(), + UUID.fromString(intent.configMapUid()), + intent.expectedResourceVersion(), + intent.expectedSnapshotDigest(), + Long.parseLong(intent.targetGeneration()), + intent.targetKid(), + intent.publicKeyFingerprint(), + activeJson(intent.expectedDurableActive()), + activeJson(intent.expectedPublishedActive()), + intent.jwksJson(), + intent.generationMarkerJson(), + intent.publicDataDigest(), + intent.generationMarkerDigest(), + intent.intentDigest()); + if (inserted != 1) { + throw new AccountJwtSignerDesiredStateRepository.StorageUnavailableException( + "Account JWT JWKS intent insert was ambiguous"); + } + } + + private void insertReceipt(PublicationReceipt receipt) { + int inserted = + dsl.execute( + "INSERT INTO " + + RECEIPT_TABLE + + " (operation_id, environment_id, cluster_id, kubernetes_namespace, custody_mode, " + + "intent_digest, config_map_uid, expected_resource_version, " + + "observed_resource_version, public_data_digest, receipt_digest) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + receipt.operationId(), + receipt.binding().environmentId(), + receipt.binding().clusterId(), + receipt.binding().namespace(), + receipt.binding().mode().value(), + receipt.intentDigest(), + UUID.fromString(receipt.configMapUid()), + receipt.expectedResourceVersion(), + receipt.observedResourceVersion(), + receipt.publicDataDigest(), + receipt.receiptDigest()); + if (inserted != 1) { + throw new AccountJwtSignerDesiredStateRepository.StorageUnavailableException( + "Account JWT JWKS receipt insert was ambiguous"); + } + } + + private void insertMountObservation(MountObservation observation, Binding binding) { + int inserted = + dsl.execute( + "INSERT INTO " + + MOUNT_TABLE + + " (operation_id, environment_id, cluster_id, kubernetes_namespace, custody_mode, " + + "intent_digest, publication_receipt_digest, " + + "generation_marker_digest, public_data_digest, public_key_fingerprint, " + + "observation_digest) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + observation.operationId(), + binding.environmentId(), + binding.clusterId(), + binding.namespace(), + binding.mode().value(), + observation.intentDigest(), + observation.publicationReceiptDigest(), + observation.generationMarkerDigest(), + observation.publicDataDigest(), + observation.publicKeyFingerprint(), + observation.observationDigest()); + if (inserted != 1) { + throw new AccountJwtSignerDesiredStateRepository.StorageUnavailableException( + "Account mounted JWT correspondence insert was ambiguous"); + } + } + + private PrepublicationIntent decodeIntent(Record row) { + try { + Binding binding = + new Binding( + row.get("environment_id", String.class), + row.get("cluster_id", String.class), + row.get("kubernetes_namespace", String.class), + parseCustodyMode(row.get("custody_mode", String.class))); + return new PrepublicationIntent( + row.get("operation_id", UUID.class), + binding, + row.get("operation_digest", String.class), + row.get("generation_request_digest", String.class), + row.get("generation_receipt_digest", String.class), + positive(row.get("desired_state_version", Long.class), "desired-state version"), + new TrustFence( + row.get("expected_cluster_incarnation_uid", UUID.class).toString(), + row.get("expected_namespace_uid", UUID.class).toString(), + row.get("trust_binding_digest", String.class), + row.get("trust_config_revision", String.class)), + row.get("api_binding_digest", String.class), + row.get("api_config_revision", String.class), + row.get("config_map_name", String.class), + row.get("config_map_uid", UUID.class).toString(), + row.get("expected_resource_version", String.class), + row.get("expected_snapshot_digest", String.class), + Long.toString(positive(row.get("target_generation", Long.class), "target generation")), + row.get("target_kid", String.class), + row.get("public_key_fingerprint", String.class), + parseActive(row.get("expected_durable_active_json", String.class)), + parseActive(row.get("expected_published_active_json", String.class)), + row.get("jwks_json", String.class), + row.get("generation_marker_json", String.class), + row.get("public_data_digest", String.class), + row.get("generation_marker_digest", String.class), + row.get("intent_digest", String.class)); + } catch (RuntimeException ex) { + throw new AccountJwtSignerDesiredStateRepository.QuarantinedStateException( + "Account JWT JWKS intent is malformed", ex); + } + } + + private PublicationReceipt decodeReceipt(Record row) { + try { + return new PublicationReceipt( + row.get("operation_id", UUID.class), + new Binding( + row.get("environment_id", String.class), + row.get("cluster_id", String.class), + row.get("kubernetes_namespace", String.class), + parseCustodyMode(row.get("custody_mode", String.class))), + row.get("intent_digest", String.class), + row.get("config_map_uid", UUID.class).toString(), + row.get("expected_resource_version", String.class), + row.get("observed_resource_version", String.class), + row.get("public_data_digest", String.class), + row.get("receipt_digest", String.class)); + } catch (RuntimeException ex) { + throw new AccountJwtSignerDesiredStateRepository.QuarantinedStateException( + "Account JWT JWKS receipt is malformed", ex); + } + } + + private MountObservation decodeMountObservation(Record row) { + try { + return new MountObservation( + row.get("operation_id", UUID.class), + row.get("intent_digest", String.class), + row.get("publication_receipt_digest", String.class), + row.get("generation_marker_digest", String.class), + row.get("public_data_digest", String.class), + row.get("public_key_fingerprint", String.class), + row.get("observation_digest", String.class)); + } catch (RuntimeException ex) { + throw new AccountJwtSignerDesiredStateRepository.QuarantinedStateException( + "Account mounted JWT correspondence is malformed", ex); + } + } + + private static void verifyIntentMatches( + GenerationResult result, GenerationRequest request, PrepublicationIntent intent) { + if (!intent.operationId().equals(result.operationId()) + || !intent.binding().equals(result.binding()) + || !intent.operationDigest().equals(result.operationDigest()) + || !intent.generationRequestDigest().equals(result.generationRequestDigest()) + || !intent.generationReceiptDigest().equals(result.receiptDigest()) + || intent.desiredStateVersion() != result.desiredStateVersion() + || !intent.trustFence().equals(result.trustFence()) + || !intent.targetGeneration().equals(result.targetGeneration()) + || !intent.targetKid().equals(result.targetKid()) + || !intent.publicKeyFingerprint().equals(result.publicKeyFingerprint()) + || !intent.expectedDurableActive().equals(request.expectedActive()) + || !intent.expectedPublishedActive().equals(request.expectedPublishedActive()) + || !PUBLIC_JWKS_NAME.equals(intent.configMapName()) + || !PrepublicationIntent.digest(intent).equals(intent.intentDigest())) { + throw new AccountJwtSignerDesiredStateRepository.QuarantinedStateException( + "Account JWT JWKS intent no longer matches its current generation result"); + } + } + + private static void verifyPreparedIntentMatches( + PreparedGenerationEvidence prepared, PrepublicationIntent intent) { + GenerationResult result = prepared.generationResult(); + PromotionOperationEvidence promotion = prepared.promotion(); + if (!intent.operationId().equals(result.operationId()) + || !intent.binding().equals(result.binding()) + || !intent.operationDigest().equals(result.operationDigest()) + || !intent.generationRequestDigest().equals(result.generationRequestDigest()) + || !intent.generationReceiptDigest().equals(result.receiptDigest()) + || intent.desiredStateVersion() != result.desiredStateVersion() + || !intent.trustFence().equals(result.trustFence()) + || !intent.targetGeneration().equals(result.targetGeneration()) + || !intent.targetKid().equals(result.targetKid()) + || !intent.publicKeyFingerprint().equals(result.publicKeyFingerprint()) + || !intent.expectedDurableActive().equals(promotion.expectedPreviousActive()) + || !intent.expectedPublishedActive().equals(promotion.expectedPublishedActive()) + || !PUBLIC_JWKS_NAME.equals(intent.configMapName()) + || !PrepublicationIntent.digest(intent).equals(intent.intentDigest())) { + throw new AccountJwtSignerDesiredStateRepository.QuarantinedStateException( + "Prepared Account JWKS intent does not match the exact source generation"); + } + } + + private static void verifyReceiptMatches( + PrepublicationIntent intent, PublicationReceipt receipt) { + if (!receipt.operationId().equals(intent.operationId()) + || !receipt.binding().equals(intent.binding()) + || !receipt.intentDigest().equals(intent.intentDigest()) + || !receipt.configMapUid().equals(intent.configMapUid()) + || !receipt.expectedResourceVersion().equals(intent.expectedResourceVersion()) + || !receipt.publicDataDigest().equals(intent.publicDataDigest()) + || !PublicationReceipt.digest(receipt).equals(receipt.receiptDigest())) { + throw new AccountJwtSignerDesiredStateRepository.QuarantinedStateException( + "Account JWT JWKS receipt is not bound to its immutable intent"); + } + } + + private static void verifyMountMatches( + PrepublicationIntent intent, PublicationReceipt receipt, MountObservation observation) { + if (!observation.operationId().equals(intent.operationId()) + || !observation.intentDigest().equals(intent.intentDigest()) + || !observation.publicationReceiptDigest().equals(receipt.receiptDigest()) + || !observation.generationMarkerDigest().equals(intent.generationMarkerDigest()) + || !observation.publicDataDigest().equals(intent.publicDataDigest()) + || !observation.publicKeyFingerprint().equals(intent.publicKeyFingerprint()) + || !MountObservation.digest(observation).equals(observation.observationDigest())) { + throw new AccountJwtSignerDesiredStateRepository.QuarantinedStateException( + "Mounted JWT correspondence is not bound to its exact Account publication"); + } + } + + private static void requireAccountTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Account JWT JWKS persistence requires the owning Account transaction"); + } + } + + private static void requireWritableAccountTransaction() { + requireAccountTransaction(); + if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException("Account JWT JWKS persistence transaction must be writable"); + } + } + + private static void requireExactCurrentIdentity( + Binding binding, + TrustFence trust, + GenerationResult result, + String apiBindingDigest, + String apiConfigRevision) { + if (!result.binding().equals(binding) + || !result.trustFence().equals(trust) + || !result.trustFence().bindingDigest().equals(trust.bindingDigest()) + || !result.trustFence().configRevision().equals(trust.configRevision())) { + throw new AccountJwtSignerDesiredStateRepository.BindingMismatchException( + "Account JWT publication trust identity changed"); + } + requireDigest(apiBindingDigest, "protected ConfigMap API binding digest"); + requireRevision(apiConfigRevision, "protected ConfigMap API configuration revision"); + } + + private static byte[] canonicalJson(Object value) { + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } catch (IOException ex) { + throw new AccountJwtSignerDesiredStateRepository.StorageUnavailableException( + "Account JWT JWKS canonicalization is unavailable"); + } + } + + private static AccountJwtSignerDesiredStateRepository.CustodyMode parseCustodyMode(String value) { + for (AccountJwtSignerDesiredStateRepository.CustodyMode candidate : + AccountJwtSignerDesiredStateRepository.CustodyMode.values()) { + if (candidate.value().equals(value)) { + return candidate; + } + } + throw new AccountJwtSignerDesiredStateRepository.QuarantinedStateException( + "JWT signer custody mode is unsupported"); + } + + private static String sha256(byte[] bytes) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException ex) { + throw new IllegalStateException("SHA-256 is unavailable", ex); + } + } + + private static void requireDigest(String value, String field) { + if (value == null || !SHA256.matcher(value).matches()) { + throw new IllegalArgumentException("JWT signer " + field + " is malformed"); + } + } + + private static void requireRevision(String value, String field) { + if (value == null || !value.matches("[A-Za-z0-9][A-Za-z0-9._:-]{0,127}")) { + throw new IllegalArgumentException("JWT signer " + field + " is malformed"); + } + } + + private static void requireUuid(String value, String field) { + try { + UUID parsed = UUID.fromString(value); + if (!parsed.toString().equals(value) || parsed.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException(); + } + } catch (RuntimeException ex) { + throw new IllegalArgumentException("JWT signer " + field + " is malformed", ex); + } + } + + private static void requireResourceVersion(String value, String field) { + if (value == null || !RESOURCE_VERSION.matcher(value).matches()) { + throw new IllegalArgumentException("JWT signer " + field + " is malformed"); + } + } + + private static void requireBounded(String value, int limit, String field) { + if (value == null || value.isBlank() || value.getBytes(StandardCharsets.UTF_8).length > limit) { + throw new IllegalArgumentException("JWT signer " + field + " is missing or oversized"); + } + } + + private static long positive(Long value, String field) { + if (value == null || value <= 0L) { + throw new IllegalArgumentException("JWT signer " + field + " is not positive"); + } + return value; + } + + private static String activeJson(Optional active) { + Map value = new LinkedHashMap<>(); + value.put("present", active.isPresent()); + active.ifPresent( + signer -> { + value.put("generation", signer.generation()); + value.put("kid", signer.kid()); + }); + return new String(canonicalJson(value), StandardCharsets.UTF_8); + } + + private static Optional parseActive(String json) { + try { + tools.jackson.databind.JsonNode node = JSON.readTree(json); + if (node == null || !node.isObject() || !node.has("present")) { + throw new IllegalArgumentException(); + } + if (node.size() == 1 + && node.get("present").isBoolean() + && !node.get("present").booleanValue()) { + return Optional.empty(); + } + if (node.size() == 3 + && node.get("present").isBoolean() + && node.get("present").booleanValue() + && node.get("generation").isTextual() + && node.get("kid").isTextual()) { + return Optional.of( + new ActiveSigner(node.get("generation").textValue(), node.get("kid").textValue())); + } + throw new IllegalArgumentException(); + } catch (Exception ex) { + throw new IllegalArgumentException("JWT signer active fence is malformed", ex); + } + } + + /** Fixed non-secret Account intent recorded before an external ConfigMap CAS. */ + public record PrepublicationIntent( + UUID operationId, + Binding binding, + String operationDigest, + String generationRequestDigest, + String generationReceiptDigest, + long desiredStateVersion, + TrustFence trustFence, + String apiBindingDigest, + String apiConfigRevision, + String configMapName, + String configMapUid, + String expectedResourceVersion, + String expectedSnapshotDigest, + String targetGeneration, + String targetKid, + String publicKeyFingerprint, + Optional expectedDurableActive, + Optional expectedPublishedActive, + String jwksJson, + String generationMarkerJson, + String publicDataDigest, + String generationMarkerDigest, + String intentDigest) { + public PrepublicationIntent { + Objects.requireNonNull(operationId, "Account JWT signer operation ID is required"); + Objects.requireNonNull(binding, "Account JWT signer binding is required"); + requireDigest(operationDigest, "operation digest"); + requireDigest(generationRequestDigest, "generation request digest"); + requireDigest(generationReceiptDigest, "generation receipt digest"); + if (desiredStateVersion <= 1L) { + throw new IllegalArgumentException("JWT signer desired-state version is invalid"); + } + Objects.requireNonNull(trustFence, "JWT signer trust fence is required"); + requireDigest(apiBindingDigest, "protected ConfigMap API binding digest"); + requireRevision(apiConfigRevision, "protected ConfigMap API configuration revision"); + if (!PUBLIC_JWKS_NAME.equals(configMapName)) { + throw new IllegalArgumentException("JWT signer public ConfigMap name is not fixed"); + } + requireUuid(configMapUid, "public ConfigMap UID"); + requireResourceVersion(expectedResourceVersion, "expected ConfigMap resourceVersion"); + requireDigest(expectedSnapshotDigest, "expected ConfigMap snapshot digest"); + if (targetGeneration == null || !targetGeneration.matches("[1-9][0-9]{0,18}")) { + throw new IllegalArgumentException("JWT signer target generation is malformed"); + } + if (targetKid == null || !targetKid.matches("[A-Za-z0-9_-]{1,64}")) { + throw new IllegalArgumentException("JWT signer target kid is malformed"); + } + requireDigest(publicKeyFingerprint, "public-key fingerprint"); + expectedDurableActive = Objects.requireNonNull(expectedDurableActive); + expectedPublishedActive = Objects.requireNonNull(expectedPublishedActive); + requireBounded(jwksJson, MAX_JWKS_BYTES, "public JWKS"); + requireBounded(generationMarkerJson, MAX_MARKER_BYTES, "public generation marker"); + requireDigest(publicDataDigest, "public data digest"); + requireDigest(generationMarkerDigest, "generation marker digest"); + requireDigest(intentDigest, "prepublication intent digest"); + if (!publicDataDigest.equals( + AccountJwtJwksPublicationRepository.publicDataDigest(jwksJson, generationMarkerJson)) + || !generationMarkerDigest.equals(digestUtf8(generationMarkerJson))) { + throw new IllegalArgumentException("JWT signer public projection digest is invalid"); + } + if (!intentDigest.equals( + digest( + operationId, + binding, + operationDigest, + generationRequestDigest, + generationReceiptDigest, + desiredStateVersion, + trustFence, + apiBindingDigest, + apiConfigRevision, + configMapName, + configMapUid, + expectedResourceVersion, + expectedSnapshotDigest, + targetGeneration, + targetKid, + publicKeyFingerprint, + expectedDurableActive, + expectedPublishedActive, + jwksJson, + generationMarkerJson, + publicDataDigest, + generationMarkerDigest))) { + throw new IllegalArgumentException("JWT signer prepublication intent digest is invalid"); + } + } + + public static PrepublicationIntent create( + GenerationResult result, + GenerationRequest request, + String apiBindingDigest, + String apiConfigRevision, + String configMapUid, + String expectedResourceVersion, + String expectedSnapshotDigest, + String jwksJson, + String generationMarkerJson) { + return create( + result.operationId(), + result.binding(), + result.operationDigest(), + result.generationRequestDigest(), + result.receiptDigest(), + result.desiredStateVersion(), + result.trustFence(), + apiBindingDigest, + apiConfigRevision, + PUBLIC_JWKS_NAME, + configMapUid, + expectedResourceVersion, + expectedSnapshotDigest, + result.targetGeneration(), + result.targetKid(), + result.publicKeyFingerprint(), + request.expectedActive(), + request.expectedPublishedActive(), + jwksJson, + generationMarkerJson, + AccountJwtJwksPublicationRepository.publicDataDigest(jwksJson, generationMarkerJson), + digestUtf8(generationMarkerJson)); + } + + public static PrepublicationIntent create( + UUID operationId, + Binding binding, + String operationDigest, + String generationRequestDigest, + String generationReceiptDigest, + long desiredStateVersion, + TrustFence trustFence, + String apiBindingDigest, + String apiConfigRevision, + String configMapName, + String configMapUid, + String expectedResourceVersion, + String expectedSnapshotDigest, + String targetGeneration, + String targetKid, + String publicKeyFingerprint, + Optional expectedDurableActive, + Optional expectedPublishedActive, + String jwksJson, + String generationMarkerJson, + String publicDataDigest, + String generationMarkerDigest) { + String intentDigest = + digest( + operationId, + binding, + operationDigest, + generationRequestDigest, + generationReceiptDigest, + desiredStateVersion, + trustFence, + apiBindingDigest, + apiConfigRevision, + configMapName, + configMapUid, + expectedResourceVersion, + expectedSnapshotDigest, + targetGeneration, + targetKid, + publicKeyFingerprint, + expectedDurableActive, + expectedPublishedActive, + jwksJson, + generationMarkerJson, + publicDataDigest, + generationMarkerDigest); + return new PrepublicationIntent( + operationId, + binding, + operationDigest, + generationRequestDigest, + generationReceiptDigest, + desiredStateVersion, + trustFence, + apiBindingDigest, + apiConfigRevision, + configMapName, + configMapUid, + expectedResourceVersion, + expectedSnapshotDigest, + targetGeneration, + targetKid, + publicKeyFingerprint, + expectedDurableActive, + expectedPublishedActive, + jwksJson, + generationMarkerJson, + publicDataDigest, + generationMarkerDigest, + intentDigest); + } + + static String digest(PrepublicationIntent value) { + return digest( + value.operationId(), + value.binding(), + value.operationDigest(), + value.generationRequestDigest(), + value.generationReceiptDigest(), + value.desiredStateVersion(), + value.trustFence(), + value.apiBindingDigest(), + value.apiConfigRevision(), + value.configMapName(), + value.configMapUid(), + value.expectedResourceVersion(), + value.expectedSnapshotDigest(), + value.targetGeneration(), + value.targetKid(), + value.publicKeyFingerprint(), + value.expectedDurableActive(), + value.expectedPublishedActive(), + value.jwksJson(), + value.generationMarkerJson(), + value.publicDataDigest(), + value.generationMarkerDigest()); + } + + private static String digest( + UUID operationId, + Binding binding, + String operationDigest, + String generationRequestDigest, + String generationReceiptDigest, + long desiredStateVersion, + TrustFence trustFence, + String apiBindingDigest, + String apiConfigRevision, + String configMapName, + String configMapUid, + String expectedResourceVersion, + String expectedSnapshotDigest, + String targetGeneration, + String targetKid, + String publicKeyFingerprint, + Optional expectedDurableActive, + Optional expectedPublishedActive, + String jwksJson, + String generationMarkerJson, + String publicDataDigest, + String generationMarkerDigest) { + Map preimage = new LinkedHashMap<>(); + preimage.put("digestVersion", "account-jwt-jwks-prepublication-intent/v1"); + preimage.put("operationId", operationId.toString()); + preimage.put("environmentId", binding.environmentId()); + preimage.put("clusterId", binding.clusterId()); + preimage.put("namespace", binding.namespace()); + preimage.put("custodyMode", CUSTODY_MODE); + preimage.put("operationDigest", operationDigest); + preimage.put("generationRequestDigest", generationRequestDigest); + preimage.put("generationReceiptDigest", generationReceiptDigest); + preimage.put("desiredStateVersion", desiredStateVersion); + preimage.put("expectedClusterIncarnationUid", trustFence.expectedClusterIncarnationUid()); + preimage.put("expectedNamespaceUid", trustFence.expectedNamespaceUid()); + preimage.put("trustBindingDigest", trustFence.bindingDigest()); + preimage.put("trustConfigRevision", trustFence.configRevision()); + preimage.put("apiBindingDigest", apiBindingDigest); + preimage.put("apiConfigRevision", apiConfigRevision); + preimage.put("configMapName", configMapName); + preimage.put("configMapUid", configMapUid); + preimage.put("expectedResourceVersion", expectedResourceVersion); + preimage.put("expectedSnapshotDigest", expectedSnapshotDigest); + preimage.put("targetGeneration", targetGeneration); + preimage.put("targetKid", targetKid); + preimage.put("publicKeyFingerprint", publicKeyFingerprint); + preimage.put( + "expectedDurableActive", expectedDurableActive.map(ActiveSigner::generation).orElse("")); + preimage.put( + "expectedDurableActiveKid", expectedDurableActive.map(ActiveSigner::kid).orElse("")); + preimage.put( + "expectedPublishedActive", + expectedPublishedActive.map(ActiveSigner::generation).orElse("")); + preimage.put( + "expectedPublishedActiveKid", expectedPublishedActive.map(ActiveSigner::kid).orElse("")); + preimage.put("jwksJson", jwksJson); + preimage.put("generationMarkerJson", generationMarkerJson); + preimage.put("publicDataDigest", publicDataDigest); + preimage.put("generationMarkerDigest", generationMarkerDigest); + return sha256(canonicalJson(preimage)); + } + } + + /** Exact ConfigMap readback; it proves publication only, never activation/readiness. */ + public record PublicationReceipt( + UUID operationId, + Binding binding, + String intentDigest, + String configMapUid, + String expectedResourceVersion, + String observedResourceVersion, + String publicDataDigest, + String receiptDigest) { + public PublicationReceipt { + Objects.requireNonNull(operationId, "Account JWT signer operation ID is required"); + Objects.requireNonNull(binding, "Account JWT signer binding is required"); + requireDigest(intentDigest, "prepublication intent digest"); + requireUuid(configMapUid, "public ConfigMap UID"); + requireResourceVersion(expectedResourceVersion, "expected ConfigMap resourceVersion"); + requireResourceVersion(observedResourceVersion, "observed ConfigMap resourceVersion"); + requireDigest(publicDataDigest, "published public data digest"); + requireDigest(receiptDigest, "publication receipt digest"); + if (expectedResourceVersion.equals(observedResourceVersion)) { + throw new IllegalArgumentException("Account JWT ConfigMap resourceVersion did not advance"); + } + if (!receiptDigest.equals( + digest( + operationId, + binding, + intentDigest, + configMapUid, + expectedResourceVersion, + observedResourceVersion, + publicDataDigest))) { + throw new IllegalArgumentException("Account JWT publication receipt digest is invalid"); + } + } + + public static PublicationReceipt create( + PrepublicationIntent intent, String observedResourceVersion) { + String receiptDigest = + digest( + intent.operationId(), + intent.binding(), + intent.intentDigest(), + intent.configMapUid(), + intent.expectedResourceVersion(), + observedResourceVersion, + intent.publicDataDigest()); + return new PublicationReceipt( + intent.operationId(), + intent.binding(), + intent.intentDigest(), + intent.configMapUid(), + intent.expectedResourceVersion(), + observedResourceVersion, + intent.publicDataDigest(), + receiptDigest); + } + + static String digest(PublicationReceipt value) { + return digest( + value.operationId(), + value.binding(), + value.intentDigest(), + value.configMapUid(), + value.expectedResourceVersion(), + value.observedResourceVersion(), + value.publicDataDigest()); + } + + private static String digest( + UUID operationId, + Binding binding, + String intentDigest, + String configMapUid, + String expectedResourceVersion, + String observedResourceVersion, + String publicDataDigest) { + Map preimage = new LinkedHashMap<>(); + preimage.put("digestVersion", "account-jwt-jwks-publication-receipt/v1"); + preimage.put("operationId", operationId.toString()); + preimage.put("environmentId", binding.environmentId()); + preimage.put("clusterId", binding.clusterId()); + preimage.put("namespace", binding.namespace()); + preimage.put("custodyMode", CUSTODY_MODE); + preimage.put("intentDigest", intentDigest); + preimage.put("configMapUid", configMapUid); + preimage.put("expectedResourceVersion", expectedResourceVersion); + preimage.put("observedResourceVersion", observedResourceVersion); + preimage.put("publicDataDigest", publicDataDigest); + return sha256(canonicalJson(preimage)); + } + } + + /** Non-secret Account-local observation of the published private/public mounted projection. */ + public record MountObservation( + UUID operationId, + String intentDigest, + String publicationReceiptDigest, + String generationMarkerDigest, + String publicDataDigest, + String publicKeyFingerprint, + String observationDigest) { + public MountObservation { + Objects.requireNonNull(operationId, "Account JWT signer operation ID is required"); + requireDigest(intentDigest, "prepublication intent digest"); + requireDigest(publicationReceiptDigest, "publication receipt digest"); + requireDigest(generationMarkerDigest, "generation marker digest"); + requireDigest(publicDataDigest, "mounted public data digest"); + requireDigest(publicKeyFingerprint, "mounted public-key fingerprint"); + requireDigest(observationDigest, "mounted observation digest"); + if (!observationDigest.equals( + digest( + operationId, + intentDigest, + publicationReceiptDigest, + generationMarkerDigest, + publicDataDigest, + publicKeyFingerprint))) { + throw new IllegalArgumentException("Mounted JWT observation digest is invalid"); + } + } + + public static MountObservation create(PrepublicationIntent intent, PublicationReceipt receipt) { + String observationDigest = + digest( + intent.operationId(), + intent.intentDigest(), + receipt.receiptDigest(), + intent.generationMarkerDigest(), + intent.publicDataDigest(), + intent.publicKeyFingerprint()); + return new MountObservation( + intent.operationId(), + intent.intentDigest(), + receipt.receiptDigest(), + intent.generationMarkerDigest(), + intent.publicDataDigest(), + intent.publicKeyFingerprint(), + observationDigest); + } + + static String digest(MountObservation value) { + return digest( + value.operationId(), + value.intentDigest(), + value.publicationReceiptDigest(), + value.generationMarkerDigest(), + value.publicDataDigest(), + value.publicKeyFingerprint()); + } + + private static String digest( + UUID operationId, + String intentDigest, + String publicationReceiptDigest, + String generationMarkerDigest, + String publicDataDigest, + String publicKeyFingerprint) { + Map preimage = new LinkedHashMap<>(); + preimage.put("digestVersion", "account-jwt-jwks-mounted-correspondence/v1"); + preimage.put("operationId", operationId.toString()); + preimage.put("intentDigest", intentDigest); + preimage.put("publicationReceiptDigest", publicationReceiptDigest); + preimage.put("generationMarkerDigest", generationMarkerDigest); + preimage.put("publicDataDigest", publicDataDigest); + preimage.put("publicKeyFingerprint", publicKeyFingerprint); + return sha256(canonicalJson(preimage)); + } + } + + public record PublicationEvidence( + PrepublicationIntent intent, + Optional receipt, + Optional mountedCorrespondence) { + public PublicationEvidence { + Objects.requireNonNull(intent); + receipt = Objects.requireNonNull(receipt); + mountedCorrespondence = Objects.requireNonNull(mountedCorrespondence); + } + } + + public record PromotionPublicationEvidence( + PrepublicationIntent intent, + PublicationReceipt receipt, + MountObservation mountedCorrespondence) { + public PromotionPublicationEvidence { + Objects.requireNonNull(intent); + Objects.requireNonNull(receipt); + Objects.requireNonNull(mountedCorrespondence); + verifyReceiptMatches(intent, receipt); + verifyMountMatches(intent, receipt, mountedCorrespondence); + } + } + + /** Canonical digest of all observed ConfigMap data used as the pre-CAS compare fence. */ + public static String snapshotDigest(Map data) { + Objects.requireNonNull(data, "ConfigMap data is required"); + if (data.size() > 128) { + throw new IllegalArgumentException("JWT public ConfigMap data has too many entries"); + } + long totalBytes = 0L; + Map bounded = new LinkedHashMap<>(); + for (Map.Entry entry : data.entrySet()) { + if (entry.getKey() == null + || entry.getKey().isBlank() + || entry.getKey().length() > 253 + || entry.getValue() == null) { + throw new IllegalArgumentException("JWT public ConfigMap data is malformed"); + } + totalBytes += entry.getKey().getBytes(StandardCharsets.UTF_8).length; + totalBytes += entry.getValue().getBytes(StandardCharsets.UTF_8).length; + if (totalBytes > 1024L * 1024L) { + throw new IllegalArgumentException("JWT public ConfigMap data is oversized"); + } + bounded.put(entry.getKey(), entry.getValue()); + } + return sha256(canonicalJson(bounded)); + } + + public static String publicDataDigest(String jwksJson, String generationMarkerJson) { + requireBounded(jwksJson, MAX_JWKS_BYTES, "public JWKS"); + requireBounded(generationMarkerJson, MAX_MARKER_BYTES, "public generation marker"); + Map data = new LinkedHashMap<>(); + data.put(JWKS_DATA_KEY, jwksJson); + data.put(GENERATION_MARKER_DATA_KEY, generationMarkerJson); + return sha256(canonicalJson(data)); + } + + private static String digestUtf8(String value) { + return sha256(value.getBytes(StandardCharsets.UTF_8)); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtReadinessProbeRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtReadinessProbeRepository.java new file mode 100644 index 0000000000..716bbb12e0 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtReadinessProbeRepository.java @@ -0,0 +1,4246 @@ +package net.firedevops.firemud.accountservice.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.io.IOException; +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.Instant; +import java.util.ArrayList; +import java.util.Comparator; +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.Set; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.accountservice.config.AccountJwtReadinessTrustBinding.PeerIdentity; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.ActiveSigner; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.Binding; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.DesiredState; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.GenerationPhase; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.GenerationRequest; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.GenerationResult; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.TrustFence; +import net.firedevops.firemud.accountservice.service.session.AccountJwtReadinessProbeOwnerSelector; +import net.firedevops.firemud.accountservice.service.session.AccountJwtReadinessReceiverInvocationPort.AuthenticatedAcceptance; +import net.firedevops.firemud.accountservice.service.session.AccountJwtReadinessReceiverInvocationPort.PodTarget; +import net.firedevops.firemud.accountservice.service.session.AccountJwtReadinessReceiverInvocationPort.ProbeExpectation; +import net.firedevops.firemud.accountservice.service.session.AccountJwtReadinessReceiverInvocationPort.ReceiverUnavailableException; +import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource.InventorySnapshot; +import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource.ObservationContext; +import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource.ObservationPurpose; +import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource.PodObservation; +import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource.ValidatorObservation; +import net.firedevops.firemud.accountservice.service.session.AccountMountedJwtSignerBundle.ProbeKind; +import net.firedevops.firemud.accountservice.service.session.AccountMountedJwtSignerBundle.SignedProbeDigest; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.security.ControlUiJwtProfileValidator; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.common.security.PlayerBootstrapJwtProfileValidator; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.Result; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; + +/** + * Durable, operation-scoped readiness-probe planning and result evidence for Account's interim + * mounted signer. + * + *

This repository never advances signer lifecycle state. It can record only a validator + * observation already authenticated and verified by the owner-internal readiness service. Every + * operation re-locks and compares the existing desired-state, generation, JWKS publication, and + * mounted-correspondence authorities; probe plans are evidence attached to that owner operation, + * not a second key authority. + */ +@Repository +public class AccountJwtReadinessProbeRepository { + public static final int MAX_VALIDATOR_CACHE_AGE_SECONDS = 300; + public static final int PROBE_LIFETIME_SECONDS = 300; + public static final int MAX_ENTRIES_PER_OPERATION = 256; + public static final int MAX_POD_RECEIPTS_PER_OPERATION = 256; + public static final String INVENTORY_STATUS = "PARTIAL_UNCONFIRMED"; + public static final int INVENTORY_PLAN_VERSION = 2; + + private static final String PLAN_TABLE = "account_jwt_readiness_probe_plans"; + private static final String ENTRY_TABLE = "account_jwt_readiness_probe_entries"; + private static final String DELIVERY_CLAIM_TABLE = "account_jwt_readiness_delivery_claims"; + private static final String EXPECTED_POD_TABLE = "account_jwt_readiness_validator_pods"; + private static final String POD_RECEIPT_TABLE = "account_jwt_readiness_pod_receipts"; + private static final String VALIDATOR_ID = "account-service"; + private static final String CANARY_PROFILE = "account-jwt-readiness-canary"; + private static final String CANARY_AUDIENCE = "firemud-account-jwt-readiness"; + private static final String CONTROL_UI_PROFILE = ControlUiJwtProfileValidator.PROFILE; + private static final String CONTROL_UI_AUDIENCE = ControlUiJwtProfileValidator.AUDIENCE; + private static final String PLAYER_BOOTSTRAP_PROFILE = PlayerBootstrapJwtProfileValidator.PROFILE; + private static final String PLAYER_BOOTSTRAP_AUDIENCE = + PlayerBootstrapJwtProfileValidator.AUDIENCE; + private static final String REPRESENTATIVE_PROFILE = GameSessionAccountDelegationProfile.PROFILE; + private static final String REPRESENTATIVE_AUDIENCE = + GameSessionAccountDelegationProfile.AUDIENCE; + private static final List PRODUCTION_PROFILE_CASES = + List.of( + new ProfileCase(CONTROL_UI_PROFILE, CONTROL_UI_AUDIENCE), + new ProfileCase(PLAYER_BOOTSTRAP_PROFILE, PLAYER_BOOTSTRAP_AUDIENCE), + new ProfileCase(REPRESENTATIVE_PROFILE, REPRESENTATIVE_AUDIENCE)); + private static final Pattern SHA256 = Pattern.compile("[0-9a-f]{64}"); + private static final JsonMapper JSON = JsonMapper.builder().build(); + + private final DSLContext dsl; + private final AccountJwtSignerDesiredStateRepository desiredStateRepository; + private final AccountJwtJwksPublicationRepository publicationRepository; + private final AccountJwtValidatorInventoryRepository inventoryRepository; + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "The constructor only validates trusted Spring collaborators and constructs an in-memory repository; it performs no I/O or resource acquisition and defines no finalizer.") + public AccountJwtReadinessProbeRepository( + DSLContext dsl, + AccountJwtSignerDesiredStateRepository desiredStateRepository, + AccountJwtJwksPublicationRepository publicationRepository) { + this( + dsl, + desiredStateRepository, + publicationRepository, + new AccountJwtValidatorInventoryRepository(dsl)); + } + + @Autowired + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "The constructor only validates trusted Spring collaborators; it performs no I/O or resource acquisition and defines no finalizer.") + public AccountJwtReadinessProbeRepository( + DSLContext dsl, + AccountJwtSignerDesiredStateRepository desiredStateRepository, + AccountJwtJwksPublicationRepository publicationRepository, + AccountJwtValidatorInventoryRepository inventoryRepository) { + this.dsl = Objects.requireNonNull(dsl, "DSLContext is required"); + this.desiredStateRepository = + Objects.requireNonNull(desiredStateRepository, "Desired-state repository is required"); + this.publicationRepository = + Objects.requireNonNull(publicationRepository, "JWKS publication repository is required"); + this.inventoryRepository = + Objects.requireNonNull(inventoryRepository, "Inventory repository is required"); + } + + /** + * Creates one immutable plan from the exact current Account operation and publication evidence. + */ + @Transactional(propagation = Propagation.MANDATORY) + public ReadinessProbePlan planCurrent(Binding binding, TrustFence trust, Instant plannedAt) { + return planCurrent(binding, trust, plannedAt, Optional.empty()); + } + + /** + * Reads the exact current operation context before protected inventory I/O. The caller must + * return to an Account transaction and recheck this context before persisting or consuming the + * resulting snapshot. + */ + @Transactional(propagation = Propagation.MANDATORY) + public ObservationContext readCurrentInventoryObservationContext( + Binding binding, TrustFence trust) { + requireAccountTransaction(); + CurrentEvidence current = lockCurrentEvidence(binding, trust); + ReadinessProbePlan existing = selectPlan(current.request().operationId(), false); + if (existing != null) { + requirePlanMatchesCurrent(readbackPlan(existing, false), current); + } + return observationContext(current); + } + + /** Reads the selected context only while its exact current V2 inventory plan remains current. */ + @Transactional(propagation = Propagation.MANDATORY) + public ObservationContext readCurrentInventoryObservationContext( + Binding binding, TrustFence trust, UUID operationId) { + requireAccountTransaction(); + requireOperationId(operationId); + CurrentEvidence current = lockCurrentEvidence(binding, trust); + requireCurrentOperation(current, operationId.toString()); + ReadinessProbePlan plan = requireStoredPlan(current); + if (plan.planVersion() != INVENTORY_PLAN_VERSION || !plan.validatorInventoryComplete()) { + throw new ReceiverUnavailableException(); + } + return observationContext(current); + } + + /** + * Creates a still-partial plan bound to the exact Account-owned immutable inventory snapshot. The + * live inventory observation does not establish per-Pod acceptance or promotion evidence. + */ + @Transactional(propagation = Propagation.MANDATORY) + public ReadinessProbePlan planCurrent( + Binding binding, TrustFence trust, Instant plannedAt, InventorySnapshot inventorySnapshot) { + return planCurrent( + binding, trust, plannedAt, Optional.of(Objects.requireNonNull(inventorySnapshot))); + } + + private ReadinessProbePlan planCurrent( + Binding binding, + TrustFence trust, + Instant plannedAt, + Optional inventorySnapshot) { + requireWritableAccountTransaction(); + Objects.requireNonNull(plannedAt, "Probe plan time is required"); + long plannedEpoch = exactEpochSecond(plannedAt); + CurrentEvidence current = lockCurrentEvidence(binding, trust); + UUID operationId = current.request().operationId(); + ReadinessProbePlan existing = selectPlan(operationId, true); + if (existing != null) { + requirePlanMatchesCurrent(existing, current); + if (inventorySnapshot.isPresent()) { + String requestedDigest = inventorySnapshot.orElseThrow().digest(); + if (!existing.inventorySnapshotDigest().equals(Optional.of(requestedDigest))) { + throw new InventoryPlanConflictException(); + } + inventoryRepository.readRequired(requestedDigest, binding, trust); + } + return readbackPlan(existing, true); + } + + Optional snapshotDigest = Optional.empty(); + if (inventorySnapshot.isPresent()) { + InventorySnapshot snapshot = inventorySnapshot.orElseThrow(); + requireObservationContext(current, snapshot); + requireInventorySnapshotWithinPlanWindow(snapshot, plannedEpoch); + AccountJwtValidatorInventoryRepository.StoredSnapshot stored = + inventoryRepository.persistOrReadback(snapshot, binding, trust); + snapshotDigest = Optional.of(stored.digest()); + } + ReadinessProbePlan candidate = + newPlan(current, plannedEpoch, inventorySnapshot, snapshotDigest); + insertPlan(candidate); + for (ProbeEntry entry : candidate.entries()) { + insertEntry(entry, candidate.planVersion()); + } + if (inventorySnapshot.isPresent()) { + for (ExpectedPod expectedPod : expectedPods(candidate, inventorySnapshot.orElseThrow())) { + insertExpectedPod(expectedPod); + } + } + ReadinessProbePlan readback = selectPlan(operationId, true); + if (readback == null) { + throw new StorageUnavailableException("Account JWT readiness probe plan did not read back"); + } + requirePlanMatchesCurrent(readback, current); + if (!candidate.equals(readback)) { + throw new QuarantinedStateException("Account JWT readiness probe plan changed on readback"); + } + return readback; + } + + private static void requireInventorySnapshotWithinPlanWindow( + InventorySnapshot snapshot, long plannedEpoch) { + long observedEpoch; + try { + observedEpoch = snapshot.observedAt().getEpochSecond(); + } catch (RuntimeException failure) { + throw new InventoryPlanConflictException(); + } + if (observedEpoch <= 0L + || observedEpoch > plannedEpoch + || plannedEpoch - observedEpoch > MAX_VALIDATOR_CACHE_AGE_SECONDS) { + throw new InventoryPlanConflictException(); + } + } + + /** + * Durably claims the one transient delivery attempt for this exact current plan before signing. A + * claim is never cleared or reused: a lost response or interrupted attempt remains quarantined. + */ + @Transactional(propagation = Propagation.MANDATORY) + public DeliveryClaim claimSingleDelivery( + net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository + .Binding + binding, + TrustFence trust, + ReadinessProbePlan expectedPlan, + net.firedevops.firemud.accountservice.config.AccountJwtReadinessTrustBinding.Binding + readinessBinding, + PeerIdentity peer, + Instant claimedAt) { + requireWritableAccountTransaction(); + Objects.requireNonNull(expectedPlan, "Exact persisted readiness plan is required"); + Objects.requireNonNull(readinessBinding, "Authenticated readiness binding is required"); + Objects.requireNonNull(peer, "TLS-authenticated readiness peer is required"); + long claimedEpoch = exactEpochSecond(claimedAt); + if (!readinessBinding.isCurrentAt(claimedEpoch) + || !readinessBinding.matches(peer) + || !binding.environmentId().equals(readinessBinding.environmentId()) + || !binding.clusterId().equals(readinessBinding.clusterId()) + || !binding.namespace().equals(readinessBinding.namespace()) + || !trust + .expectedClusterIncarnationUid() + .equals(readinessBinding.expectedClusterIncarnationUid()) + || !trust.expectedNamespaceUid().equals(readinessBinding.expectedNamespaceUid())) { + throw new DeliveryClaimRejectedException(); + } + CurrentEvidence current = lockCurrentEvidence(binding, trust); + requireCurrentOperation(current, expectedPlan.operationId().toString()); + ReadinessProbePlan stored = requireStoredPlan(current); + ReadinessProbePlan currentPlan = readbackPlan(stored, true); + if (!currentPlan.equals(expectedPlan)) { + throw new StaleOperationException( + "Readiness delivery claim does not match the exact current plan"); + } + if (claimedEpoch < currentPlan.notBeforeEpochSecond()) { + throw new CacheAgeNotElapsedException(); + } + if (claimedEpoch >= currentPlan.expiresAtEpochSecond()) { + throw new ProbeExpiredException(); + } + if (currentPlan.entries().isEmpty() + || currentPlan.entries().size() > MAX_ENTRIES_PER_OPERATION + || currentPlan.entries().stream() + .anyMatch( + entry -> + entry.state() != ProbeState.PLANNED + || entry.signingAttemptedAtEpochSecond().isPresent() + || entry.compactTokenSha256().isPresent() + || entry.verificationReceipt().isPresent())) { + throw new DeliveryAlreadyClaimedException(); + } + if (selectDeliveryClaim(currentPlan.operationId(), true) != null) { + throw new DeliveryAlreadyClaimedException(); + } + + DeliveryClaim candidate = + DeliveryClaim.create(currentPlan, trust, readinessBinding, peer, claimedEpoch); + insertDeliveryClaim(candidate); + DeliveryClaim readback = selectDeliveryClaim(candidate.rotationOperationId(), true); + if (readback == null || !readback.equals(candidate)) { + throw new QuarantinedStateException( + "Account readiness single-delivery claim did not read back exactly"); + } + return readback; + } + + /** Rechecks the immutable one-shot claim immediately before any pending-key signing. */ + @Transactional(propagation = Propagation.MANDATORY) + public DeliveryClaim requireCurrentDeliveryClaim( + Binding binding, + TrustFence trust, + ReadinessProbePlan expectedPlan, + DeliveryClaim expectedClaim, + Instant checkedAt) { + requireAccountTransaction(); + Objects.requireNonNull(expectedPlan, "Exact persisted readiness plan is required"); + Objects.requireNonNull(expectedClaim, "Durable single-delivery claim is required"); + long checkedEpoch = exactEpochSecond(checkedAt); + CurrentEvidence current = lockCurrentEvidence(binding, trust); + requireCurrentOperation(current, expectedPlan.operationId().toString()); + ReadinessProbePlan plan = readbackPlan(requireStoredPlan(current), true); + DeliveryClaim persisted = selectDeliveryClaim(plan.operationId(), true); + if (!plan.equals(expectedPlan) + || persisted == null + || !persisted.equals(expectedClaim) + || !persisted.planDigest().equals(plan.planDigest()) + || !persisted.materializerTrustBindingDigest().equals(trust.bindingDigest()) + || !persisted.materializerTrustConfigRevision().equals(trust.configRevision()) + || !persisted.expectedClusterUid().equals(trust.expectedClusterIncarnationUid()) + || !persisted.expectedNamespaceUid().equals(trust.expectedNamespaceUid()) + || !persisted.targetGeneration().equals(plan.targetGeneration()) + || !persisted.targetKid().equals(plan.targetKid())) { + throw new DeliveryAlreadyClaimedException(); + } + if (checkedEpoch < plan.notBeforeEpochSecond()) { + throw new CacheAgeNotElapsedException(); + } + if (checkedEpoch >= plan.expiresAtEpochSecond()) { + throw new ProbeExpiredException(); + } + return persisted; + } + + /** + * Reads the exact current generation and public publication before PREPARED so the caller can + * authorize that same generation's preparation. The static applicability matrix and immutable + * Deployment inventory snapshot alone are not per-Pod acceptance evidence; partial plans cannot + * satisfy promotion. + */ + @Transactional(propagation = Propagation.MANDATORY) + public Optional readCurrentPromotionPrerequisites( + Binding binding, TrustFence trust, UUID rotationOperationId) { + return readCurrentPromotionPrerequisites(binding, trust, rotationOperationId, null); + } + + @Transactional(propagation = Propagation.MANDATORY) + public Optional readCurrentPromotionPrerequisites( + Binding binding, + TrustFence trust, + UUID rotationOperationId, + InventorySnapshot liveInventory) { + // This is a nonmutating proof read, but it joins the writable lifecycle transaction because + // the existing owner evidence readers lock their rows to fence the adjacent PREPARED CAS. + requireWritableAccountTransaction(); + requireOperationId(rotationOperationId); + CurrentEvidence current = lockCurrentEvidence(binding, trust); + if (!current.request().operationId().equals(rotationOperationId)) { + throw new StaleOperationException( + "Readiness prerequisite proof is not for Account's current operation"); + } + ReadinessProbePlan plan = selectPlan(rotationOperationId, false); + if (plan == null) { + throw new MissingPlanException("Current signer generation has no readiness plan"); + } + ReadinessProbePlan stored = readbackPlan(plan, false); + requirePlanMatchesCurrent(stored, current); + if (readinessPlanOutOfWindow(stored)) { + return Optional.empty(); + } + if (!stored.validatorInventoryComplete()) { + return Optional.empty(); + } + if (stored.planVersion() != INVENTORY_PLAN_VERSION || liveInventory == null) { + return Optional.empty(); + } + requireLiveInventoryMatches(stored, binding, trust, liveInventory, observationContext(current)); + if (!hasCompletePodReceiptClosure(stored)) { + return Optional.empty(); + } + AccountJwtJwksPublicationRepository.PromotionPublicationEvidence publication = + promotionPublicationEvidence(current.publication()); + return Optional.of( + new ReadinessPromotionProof( + stored, + current.result(), + publication, + "protected-validator-inventory:" + liveInventory.digest(), + liveInventory.digest())); + } + + @Transactional(propagation = Propagation.MANDATORY) + public Optional readPromotionProof( + Binding binding, TrustFence trust, UUID rotationOperationId) { + return readPromotionProof(binding, trust, rotationOperationId, null); + } + + @Transactional(propagation = Propagation.MANDATORY) + public Optional readPromotionProof( + Binding binding, + TrustFence trust, + UUID rotationOperationId, + InventorySnapshot liveInventory) { + // Recovery evidence is likewise a locked, nonmutating read inside the writable reconciliation + // transaction; do not split these reads into an unlocked read-only snapshot. + requireWritableAccountTransaction(); + requireOperationId(rotationOperationId); + var prepared = desiredStateRepository.readPreparedGenerationForRecovery(binding, trust); + var generation = prepared.generationResult(); + var promotion = prepared.promotion(); + if (!generation.operationId().equals(rotationOperationId) + || !promotion.generationOperationId().equals(rotationOperationId) + || !promotion.binding().equals(binding) + || !promotion.trustFence().equals(trust)) { + throw new StaleOperationException( + "Readiness promotion proof does not match the exact PREPARED generation"); + } + AccountJwtJwksPublicationRepository.PromotionPublicationEvidence publication = + publicationRepository.readPreparedPublicationForRecovery(binding, trust); + ReadinessProbePlan plan = selectPlan(rotationOperationId, false); + if (plan == null) { + throw new MissingPlanException("Prepared signer generation has no readiness plan"); + } + ReadinessProbePlan stored = readbackPlan(plan, false); + requirePreparedPlanMatches(stored, generation, promotion, publication); + if (readinessPlanOutOfWindow(stored)) { + return Optional.empty(); + } + if (!stored.validatorInventoryComplete()) { + return Optional.empty(); + } + if (stored.planVersion() != INVENTORY_PLAN_VERSION || liveInventory == null) { + return Optional.empty(); + } + requireLiveInventoryMatches( + stored, + binding, + trust, + liveInventory, + observationContext( + generation.operationId(), generation.operationDigest(), stored.expectedFence())); + if (!hasCompletePodReceiptClosure(stored)) { + return Optional.empty(); + } + return Optional.of( + new ReadinessPromotionProof( + stored, + generation, + publication, + "protected-validator-inventory:" + liveInventory.digest(), + liveInventory.digest())); + } + + private boolean readinessPlanOutOfWindow(ReadinessProbePlan plan) { + Long databaseNow = + dsl.resultQuery("SELECT floor(extract(epoch FROM CURRENT_TIMESTAMP))::bigint") + .fetchOne(0, Long.class); + if (databaseNow == null) { + throw new AccountJwtSignerDesiredStateRepository.StorageUnavailableException( + "Account readiness database clock readback is unavailable"); + } + return databaseNow < plan.notBeforeEpochSecond() || databaseNow >= plan.expiresAtEpochSecond(); + } + + /** Reads one plan only while its original generation and publication evidence remain current. */ + @Transactional(propagation = Propagation.MANDATORY) + public ReadinessProbePlan readCurrentPlan(Binding binding, TrustFence trust, UUID operationId) { + requireAccountTransaction(); + requireOperationId(operationId); + CurrentEvidence current = lockCurrentEvidence(binding, trust); + if (!current.request().operationId().equals(operationId)) { + throw new StaleOperationException( + "Readiness probe plan is not for Account's current operation"); + } + ReadinessProbePlan stored = selectPlan(operationId, true); + if (stored == null) { + throw new MissingPlanException("Account JWT readiness probe plan is missing"); + } + requirePlanMatchesCurrent(stored, current); + return readbackPlan(stored, true); + } + + /** Reads one exact current probe selected by the complete key and its immutable JTI. */ + @Transactional(propagation = Propagation.MANDATORY) + public ProbeEntry readCurrentEntry( + Binding binding, + TrustFence trust, + UUID operationId, + String validatorId, + String tokenProfile, + String audience, + ProbeKind probeKind, + UUID jti) { + requireAccountTransaction(); + requireOperationId(operationId); + CurrentEvidence current = lockCurrentEvidence(binding, trust); + requireCurrentOperation(current, operationId.toString()); + ReadinessProbePlan plan = requireStoredPlan(current); + if (plan.planVersion() != 1) { + throw new ReceiverUnavailableException(); + } + ProbeEntry entry = + selectEntry(operationId, validatorId, tokenProfile, audience, probeKind, true); + if (entry == null + || !entry.jti().equals(jti) + || !entry.planDigest().equals(plan.planDigest())) { + throw new StaleOperationException("Readiness probe selector is not the exact current entry"); + } + return entry; + } + + /** + * Records only the exact authenticated, cryptographically verified observation for one current + * ISSUED entry. A matching VERIFIED retry reads back the original immutable receipt. + */ + @Transactional(propagation = Propagation.MANDATORY) + public ProbeEntry recordVerified( + Binding binding, + TrustFence trust, + UUID operationId, + String validatorId, + String tokenProfile, + String audience, + ProbeKind probeKind, + UUID jti, + VerifiedProbeObservation observation) { + requireWritableAccountTransaction(); + requireOperationId(operationId); + Objects.requireNonNull(observation, "Authenticated verification observation is required"); + long observedAt = exactEpochSecond(Instant.ofEpochSecond(observation.observedAtEpochSecond())); + CurrentEvidence current = lockCurrentEvidence(binding, trust); + requireCurrentOperation(current, operationId.toString()); + ReadinessProbePlan plan = requireStoredPlan(current); + if (plan.planVersion() != 1) { + throw new ReceiverUnavailableException(); + } + ProbeEntry entry = + selectEntry(operationId, validatorId, tokenProfile, audience, probeKind, true); + if (entry == null + || !entry.jti().equals(jti) + || !entry.planDigest().equals(plan.planDigest()) + || !entry.targetGeneration().equals(plan.targetGeneration()) + || !entry.targetKid().equals(plan.targetKid()) + || !entry.expectedActive().equals(plan.expectedFence().durableActive()) + || !entry.expectedActive().equals(plan.expectedFence().publishedActive()) + || entry.registryVersion() != 1 + || !entry.compactTokenSha256().equals(Optional.of(observation.compactTokenSha256())) + || !entry.targetKid().equals(observation.verifiedKid())) { + throw new StaleOperationException( + "Verified readiness probe does not match the exact current operation entry"); + } + requireNotExpired(entry, observedAt); + if (observedAt < entry.plannedIssuedAtEpochSecond()) { + throw new CacheAgeNotElapsedException(); + } + + if (entry.state() == ProbeState.VERIFIED) { + VerificationReceipt existing = + entry + .verificationReceipt() + .orElseThrow( + () -> + new QuarantinedStateException( + "Verified readiness entry has no immutable receipt")); + requireMatchingObservation(existing, observation); + return entry; + } + if (entry.state() != ProbeState.ISSUED || entry.verificationReceipt().isPresent()) { + throw new AmbiguousDeliveryException("Readiness probe is not the exact current ISSUED entry"); + } + + long resultEntryVersion = Math.addExact(entry.entryVersion(), 1L); + VerificationReceipt receipt = verificationReceipt(plan, entry, observation, resultEntryVersion); + int changed = + dsl.execute( + "UPDATE " + + ENTRY_TABLE + + " SET state = 'VERIFIED', entry_version = ?, verification_receipt_version = ?, " + + "verification_source_entry_version = ?, verified_at_epoch_seconds = ?, " + + "verified_kid = ?, validator_instance_id = ?, validator_binding_digest = ?, " + + "validator_config_revision = ?, validator_peer_uri = ?, " + + "validator_peer_spki_sha256 = ?, verification_receipt_sha256 = ? " + + "WHERE rotation_operation_id = ? AND validator_id = ? AND token_profile = ? " + + "AND audience = ? AND probe_kind = ? AND jti = ? AND plan_digest = ? " + + "AND state = 'ISSUED' AND entry_version = ? AND target_generation = ? " + + "AND target_kid = ? AND compact_token_sha256 = ? " + + "AND verification_receipt_sha256 IS NULL " + + "AND CURRENT_TIMESTAMP >= to_timestamp(planned_issued_at_epoch_seconds) " + + "AND CURRENT_TIMESTAMP < to_timestamp(expires_at_epoch_seconds)", + receipt.resultEntryVersion(), + receipt.receiptVersion(), + receipt.sourceEntryVersion(), + receipt.observedAtEpochSecond(), + receipt.verifiedKid(), + receipt.validatorInstanceId(), + receipt.validatorBindingDigest(), + receipt.validatorConfigRevision(), + receipt.validatorPeerUri(), + receipt.validatorPeerSpkiSha256(), + receipt.receiptSha256(), + operationId, + validatorId, + tokenProfile, + audience, + probeKind.name(), + jti, + plan.planDigest(), + entry.entryVersion(), + Long.parseLong(plan.targetGeneration()), + plan.targetKid(), + observation.compactTokenSha256()); + if (changed != 1) { + throw new VersionConflictException("Readiness VERIFIED transition lost its exact CAS"); + } + ProbeEntry readback = selectEntry(entry, true); + if (readback == null + || readback.state() != ProbeState.VERIFIED + || readback.entryVersion() != receipt.resultEntryVersion() + || readback.verificationReceipt().filter(receipt::equals).isEmpty()) { + throw new QuarantinedStateException("Verified readiness receipt did not read back exactly"); + } + return readback; + } + + /** + * Pins the exact signed-token hash before delivery. A row with this pin but no ISSUED result is + * ambiguous after a crash and must be quarantined; it is never signed or delivered again. + */ + @Transactional(propagation = Propagation.MANDATORY) + public ProbeEntry recordSigningAttempt( + Binding binding, TrustFence trust, SignedProbeDigest signed, Instant attemptedAt) { + requireWritableAccountTransaction(); + Objects.requireNonNull(signed, "Mounted signer result is required"); + long attemptedEpoch = exactEpochSecond(attemptedAt); + CurrentEvidence current = lockCurrentEvidence(binding, trust); + requireCurrentOperation(current, signed.operationId()); + ReadinessProbePlan plan = requireStoredPlan(current); + ProbeEntry entry = + selectEntry( + plan.operationId(), + signed.validatorId(), + signed.tokenProfile(), + signed.audience(), + signed.probeKind(), + true); + requireSignedResultMatches(plan, entry, signed); + requireNotExpired(entry, attemptedEpoch); + if (attemptedEpoch < entry.plannedIssuedAtEpochSecond()) { + throw new CacheAgeNotElapsedException(); + } + if (entry.state() != ProbeState.PLANNED + || entry.compactTokenSha256().isPresent() + || entry.signingAttemptedAtEpochSecond().isPresent()) { + throw new AmbiguousDeliveryException("Readiness probe already has a signing attempt"); + } + int changed = + dsl.execute( + "UPDATE " + + ENTRY_TABLE + + " SET signing_attempted_at_epoch_seconds = ?, compact_token_sha256 = ?, " + + "entry_version = entry_version + 1 WHERE rotation_operation_id = ? " + + "AND validator_id = ? AND token_profile = ? AND audience = ? AND probe_kind = ? " + + "AND plan_digest = ? AND state = 'PLANNED' AND entry_version = ? " + + "AND compact_token_sha256 IS NULL AND signing_attempted_at_epoch_seconds IS NULL", + attemptedEpoch, + signed.compactTokenSha256(), + plan.operationId(), + signed.validatorId(), + signed.tokenProfile(), + signed.audience(), + signed.probeKind().name(), + plan.planDigest(), + entry.entryVersion()); + if (changed != 1) { + throw new VersionConflictException("Readiness probe signing attempt lost its exact CAS"); + } + ProbeEntry readback = + selectEntry( + plan.operationId(), + signed.validatorId(), + signed.tokenProfile(), + signed.audience(), + signed.probeKind(), + true); + if (readback == null + || readback.state() != ProbeState.PLANNED + || readback.entryVersion() != entry.entryVersion() + 1 + || !readback.compactTokenSha256().equals(Optional.of(signed.compactTokenSha256())) + || !readback.signingAttemptedAtEpochSecond().equals(Optional.of(attemptedEpoch))) { + throw new QuarantinedStateException( + "Readiness probe signing attempt did not read back exactly"); + } + return readback; + } + + /** Durably records ISSUED before the exact compact probe reaches its transient consumer. */ + @Transactional(propagation = Propagation.MANDATORY) + public ProbeEntry recordIssued( + Binding binding, TrustFence trust, SignedProbeDigest signed, Instant issuedAt) { + requireWritableAccountTransaction(); + Objects.requireNonNull(signed, "Mounted signer result is required"); + long issuedEpoch = exactEpochSecond(issuedAt); + CurrentEvidence current = lockCurrentEvidence(binding, trust); + requireCurrentOperation(current, signed.operationId()); + ReadinessProbePlan plan = requireStoredPlan(current); + ProbeEntry entry = + selectEntry( + plan.operationId(), + signed.validatorId(), + signed.tokenProfile(), + signed.audience(), + signed.probeKind(), + true); + requireSignedResultMatches(plan, entry, signed); + requireNotExpired(entry, issuedEpoch); + if (issuedEpoch < entry.plannedIssuedAtEpochSecond()) { + throw new CacheAgeNotElapsedException(); + } + if (entry.state() == ProbeState.ISSUED) { + if (!entry.compactTokenSha256().equals(Optional.of(signed.compactTokenSha256()))) { + throw new IdempotencyConflictException("Issued readiness probe hash changed"); + } + return entry; + } + if (entry.state() != ProbeState.PLANNED + || !entry.compactTokenSha256().equals(Optional.of(signed.compactTokenSha256())) + || entry.signingAttemptedAtEpochSecond().isEmpty()) { + throw new AmbiguousDeliveryException("Readiness probe is not pinned for exact delivery"); + } + int changed = + dsl.execute( + "UPDATE " + + ENTRY_TABLE + + " SET state = 'ISSUED', entry_version = entry_version + 1 " + + "WHERE rotation_operation_id = ? AND validator_id = ? AND token_profile = ? " + + "AND audience = ? AND probe_kind = ? AND plan_digest = ? " + + "AND state = 'PLANNED' AND entry_version = ? AND compact_token_sha256 = ? " + + "AND signing_attempted_at_epoch_seconds IS NOT NULL", + plan.operationId(), + signed.validatorId(), + signed.tokenProfile(), + signed.audience(), + signed.probeKind().name(), + plan.planDigest(), + entry.entryVersion(), + signed.compactTokenSha256()); + if (changed != 1) { + throw new VersionConflictException("Readiness probe ISSUED transition lost its exact CAS"); + } + ProbeEntry readback = + selectEntry( + plan.operationId(), + signed.validatorId(), + signed.tokenProfile(), + signed.audience(), + signed.probeKind(), + true); + if (readback == null + || readback.state() != ProbeState.ISSUED + || readback.entryVersion() != entry.entryVersion() + 1 + || !readback.compactTokenSha256().equals(Optional.of(signed.compactTokenSha256()))) { + throw new QuarantinedStateException("Issued readiness probe did not read back exactly"); + } + return readback; + } + + /** Quarantines a pinned PLANNED attempt after delivery or persistence became ambiguous. */ + @Transactional(propagation = Propagation.MANDATORY) + public ProbeEntry abortAmbiguousAttempt( + Binding binding, + TrustFence trust, + UUID operationId, + String validatorId, + String tokenProfile, + String audience, + ProbeKind probeKind, + Instant terminalAt) { + requireWritableAccountTransaction(); + long terminalEpoch = exactEpochSecond(terminalAt); + CurrentEvidence current = lockCurrentEvidence(binding, trust); + requireCurrentOperation(current, operationId.toString()); + requireStoredPlan(current); + ProbeEntry entry = + selectEntry(operationId, validatorId, tokenProfile, audience, probeKind, true); + if (entry == null + || entry.state() != ProbeState.PLANNED + || entry.compactTokenSha256().isEmpty()) { + throw new AmbiguousDeliveryException("No ambiguous pinned readiness attempt exists"); + } + return transitionTerminal(entry, ProbeState.ABORTED, terminalEpoch); + } + + /** Aborts only entries belonging to the exact current Account operation. */ + @Transactional(propagation = Propagation.MANDATORY) + public List abortCurrent( + Binding binding, TrustFence trust, UUID operationId, Instant terminalAt) { + requireWritableAccountTransaction(); + long terminalEpoch = exactEpochSecond(terminalAt); + CurrentEvidence current = lockCurrentEvidence(binding, trust); + requireCurrentOperation(current, operationId.toString()); + ReadinessProbePlan plan = requireStoredPlan(current); + List result = new ArrayList<>(); + for (ProbeEntry entry : plan.entries()) { + ProbeEntry currentEntry = selectEntry(entry, true); + if (currentEntry.state() == ProbeState.PLANNED + || currentEntry.state() == ProbeState.ISSUED + || currentEntry.state() == ProbeState.VERIFIED) { + result.add(transitionTerminal(currentEntry, ProbeState.ABORTED, terminalEpoch)); + } else { + result.add(currentEntry); + } + } + return List.copyOf(result); + } + + /** Expires only this exact current operation after its immutable entry expiry. */ + @Transactional(propagation = Propagation.MANDATORY) + public List expireCurrent( + Binding binding, TrustFence trust, UUID operationId, Instant now) { + requireWritableAccountTransaction(); + long nowEpoch = exactEpochSecond(now); + CurrentEvidence current = lockCurrentEvidence(binding, trust); + requireCurrentOperation(current, operationId.toString()); + ReadinessProbePlan plan = requireStoredPlan(current); + List result = new ArrayList<>(); + for (ProbeEntry entry : plan.entries()) { + ProbeEntry currentEntry = selectEntry(entry, true); + if ((currentEntry.state() == ProbeState.PLANNED + || currentEntry.state() == ProbeState.ISSUED + || currentEntry.state() == ProbeState.VERIFIED) + && nowEpoch >= currentEntry.expiresAtEpochSecond()) { + result.add(transitionTerminal(currentEntry, ProbeState.EXPIRED, nowEpoch)); + } else { + result.add(currentEntry); + } + } + return List.copyOf(result); + } + + /** + * Bounded cleanup of terminal entries for one explicit operation. It never queries or scans + * another operation and retains all non-secret identity/hash/terminal evidence. + */ + @Transactional(propagation = Propagation.MANDATORY) + public List cleanTerminalEntries(UUID operationId, int maximumEntries) { + requireWritableAccountTransaction(); + requireOperationId(operationId); + if (maximumEntries < 1 || maximumEntries > MAX_ENTRIES_PER_OPERATION) { + throw new IllegalArgumentException("Readiness cleanup bound is outside its fixed limit"); + } + Result terminalRows = + dsl.fetch( + "SELECT * FROM " + + ENTRY_TABLE + + " WHERE rotation_operation_id = ? AND state IN ('ABORTED', 'EXPIRED') " + + "ORDER BY validator_id, token_profile, audience, probe_kind LIMIT ? FOR UPDATE", + operationId, + maximumEntries); + if (terminalRows.size() > maximumEntries) { + throw new QuarantinedStateException("Readiness cleanup exceeded its exact operation bound"); + } + List cleaned = new ArrayList<>(); + for (Record row : terminalRows) { + ProbeEntry entry = decodeEntry(row); + cleaned.add(transitionTerminal(entry, ProbeState.CLEANED, null)); + } + return List.copyOf(cleaned); + } + + private ProbeEntry transitionTerminal(ProbeEntry entry, ProbeState target, Long transitionEpoch) { + if (target == ProbeState.EXPIRED && transitionEpoch == null) { + throw new IllegalArgumentException("Expiry time is required"); + } + String outcome = + target == ProbeState.CLEANED ? entry.terminalOutcome().orElseThrow() : target.name(); + int changed = + dsl.execute( + "UPDATE " + + ENTRY_TABLE + + " SET state = ?, terminal_outcome = ?, entry_version = entry_version + 1 " + + "WHERE rotation_operation_id = ? AND validator_id = ? AND token_profile = ? " + + "AND audience = ? AND probe_kind = ? AND state = ? AND entry_version = ?", + target.name(), + outcome, + entry.rotationOperationId(), + entry.validatorId(), + entry.tokenProfile(), + entry.audience(), + entry.probeKind().name(), + entry.state().name(), + entry.entryVersion()); + if (changed != 1) { + throw new VersionConflictException("Readiness terminal transition lost its exact CAS"); + } + ProbeEntry readback = selectEntry(entry, true); + if (readback == null + || readback.state() != target + || readback.entryVersion() != entry.entryVersion() + 1 + || !readback.terminalOutcome().equals(Optional.of(outcome))) { + throw new QuarantinedStateException( + "Readiness terminal transition did not read back exactly"); + } + return readback; + } + + private ReadinessProbePlan newPlan( + CurrentEvidence current, + long plannedAtEpochSecond, + Optional inventorySnapshot, + Optional inventorySnapshotDigest) { + long notBefore = add(plannedAtEpochSecond, MAX_VALIDATOR_CACHE_AGE_SECONDS); + long expiresAt = add(notBefore, PROBE_LIFETIME_SECONDS); + int planVersion = inventorySnapshot.isPresent() ? INVENTORY_PLAN_VERSION : 1; + boolean inventoryComplete = + inventorySnapshot + .map(AccountJwtReadinessProbeRepository::inventoryPlanComplete) + .orElse(false); + String matrixJson = + inventorySnapshot + .map(snapshot -> applicabilityMatrixJson(snapshot, inventoryComplete)) + .orElseGet(AccountJwtReadinessProbeRepository::applicabilityMatrixJson); + String matrixDigest = sha256(matrixJson.getBytes(StandardCharsets.UTF_8)); + List entries = + (inventorySnapshot.isPresent() + ? inventoryEntries(current, inventorySnapshot.orElseThrow(), notBefore, expiresAt) + : legacyEntries(current, notBefore, expiresAt)) + .stream().sorted(PROBE_ENTRY_ORDER).toList(); + String planDigest = + planDigest( + current, + matrixJson, + matrixDigest, + planVersion, + inventoryComplete, + plannedAtEpochSecond, + notBefore, + expiresAt, + entries, + inventorySnapshotDigest); + List boundEntries = + entries.stream().map(entry -> entry.withPlanDigest(planDigest)).toList(); + return ReadinessProbePlan.fromCurrent( + current, + matrixJson, + matrixDigest, + inventoryComplete, + MAX_VALIDATOR_CACHE_AGE_SECONDS, + plannedAtEpochSecond, + notBefore, + expiresAt, + planDigest, + boundEntries, + inventorySnapshotDigest, + planVersion); + } + + private static List legacyEntries( + CurrentEvidence current, long notBefore, long expiresAt) { + return List.of( + newEntry( + current, + VALIDATOR_ID, + ProbeKind.CANARY, + CANARY_PROFILE, + CANARY_AUDIENCE, + notBefore, + expiresAt), + newEntry( + current, + VALIDATOR_ID, + ProbeKind.REPRESENTATIVE, + CONTROL_UI_PROFILE, + CONTROL_UI_AUDIENCE, + notBefore, + expiresAt), + newEntry( + current, + VALIDATOR_ID, + ProbeKind.REPRESENTATIVE, + PLAYER_BOOTSTRAP_PROFILE, + PLAYER_BOOTSTRAP_AUDIENCE, + notBefore, + expiresAt), + newEntry( + current, + VALIDATOR_ID, + ProbeKind.REPRESENTATIVE, + REPRESENTATIVE_PROFILE, + REPRESENTATIVE_AUDIENCE, + notBefore, + expiresAt)); + } + + private static List inventoryEntries( + CurrentEvidence current, InventorySnapshot snapshot, long notBefore, long expiresAt) { + List entries = new ArrayList<>(); + for (ValidatorObservation validator : snapshot.validators()) { + entries.add( + newEntry( + current, + validator.validatorId(), + ProbeKind.CANARY, + CANARY_PROFILE, + CANARY_AUDIENCE, + notBefore, + expiresAt)); + for (ProfileCase profile : PRODUCTION_PROFILE_CASES) { + entries.add( + newEntry( + current, + validator.validatorId(), + ProbeKind.REPRESENTATIVE, + profile.tokenProfile(), + profile.audience(), + notBefore, + expiresAt)); + } + } + if (entries.isEmpty() || entries.size() > MAX_ENTRIES_PER_OPERATION) { + throw new InventoryPlanConflictException(); + } + return List.copyOf(entries); + } + + private static ProbeEntry newEntry( + CurrentEvidence current, + String validatorId, + ProbeKind kind, + String profile, + String audience, + long notBefore, + long expiresAt) { + return new ProbeEntry( + current.request().operationId(), + "0".repeat(64), + validatorId, + profile, + audience, + kind, + UUID.randomUUID(), + current.request().targetGeneration(), + current.request().targetKid(), + current.state().durableActive(), + 1, + 1, + notBefore, + expiresAt, + ProbeState.PLANNED, + Optional.empty(), + Optional.empty(), + Optional.empty(), + Optional.empty()); + } + + private void insertPlan(ReadinessProbePlan plan) { + Map fields = new LinkedHashMap<>(); + fields.put("rotation_operation_id", plan.operationId()); + fields.put("environment_id", plan.binding().environmentId()); + fields.put("cluster_id", plan.binding().clusterId()); + fields.put("kubernetes_namespace", plan.binding().namespace()); + fields.put("custody_mode", plan.binding().mode().value()); + fields.put("operation_digest", plan.operationDigest()); + fields.put("generation_request_digest", plan.generationRequestDigest()); + fields.put("generation_receipt_digest", plan.generationReceiptDigest()); + fields.put("desired_state_version", plan.desiredStateVersion()); + fields.put( + "expected_cluster_incarnation_uid", + UUID.fromString(plan.trustFence().expectedClusterIncarnationUid())); + fields.put("expected_namespace_uid", UUID.fromString(plan.trustFence().expectedNamespaceUid())); + fields.put("trust_binding_digest", plan.trustFence().bindingDigest()); + fields.put("trust_config_revision", plan.trustFence().configRevision()); + fields.put("target_generation", Long.parseLong(plan.targetGeneration())); + fields.put("target_kid", plan.targetKid()); + fields.put("target_public_key_fingerprint", plan.targetPublicKeyFingerprint()); + fields.put( + "expected_active_generation", + plan.expectedFence() + .durableActive() + .map(value -> Long.parseLong(value.generation())) + .orElse(null)); + fields.put( + "expected_active_kid", + plan.expectedFence().durableActive().map(ActiveSigner::kid).orElse(null)); + fields.put( + "expected_published_generation", + plan.expectedFence() + .publishedActive() + .map(value -> Long.parseLong(value.generation())) + .orElse(null)); + fields.put( + "expected_published_kid", + plan.expectedFence().publishedActive().map(ActiveSigner::kid).orElse(null)); + fields.put("publication_intent_digest", plan.publicationIntentDigest()); + fields.put("publication_receipt_digest", plan.publicationReceiptDigest()); + fields.put("mounted_observation_digest", plan.mountedObservationDigest()); + fields.put("applicability_matrix_json", plan.applicabilityMatrixJson()); + fields.put("applicability_matrix_digest", plan.applicabilityMatrixDigest()); + fields.put("validator_inventory_complete", plan.validatorInventoryComplete()); + fields.put("inventory_snapshot_digest", plan.inventorySnapshotDigest().orElse(null)); + fields.put("maximum_cache_age_seconds", plan.maximumCacheAgeSeconds()); + fields.put("planned_at_epoch_seconds", plan.plannedAtEpochSecond()); + fields.put("not_before_epoch_seconds", plan.notBeforeEpochSecond()); + fields.put("expires_at_epoch_seconds", plan.expiresAtEpochSecond()); + fields.put("plan_version", plan.planVersion()); + fields.put("plan_digest", plan.planDigest()); + insertOne(dsl, PLAN_TABLE, fields); + } + + private void insertDeliveryClaim(DeliveryClaim claim) { + Map fields = new LinkedHashMap<>(); + fields.put("rotation_operation_id", claim.rotationOperationId()); + fields.put("plan_digest", claim.planDigest()); + fields.put("expected_cluster_incarnation_uid", UUID.fromString(claim.expectedClusterUid())); + fields.put("expected_namespace_uid", UUID.fromString(claim.expectedNamespaceUid())); + fields.put("materializer_trust_binding_digest", claim.materializerTrustBindingDigest()); + fields.put("materializer_trust_config_revision", claim.materializerTrustConfigRevision()); + fields.put("target_generation", Long.parseLong(claim.targetGeneration())); + fields.put("target_kid", claim.targetKid()); + fields.put( + "expected_active_generation", + claim.expectedActive().map(value -> Long.parseLong(value.generation())).orElse(null)); + fields.put("expected_active_kid", claim.expectedActive().map(ActiveSigner::kid).orElse(null)); + fields.put("readiness_binding_digest", claim.readinessBindingDigest()); + fields.put("readiness_config_revision", claim.readinessConfigRevision()); + fields.put( + "readiness_binding_valid_until_epoch_seconds", + claim.readinessBindingValidUntilEpochSecond()); + fields.put("validator_id", claim.validatorId()); + fields.put("validator_instance_id", claim.validatorInstanceId()); + fields.put("validator_peer_uri", claim.validatorPeerUri()); + fields.put("validator_peer_spki_sha256", claim.validatorPeerSpkiSha256()); + fields.put("claimed_at_epoch_seconds", claim.claimedAtEpochSecond()); + fields.put("expires_at_epoch_seconds", claim.expiresAtEpochSecond()); + fields.put("claim_digest", claim.claimDigest()); + insertOne(dsl, DELIVERY_CLAIM_TABLE, fields); + } + + private DeliveryClaim selectDeliveryClaim(UUID operationId, boolean lock) { + Record row = + dsl.fetchOne( + "SELECT * FROM " + + DELIVERY_CLAIM_TABLE + + " WHERE rotation_operation_id = ?" + + (lock ? " FOR UPDATE" : ""), + operationId); + if (row == null) { + return null; + } + Long activeGeneration = row.get("expected_active_generation", Long.class); + String activeKid = row.get("expected_active_kid", String.class); + DeliveryClaim result = + new DeliveryClaim( + row.get("rotation_operation_id", UUID.class), + row.get("plan_digest", String.class), + row.get("expected_cluster_incarnation_uid", UUID.class).toString(), + row.get("expected_namespace_uid", UUID.class).toString(), + row.get("materializer_trust_binding_digest", String.class), + row.get("materializer_trust_config_revision", String.class), + String.valueOf(row.get("target_generation", Long.class)), + row.get("target_kid", String.class), + decodeActive(activeGeneration, activeKid), + row.get("readiness_binding_digest", String.class), + row.get("readiness_config_revision", String.class), + row.get("readiness_binding_valid_until_epoch_seconds", Long.class), + row.get("validator_id", String.class), + row.get("validator_instance_id", String.class), + row.get("validator_peer_uri", String.class), + row.get("validator_peer_spki_sha256", String.class), + row.get("claimed_at_epoch_seconds", Long.class), + row.get("expires_at_epoch_seconds", Long.class), + row.get("claim_digest", String.class)); + if (!result.claimDigest().equals(deliveryClaimDigest(result))) { + throw new QuarantinedStateException("Account readiness delivery claim digest is invalid"); + } + return result; + } + + private void insertEntry(ProbeEntry entry, int planVersion) { + Map fields = new LinkedHashMap<>(); + fields.put("rotation_operation_id", entry.rotationOperationId()); + fields.put("plan_digest", entry.planDigest()); + fields.put("validator_id", entry.validatorId()); + fields.put("token_profile", entry.tokenProfile()); + fields.put("audience", entry.audience()); + fields.put("probe_kind", entry.probeKind().name()); + fields.put("jti", entry.jti()); + fields.put("target_generation", Long.parseLong(entry.targetGeneration())); + fields.put("target_kid", entry.targetKid()); + fields.put( + "expected_active_generation", + entry.expectedActive().map(value -> Long.parseLong(value.generation())).orElse(null)); + fields.put("expected_active_kid", entry.expectedActive().map(ActiveSigner::kid).orElse(null)); + fields.put("registry_version", entry.registryVersion()); + fields.put("entry_version", entry.entryVersion()); + fields.put("planned_issued_at_epoch_seconds", entry.plannedIssuedAtEpochSecond()); + fields.put("expires_at_epoch_seconds", entry.expiresAtEpochSecond()); + fields.put("state", entry.state().name()); + fields.put("entry_plan_version", planVersion); + fields.put("terminal_outcome", null); + fields.put("signing_attempted_at_epoch_seconds", null); + fields.put("compact_token_sha256", null); + insertOne(dsl, ENTRY_TABLE, fields); + } + + private void insertExpectedPod(ExpectedPod expected) { + PodTarget target = expected.target(); + target.requireRoutablePodIdentity(); + Map fields = new LinkedHashMap<>(); + fields.put("rotation_operation_id", expected.rotationOperationId()); + fields.put("plan_digest", expected.planDigest()); + fields.put("validator_id", expected.validatorId()); + fields.put("token_profile", expected.tokenProfile()); + fields.put("audience", expected.audience()); + fields.put("probe_kind", expected.probeKind().name()); + fields.put("jti", expected.jti()); + fields.put("inventory_snapshot_digest", target.inventorySnapshotDigest()); + fields.put("environment_id", target.environmentId()); + fields.put("cluster_id", target.clusterId()); + fields.put("cluster_incarnation_uid", UUID.fromString(target.clusterIncarnationUid())); + fields.put("kubernetes_namespace", target.namespace()); + fields.put("namespace_uid", UUID.fromString(target.namespaceUid())); + fields.put("api_binding_revision", target.apiBindingRevision()); + fields.put("api_binding_digest", target.apiBindingDigest()); + fields.put("inventory_binding_revision", target.inventoryBindingRevision()); + fields.put("inventory_binding_digest", target.inventoryBindingDigest()); + fields.put("deployment_uid", UUID.fromString(target.deploymentUid())); + fields.put("pod_uid", UUID.fromString(target.podUid())); + fields.put("pod_ip", target.podIp()); + fields.put("image", target.image()); + fields.put("verifier_config_sha256", target.verifierConfigSha256()); + fields.put("applicability_matrix_digest", target.applicabilityMatrixDigest()); + fields.put("expected_outcome", target.expectation().name()); + fields.put("exact_pod_endpoint", target.exactPodEndpoint().map(URI::toString).orElse(null)); + fields.put("canonical_service_uri", target.canonicalServiceUri().orElse(null)); + fields.put("expected_pod_leaf_spki_sha256", target.podLeafSpkiSha256().orElse(null)); + insertOne(dsl, EXPECTED_POD_TABLE, fields); + } + + /** Reads the immutable, exact per-Pod plan rows for one current V2 entry. */ + @Transactional(propagation = Propagation.MANDATORY) + public List readCurrentExpectedPods( + Binding binding, TrustFence trust, ProbeEntry expectedEntry) { + throw new ReceiverUnavailableException(); + } + + /** Reads exact expected Pod rows only after a fresh independent owner observation. */ + @Transactional(propagation = Propagation.MANDATORY) + public List readCurrentExpectedPods( + Binding binding, + TrustFence trust, + ProbeEntry expectedEntry, + InventorySnapshot liveInventory) { + requireAccountTransaction(); + Objects.requireNonNull(expectedEntry, "Exact readiness entry is required"); + CurrentEvidence current = lockCurrentEvidence(binding, trust); + requireCurrentOperation(current, expectedEntry.rotationOperationId().toString()); + ReadinessProbePlan plan = requireStoredPlan(current); + if (plan.planVersion() != INVENTORY_PLAN_VERSION + || !plan.validatorInventoryComplete() + || !plan.planDigest().equals(expectedEntry.planDigest())) { + throw new ReceiverUnavailableException(); + } + requireLiveInventoryMatches(plan, binding, trust, liveInventory, observationContext(current)); + ProbeEntry stored = + selectEntry( + expectedEntry.rotationOperationId(), + expectedEntry.validatorId(), + expectedEntry.tokenProfile(), + expectedEntry.audience(), + expectedEntry.probeKind(), + true); + if (stored == null + || !stored.equals(expectedEntry) + || stored.state() != ProbeState.ISSUED + || stored.compactTokenSha256().isEmpty()) { + throw new StaleOperationException("Readiness receiver entry changed before invocation"); + } + plan.inventorySnapshotDigest() + .ifPresent(digest -> inventoryRepository.readRequired(digest, binding, trust)); + List expectedPods = selectExpectedPods(stored, true); + if (expectedPods.isEmpty() || expectedPods.size() > MAX_POD_RECEIPTS_PER_OPERATION) { + throw new QuarantinedStateException("Readiness V2 entry has no bounded expected Pod set"); + } + return expectedPods; + } + + /** + * Reads only the owner-retained coordinates and one Pod target for the authenticated V2 receiver + * lookup. The caller's tuple is a selector: every returned coordinate is projected from locked + * current owner rows, never copied from the request. + */ + @Transactional(propagation = Propagation.MANDATORY) + public OwnerProbeEvidence readCurrentProbeOwner( + Binding binding, + TrustFence trust, + AccountJwtReadinessProbeOwnerSelector selector, + InventorySnapshot liveInventory, + String authenticatedWorkloadNamespace) { + requireAccountTransaction(); + Objects.requireNonNull(selector, "Exact readiness probe selector is required"); + if (authenticatedWorkloadNamespace == null || authenticatedWorkloadNamespace.isBlank()) { + throw new ReceiverUnavailableException(); + } + CurrentEvidence current = lockCurrentEvidence(binding, trust); + if (!current.request().operationId().equals(selector.rotationOperationId())) { + throw new ReceiverUnavailableException(); + } + ReadinessProbePlan plan = requireStoredPlan(current); + if (plan.planVersion() != INVENTORY_PLAN_VERSION + || !plan.validatorInventoryComplete() + || !plan.operationId().equals(selector.rotationOperationId()) + || !plan.operationDigest().equals(selector.operationDigest()) + || !plan.planDigest().equals(selector.planDigest()) + || plan.planVersion() != selector.planVersion() + || plan.expiresAtEpochSecond() != selector.planExpiresAtEpochSecond() + || !plan.targetGeneration().equals(selector.targetGeneration()) + || !plan.targetKid().equals(selector.targetKid()) + || !plan.expectedFence().durableActive().equals(selector.expectedActive()) + || !plan.expectedFence().publishedActive().equals(selector.expectedActive())) { + throw new ReceiverUnavailableException(); + } + requireLiveInventoryMatches(plan, binding, trust, liveInventory, observationContext(current)); + if (readinessPlanOutOfWindow(plan)) { + throw new ReceiverUnavailableException(); + } + + ProbeEntry entry = + selectEntry( + selector.rotationOperationId(), + selector.validatorId(), + selector.tokenProfile(), + selector.audience(), + selector.probeKind(), + true); + if (entry == null + || entry.state() != ProbeState.ISSUED + || entry.verificationReceipt().isPresent() + || !entry.rotationOperationId().equals(selector.rotationOperationId()) + || !entry.planDigest().equals(plan.planDigest()) + || !entry.jti().equals(selector.jti()) + || entry.registryVersion() != selector.registryVersion() + || entry.entryVersion() != selector.entryVersion() + || !entry.targetGeneration().equals(selector.targetGeneration()) + || !entry.targetKid().equals(selector.targetKid()) + || !entry.expectedActive().equals(selector.expectedActive()) + || entry.plannedIssuedAtEpochSecond() != selector.issuedAtEpochSecond() + || entry.expiresAtEpochSecond() != selector.expiresAtEpochSecond() + || !entry.compactTokenSha256().equals(Optional.of(selector.compactTokenSha256()))) { + throw new ReceiverUnavailableException(); + } + Long databaseNow = + dsl.resultQuery("SELECT floor(extract(epoch FROM CURRENT_TIMESTAMP))::bigint") + .fetchOne(0, Long.class); + if (databaseNow == null + || databaseNow < entry.plannedIssuedAtEpochSecond() + || databaseNow >= entry.expiresAtEpochSecond()) { + throw new ReceiverUnavailableException(); + } + + List expectedPods = selectExpectedPods(entry, true); + if (expectedPods.isEmpty() || expectedPods.size() > MAX_POD_RECEIPTS_PER_OPERATION) { + throw new ReceiverUnavailableException(); + } + List selectedPods = + expectedPods.stream() + .filter(value -> value.target().podUid().equals(selector.localIdentity().podUid())) + .toList(); + if (selectedPods.size() != 1) { + throw new ReceiverUnavailableException(); + } + ExpectedPod expectedPod = selectedPods.getFirst(); + PodTarget target = expectedPod.target(); + target.requireRoutablePodIdentity(); + AccountJwtReadinessProbeOwnerSelector.LocalIdentity local = selector.localIdentity(); + if (!target.validatorId().equals(selector.validatorId()) + || !expectedPod.rotationOperationId().equals(selector.rotationOperationId()) + || !expectedPod.planDigest().equals(plan.planDigest()) + || !expectedPod.jti().equals(entry.jti()) + || target.expectation() != selector.expectedOutcome() + || !target.namespace().equals(authenticatedWorkloadNamespace) + || !local.validatorId().equals(target.validatorId()) + || !local.deploymentUid().equals(target.deploymentUid()) + || !local.podUid().equals(target.podUid()) + || !local.podIp().equals(target.podIp()) + || !local.directPodEndpoint().equals(target.exactPodEndpoint().orElseThrow().toString()) + || !local.canonicalServiceUri().equals(target.canonicalServiceUri().orElseThrow()) + || !local.image().equals(target.image()) + || !local.verifierConfigSha256().equals(target.verifierConfigSha256()) + || !local.applicabilityMatrixDigest().equals(plan.applicabilityMatrixDigest()) + || !local.serverLeafSpkiSha256().equals(target.podLeafSpkiSha256().orElseThrow())) { + throw new ReceiverUnavailableException(); + } + return new OwnerProbeEvidence(plan, entry, expectedPod); + } + + /** + * Records one owner-authenticated production verifier result for one exact expected Pod. A + * logical entry remains ISSUED until every immutable expected Pod has a matching unique receipt. + */ + @Transactional(propagation = Propagation.MANDATORY) + public ProbeEntry recordPodAcceptance( + Binding binding, + TrustFence trust, + ProbeEntry expectedEntry, + ExpectedPod expectedPod, + AuthenticatedAcceptance acceptance, + InventorySnapshot liveInventory) { + requireWritableAccountTransaction(); + Objects.requireNonNull(expectedEntry, "Exact readiness entry is required"); + Objects.requireNonNull(expectedPod, "Exact expected Pod row is required"); + Objects.requireNonNull(acceptance, "Owner-authenticated receiver result is required"); + CurrentEvidence current = lockCurrentEvidence(binding, trust); + requireCurrentOperation(current, expectedEntry.rotationOperationId().toString()); + ReadinessProbePlan plan = requireStoredPlan(current); + if (plan.planVersion() != INVENTORY_PLAN_VERSION + || !plan.validatorInventoryComplete() + || !plan.planDigest().equals(expectedEntry.planDigest()) + || !expectedPod.rotationOperationId().equals(plan.operationId()) + || !expectedPod.planDigest().equals(plan.planDigest()) + || !expectedPod.validatorId().equals(expectedEntry.validatorId()) + || !expectedPod.tokenProfile().equals(expectedEntry.tokenProfile()) + || !expectedPod.audience().equals(expectedEntry.audience()) + || expectedPod.probeKind() != expectedEntry.probeKind() + || !expectedPod.jti().equals(expectedEntry.jti())) { + throw new StaleOperationException("Readiness Pod receipt is outside the exact current entry"); + } + requireLiveInventoryMatches(plan, binding, trust, liveInventory, observationContext(current)); + ProbeEntry entry = + selectEntry( + expectedEntry.rotationOperationId(), + expectedEntry.validatorId(), + expectedEntry.tokenProfile(), + expectedEntry.audience(), + expectedEntry.probeKind(), + true); + if (entry == null + || entry.compactTokenSha256().isEmpty() + || !entry.rotationOperationId().equals(expectedEntry.rotationOperationId()) + || !entry.planDigest().equals(expectedEntry.planDigest()) + || !entry.validatorId().equals(expectedEntry.validatorId()) + || !entry.tokenProfile().equals(expectedEntry.tokenProfile()) + || !entry.audience().equals(expectedEntry.audience()) + || entry.probeKind() != expectedEntry.probeKind() + || !entry.jti().equals(expectedEntry.jti()) + || !entry.targetGeneration().equals(expectedEntry.targetGeneration()) + || !entry.targetKid().equals(expectedEntry.targetKid()) + || !entry.expectedActive().equals(expectedEntry.expectedActive()) + || entry.registryVersion() != expectedEntry.registryVersion() + || entry.plannedIssuedAtEpochSecond() != expectedEntry.plannedIssuedAtEpochSecond() + || entry.expiresAtEpochSecond() != expectedEntry.expiresAtEpochSecond()) { + throw new AmbiguousDeliveryException("Readiness Pod receipt requires its exact ISSUED entry"); + } + boolean alreadyVerified = entry.state() == ProbeState.VERIFIED; + if ((!alreadyVerified && entry.state() != ProbeState.ISSUED) + || (!alreadyVerified && !entry.equals(expectedEntry)) + || (alreadyVerified + && (entry.entryVersion() <= 1L + || entry + .verificationReceipt() + .filter(value -> value.receiptVersion() == 2) + .isEmpty()))) { + throw new AmbiguousDeliveryException("Readiness Pod receipt requires its exact ISSUED entry"); + } + List expectedPods = selectExpectedPods(entry, true); + ExpectedPod persistedPod = + expectedPods.stream() + .filter(value -> value.target().podUid().equals(expectedPod.target().podUid())) + .findFirst() + .orElseThrow(ReceiverUnavailableException::new); + if (!persistedPod.equals(expectedPod)) { + throw new QuarantinedStateException("Readiness Pod target changed after its immutable plan"); + } + PodTarget target = persistedPod.target(); + target.requireRoutablePodIdentity(); + long observedAt = acceptance.observedAtEpochSecond(); + if (!acceptance.podUid().equals(target.podUid()) + || !acceptance + .actualPodEndpoint() + .equals(target.exactPodEndpoint().orElseThrow().toString()) + || !acceptance.image().equals(target.image()) + || !acceptance.verifierConfigSha256().equals(target.verifierConfigSha256()) + || !acceptance.actualServiceUri().equals(target.canonicalServiceUri().orElseThrow()) + || !acceptance.actualPeerSpkiSha256().equals(target.podLeafSpkiSha256().orElseThrow()) + || !acceptance.jti().equals(entry.jti()) + || !acceptance.compactTokenSha256().equals(entry.compactTokenSha256().orElseThrow()) + || acceptance.result() != target.expectation() + || !entry.targetKid().equals(acceptance.verifiedKid())) { + throw new IdempotencyConflictException( + "Authenticated receiver evidence differs from the exact protected Pod target"); + } + requireNotExpired(entry, observedAt); + if (observedAt < entry.plannedIssuedAtEpochSecond()) { + throw new CacheAgeNotElapsedException(); + } + + PodReceipt candidate = + podReceipt( + entry, + persistedPod, + acceptance, + alreadyVerified ? entry.entryVersion() - 1L : entry.entryVersion()); + PodReceipt existing = selectPodReceipt(candidate, true); + if (alreadyVerified) { + List retainedReceipts = selectPodReceipts(entry, true); + ProbeEntry sourceEntry = sourceEntryForVerifiedClosure(entry); + VerificationReceipt recomputed = + podReceiptClosure(plan, sourceEntry, expectedPods, retainedReceipts); + if (existing == null + || !existing.equals(candidate) + || retainedReceipts.size() != expectedPods.size() + || entry.verificationReceipt().filter(recomputed::equals).isEmpty()) { + throw new IdempotencyConflictException( + "A completed readiness Pod receipt retry differs from its immutable evidence"); + } + return entry; + } + if (existing != null) { + if (!existing.equals(candidate)) { + throw new IdempotencyConflictException( + "A per-Pod readiness receipt already exists with different evidence"); + } + } else { + insertPodReceipt(candidate); + PodReceipt readback = selectPodReceipt(candidate, true); + if (readback == null || !readback.equals(candidate)) { + throw new QuarantinedStateException("Readiness Pod receipt did not read back exactly"); + } + } + + List receipts = selectPodReceipts(entry, true); + if (receipts.size() != expectedPods.size()) { + if (receipts.size() > expectedPods.size()) { + throw new QuarantinedStateException("Readiness Pod receipt set exceeds its exact target"); + } + ProbeEntry partial = selectEntry(entry, true); + if (partial == null || partial.state() != ProbeState.ISSUED) { + throw new QuarantinedStateException("Partial per-Pod receipt changed its logical entry"); + } + return partial; + } + VerificationReceipt closure = podReceiptClosure(plan, entry, expectedPods, receipts); + long resultEntryVersion = Math.addExact(entry.entryVersion(), 1L); + VerificationReceipt finalReceipt = + new VerificationReceipt( + closure.receiptVersion(), + entry.entryVersion(), + resultEntryVersion, + closure.observedAtEpochSecond(), + closure.receiptSha256(), + closure.verifiedKid(), + closure.validatorInstanceId(), + closure.validatorBindingDigest(), + closure.validatorConfigRevision(), + closure.validatorPeerUri(), + closure.validatorPeerSpkiSha256(), + closure.podReceiptCount(), + closure.podReceiptClosureSha256()); + int changed = + dsl.execute( + "UPDATE " + + ENTRY_TABLE + + " SET state = 'VERIFIED', entry_version = ?, verification_receipt_version = ?, " + + "verification_source_entry_version = ?, verified_at_epoch_seconds = ?, " + + "verified_kid = ?, validator_instance_id = ?, validator_binding_digest = ?, " + + "validator_config_revision = ?, validator_peer_uri = ?, " + + "validator_peer_spki_sha256 = ?, verification_receipt_sha256 = ?, " + + "pod_receipt_count = ?, pod_receipt_closure_sha256 = ? " + + "WHERE rotation_operation_id = ? AND validator_id = ? AND token_profile = ? " + + "AND audience = ? AND probe_kind = ? AND jti = ? AND plan_digest = ? " + + "AND entry_plan_version = 2 AND state = 'ISSUED' AND entry_version = ? " + + "AND target_generation = ? AND target_kid = ? AND compact_token_sha256 = ? " + + "AND verification_receipt_sha256 IS NULL " + + "AND CURRENT_TIMESTAMP >= to_timestamp(planned_issued_at_epoch_seconds) " + + "AND CURRENT_TIMESTAMP < to_timestamp(expires_at_epoch_seconds)", + finalReceipt.resultEntryVersion(), + finalReceipt.receiptVersion(), + finalReceipt.sourceEntryVersion(), + finalReceipt.observedAtEpochSecond(), + finalReceipt.verifiedKid(), + finalReceipt.validatorInstanceId(), + finalReceipt.validatorBindingDigest(), + finalReceipt.validatorConfigRevision(), + finalReceipt.validatorPeerUri(), + finalReceipt.validatorPeerSpkiSha256(), + finalReceipt.receiptSha256(), + finalReceipt.podReceiptCount(), + finalReceipt.podReceiptClosureSha256(), + entry.rotationOperationId(), + entry.validatorId(), + entry.tokenProfile(), + entry.audience(), + entry.probeKind().name(), + entry.jti(), + entry.planDigest(), + entry.entryVersion(), + Long.parseLong(entry.targetGeneration()), + entry.targetKid(), + entry.compactTokenSha256().orElseThrow()); + if (changed != 1) { + throw new VersionConflictException("Readiness per-Pod closure lost its exact CAS"); + } + ProbeEntry readback = selectEntry(entry, true); + if (readback == null + || readback.state() != ProbeState.VERIFIED + || readback.entryVersion() != finalReceipt.resultEntryVersion() + || readback.verificationReceipt().filter(finalReceipt::equals).isEmpty()) { + throw new QuarantinedStateException("Readiness per-Pod closure did not read back exactly"); + } + return readback; + } + + private List selectExpectedPods(ProbeEntry entry, boolean lock) { + Result rows = + dsl.fetch( + "SELECT * FROM " + + EXPECTED_POD_TABLE + + " WHERE rotation_operation_id = ? AND validator_id = ? AND token_profile = ? " + + "AND audience = ? AND probe_kind = ? ORDER BY pod_uid" + + (lock ? " FOR KEY SHARE" : ""), + entry.rotationOperationId(), + entry.validatorId(), + entry.tokenProfile(), + entry.audience(), + entry.probeKind().name()); + List expected = new ArrayList<>(rows.size()); + for (Record row : rows) { + String endpoint = row.get("exact_pod_endpoint", String.class); + expected.add( + new ExpectedPod( + row.get("rotation_operation_id", UUID.class), + row.get("plan_digest", String.class), + row.get("validator_id", String.class), + row.get("token_profile", String.class), + row.get("audience", String.class), + ProbeKind.valueOf(row.get("probe_kind", String.class)), + row.get("jti", UUID.class), + new PodTarget( + row.get("inventory_snapshot_digest", String.class), + row.get("environment_id", String.class), + row.get("cluster_id", String.class), + row.get("cluster_incarnation_uid", UUID.class).toString(), + row.get("kubernetes_namespace", String.class), + row.get("namespace_uid", UUID.class).toString(), + row.get("api_binding_revision", String.class), + row.get("api_binding_digest", String.class), + row.get("inventory_binding_revision", String.class), + row.get("inventory_binding_digest", String.class), + row.get("validator_id", String.class), + row.get("deployment_uid", UUID.class).toString(), + row.get("pod_uid", UUID.class).toString(), + row.get("pod_ip", String.class), + row.get("image", String.class), + row.get("verifier_config_sha256", String.class), + row.get("applicability_matrix_digest", String.class), + ProbeExpectation.valueOf(row.get("expected_outcome", String.class)), + Optional.ofNullable(endpoint).map(URI::create), + Optional.ofNullable(row.get("canonical_service_uri", String.class)), + Optional.ofNullable(row.get("expected_pod_leaf_spki_sha256", String.class))))); + } + return List.copyOf(expected); + } + + private void requireLiveInventoryMatches( + ReadinessProbePlan plan, + Binding binding, + TrustFence trust, + InventorySnapshot liveInventory, + ObservationContext expectedContext) { + Objects.requireNonNull(liveInventory, "Fresh protected live inventory is required"); + requireFreshLiveInventory(liveInventory); + String expectedDigest = + plan.inventorySnapshotDigest().orElseThrow(ReceiverUnavailableException::new); + AccountJwtValidatorInventoryRepository.StoredSnapshot stored = + inventoryRepository.readRequired(expectedDigest, binding, trust); + if (liveInventory.observationContext().filter(expectedContext::equals).isEmpty() + || !expectedDigest.equals(liveInventory.digest()) + || !stored.digest().equals(liveInventory.digest()) + || !stored.environmentId().equals(liveInventory.environmentId()) + || !stored.clusterId().equals(liveInventory.clusterId()) + || !stored.clusterIncarnationUid().equals(liveInventory.clusterIncarnationUid()) + || !stored.namespace().equals(liveInventory.namespace()) + || !stored.namespaceUid().equals(liveInventory.namespaceUid()) + || !stored.apiBindingRevision().equals(liveInventory.apiBindingRevision()) + || !stored.apiBindingDigest().equals(liveInventory.apiBindingDigest()) + || !stored.inventoryBindingRevision().equals(liveInventory.inventoryBindingRevision()) + || !stored.inventoryBindingDigest().equals(liveInventory.inventoryBindingDigest()) + || !MessageDigest.isEqual(stored.canonicalBytes(), liveInventory.canonicalBytes())) { + throw new ReceiverUnavailableException(); + } + } + + private static void requireObservationContext( + CurrentEvidence current, InventorySnapshot snapshot) { + if (snapshot.observationContext().filter(observationContext(current)::equals).isEmpty()) { + throw new InventoryPlanConflictException(); + } + } + + private static ObservationContext observationContext(CurrentEvidence current) { + return observationContext( + current.request().operationId(), + current.request().operationDigest(), + new SignerFence(current.state().durableActive(), current.state().publishedActive())); + } + + private static ObservationContext observationContext( + UUID operationId, String operationDigest, SignerFence expectedFence) { + if (!expectedFence.durableActive().equals(expectedFence.publishedActive())) { + throw new StaleOperationException("JWT active signer fence changed during inventory proof"); + } + ObservationPurpose purpose = + expectedFence.durableActive().isEmpty() + ? ObservationPurpose.INITIAL_NO_ACTIVE_SIGNER_CANDIDATES + : ObservationPurpose.STRICT_READY; + return new ObservationContext(purpose, operationId, operationDigest); + } + + private void requireFreshLiveInventory(InventorySnapshot snapshot) { + long observedAt = snapshot.observedAt().getEpochSecond(); + Long databaseNow = + dsl.resultQuery("SELECT floor(extract(epoch FROM CURRENT_TIMESTAMP))::bigint") + .fetchOne(0, Long.class); + if (databaseNow == null) { + throw new StorageUnavailableException("Account validator inventory clock is unavailable"); + } + if (observedAt <= 0L + || observedAt > databaseNow + || databaseNow - observedAt > MAX_VALIDATOR_CACHE_AGE_SECONDS) { + throw new ReceiverUnavailableException(); + } + } + + private boolean hasCompletePodReceiptClosure(ReadinessProbePlan plan) { + if (plan.planVersion() != INVENTORY_PLAN_VERSION || !plan.validatorInventoryComplete()) { + return false; + } + int totalReceipts = 0; + for (ProbeEntry entry : plan.entries()) { + if (entry.state() != ProbeState.VERIFIED) { + return false; + } + VerificationReceipt receipt = entry.verificationReceipt().orElseThrow(); + if (receipt.receiptVersion() != 2) { + throw new QuarantinedStateException( + "V2 readiness entry has no per-Pod verification closure receipt"); + } + List expectedPods = selectExpectedPods(entry, true); + List podReceipts = selectPodReceipts(entry, true); + if (expectedPods.isEmpty() || expectedPods.size() != receipt.podReceiptCount()) { + throw new QuarantinedStateException( + "V2 readiness receipt count differs from its exact expected Pod inventory"); + } + if (podReceipts.size() < expectedPods.size()) { + return false; + } + if (podReceipts.size() != expectedPods.size()) { + throw new QuarantinedStateException( + "V2 readiness receipt set exceeds its exact expected Pod inventory"); + } + ProbeEntry sourceEntry = sourceEntryForVerifiedClosure(entry); + VerificationReceipt recomputed = + podReceiptClosure(plan, sourceEntry, expectedPods, podReceipts); + if (!recomputed.equals(receipt)) { + throw new QuarantinedStateException( + "V2 readiness entry closure differs from retained per-Pod receipts"); + } + totalReceipts = Math.addExact(totalReceipts, podReceipts.size()); + if (totalReceipts > MAX_POD_RECEIPTS_PER_OPERATION) { + throw new QuarantinedStateException("Readiness Pod receipt closure exceeds its bound"); + } + } + return totalReceipts > 0; + } + + private void insertPodReceipt(PodReceipt receipt) { + dsl.execute( + "INSERT INTO " + + POD_RECEIPT_TABLE + + " (rotation_operation_id, plan_digest, validator_id, token_profile, audience, " + + "probe_kind, pod_uid, receipt_version, jti, source_entry_version, " + + "compact_token_sha256, target_generation, target_kid, expected_active_generation, " + + "expected_active_kid, outcome, observed_pod_uid, observed_image, " + + "observed_verifier_config_sha256, verified_kid, receiver_endpoint, " + + "receiver_service_uri, receiver_peer_spki_sha256, observed_at_epoch_seconds, receipt_sha256) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) " + + "ON CONFLICT (rotation_operation_id, validator_id, token_profile, audience, probe_kind, pod_uid) " + + "DO NOTHING", + receipt.rotationOperationId(), + receipt.planDigest(), + receipt.validatorId(), + receipt.tokenProfile(), + receipt.audience(), + receipt.probeKind().name(), + UUID.fromString(receipt.podUid()), + 1, + receipt.jti(), + receipt.sourceEntryVersion(), + receipt.compactTokenSha256(), + Long.parseLong(receipt.targetGeneration()), + receipt.targetKid(), + receipt.expectedActive().map(value -> Long.parseLong(value.generation())).orElse(null), + receipt.expectedActive().map(ActiveSigner::kid).orElse(null), + receipt.outcome().name(), + UUID.fromString(receipt.observedPodUid()), + receipt.image(), + receipt.verifierConfigSha256(), + receipt.verifiedKid(), + receipt.receiverEndpoint().toString(), + receipt.receiverServiceUri(), + receipt.receiverPeerSpkiSha256(), + receipt.observedAtEpochSecond(), + receipt.receiptSha256()); + } + + private PodReceipt selectPodReceipt(PodReceipt key, boolean lock) { + Record row = + dsl.fetchOne( + "SELECT * FROM " + + POD_RECEIPT_TABLE + + " WHERE rotation_operation_id = ? AND validator_id = ? AND token_profile = ? " + + "AND audience = ? AND probe_kind = ? AND pod_uid = ?" + + (lock ? " FOR UPDATE" : ""), + key.rotationOperationId(), + key.validatorId(), + key.tokenProfile(), + key.audience(), + key.probeKind().name(), + UUID.fromString(key.podUid())); + return row == null ? null : decodePodReceipt(row); + } + + private List selectPodReceipts(ProbeEntry entry, boolean lock) { + Result rows = + dsl.fetch( + "SELECT * FROM " + + POD_RECEIPT_TABLE + + " WHERE rotation_operation_id = ? AND validator_id = ? AND token_profile = ? " + + "AND audience = ? AND probe_kind = ? ORDER BY pod_uid" + + (lock ? " FOR UPDATE" : ""), + entry.rotationOperationId(), + entry.validatorId(), + entry.tokenProfile(), + entry.audience(), + entry.probeKind().name()); + List receipts = new ArrayList<>(rows.size()); + for (Record row : rows) { + receipts.add(decodePodReceipt(row)); + } + return List.copyOf(receipts); + } + + private static PodReceipt decodePodReceipt(Record row) { + Long activeGeneration = row.get("expected_active_generation", Long.class); + String activeKid = row.get("expected_active_kid", String.class); + PodReceipt receipt = + new PodReceipt( + row.get("rotation_operation_id", UUID.class), + row.get("plan_digest", String.class), + row.get("validator_id", String.class), + row.get("token_profile", String.class), + row.get("audience", String.class), + ProbeKind.valueOf(row.get("probe_kind", String.class)), + row.get("pod_uid", UUID.class).toString(), + row.get("jti", UUID.class), + row.get("source_entry_version", Long.class), + row.get("compact_token_sha256", String.class), + String.valueOf(row.get("target_generation", Long.class)), + row.get("target_kid", String.class), + decodeActive(activeGeneration, activeKid), + ProbeExpectation.valueOf(row.get("outcome", String.class)), + row.get("observed_pod_uid", UUID.class).toString(), + row.get("observed_image", String.class), + row.get("observed_verifier_config_sha256", String.class), + row.get("verified_kid", String.class), + URI.create(row.get("receiver_endpoint", String.class)), + row.get("receiver_service_uri", String.class), + row.get("receiver_peer_spki_sha256", String.class), + row.get("observed_at_epoch_seconds", Long.class), + row.get("receipt_sha256", String.class)); + if (!receipt.receiptSha256().equals(podReceiptDigest(receipt))) { + throw new QuarantinedStateException("Immutable per-Pod readiness receipt digest is invalid"); + } + return receipt; + } + + private static PodReceipt podReceipt( + ProbeEntry entry, + ExpectedPod expected, + AuthenticatedAcceptance acceptance, + long sourceEntryVersion) { + PodTarget target = expected.target(); + PodReceipt unsigned = + new PodReceipt( + entry.rotationOperationId(), + entry.planDigest(), + entry.validatorId(), + entry.tokenProfile(), + entry.audience(), + entry.probeKind(), + target.podUid(), + entry.jti(), + sourceEntryVersion, + entry.compactTokenSha256().orElseThrow(), + entry.targetGeneration(), + entry.targetKid(), + entry.expectedActive(), + acceptance.result(), + acceptance.podUid(), + acceptance.image(), + acceptance.verifierConfigSha256(), + acceptance.verifiedKid(), + URI.create(acceptance.actualPodEndpoint()), + acceptance.actualServiceUri(), + acceptance.actualPeerSpkiSha256(), + acceptance.observedAtEpochSecond(), + "0".repeat(64)); + return new PodReceipt( + unsigned.rotationOperationId(), + unsigned.planDigest(), + unsigned.validatorId(), + unsigned.tokenProfile(), + unsigned.audience(), + unsigned.probeKind(), + unsigned.podUid(), + unsigned.jti(), + unsigned.sourceEntryVersion(), + unsigned.compactTokenSha256(), + unsigned.targetGeneration(), + unsigned.targetKid(), + unsigned.expectedActive(), + unsigned.outcome(), + unsigned.observedPodUid(), + unsigned.image(), + unsigned.verifierConfigSha256(), + unsigned.verifiedKid(), + unsigned.receiverEndpoint(), + unsigned.receiverServiceUri(), + unsigned.receiverPeerSpkiSha256(), + unsigned.observedAtEpochSecond(), + podReceiptDigest(unsigned)); + } + + private static ProbeEntry sourceEntryForVerifiedClosure(ProbeEntry verified) { + VerificationReceipt receipt = verified.verificationReceipt().orElseThrow(); + if (receipt.receiptVersion() != 2 + || receipt.sourceEntryVersion() + 1L != verified.entryVersion()) { + throw new QuarantinedStateException("Verified per-Pod closure has an invalid source version"); + } + return new ProbeEntry( + verified.rotationOperationId(), + verified.planDigest(), + verified.validatorId(), + verified.tokenProfile(), + verified.audience(), + verified.probeKind(), + verified.jti(), + verified.targetGeneration(), + verified.targetKid(), + verified.expectedActive(), + verified.registryVersion(), + receipt.sourceEntryVersion(), + verified.plannedIssuedAtEpochSecond(), + verified.expiresAtEpochSecond(), + ProbeState.ISSUED, + Optional.empty(), + verified.signingAttemptedAtEpochSecond(), + verified.compactTokenSha256(), + Optional.empty()); + } + + private static String podReceiptDigest(PodReceipt receipt) { + Map value = new LinkedHashMap<>(); + value.put("domain", "account-jwt-readiness-per-pod-receipt/v1"); + value.put("rotationOperationId", receipt.rotationOperationId().toString()); + value.put("planDigest", receipt.planDigest()); + value.put("validatorId", receipt.validatorId()); + value.put("tokenProfile", receipt.tokenProfile()); + value.put("audience", receipt.audience()); + value.put("probeKind", receipt.probeKind().name()); + value.put("podUid", receipt.podUid()); + value.put("jti", receipt.jti().toString()); + value.put("sourceEntryVersion", receipt.sourceEntryVersion()); + value.put("compactTokenSha256", receipt.compactTokenSha256()); + value.put("targetGeneration", receipt.targetGeneration()); + value.put("targetKid", receipt.targetKid()); + value.put("expectedActive", activeMap(receipt.expectedActive())); + value.put("outcome", receipt.outcome().name()); + value.put("observedPodUid", receipt.observedPodUid()); + value.put("image", receipt.image()); + value.put("verifierConfigSha256", receipt.verifierConfigSha256()); + value.put("verifiedKid", receipt.verifiedKid()); + value.put("receiverEndpoint", receipt.receiverEndpoint().toString()); + value.put("receiverServiceUri", receipt.receiverServiceUri()); + value.put("receiverPeerSpkiSha256", receipt.receiverPeerSpkiSha256()); + value.put("observedAtEpochSecond", receipt.observedAtEpochSecond()); + return digest(value); + } + + private static VerificationReceipt podReceiptClosure( + ReadinessProbePlan plan, + ProbeEntry entry, + List expectedPods, + List receipts) { + Map expectedByUid = new LinkedHashMap<>(); + for (ExpectedPod expected : expectedPods) { + if (expectedByUid.putIfAbsent(expected.target().podUid(), expected) != null) { + throw new QuarantinedStateException("Readiness Pod plan contains duplicate Pod UIDs"); + } + } + Map receiptsByUid = new LinkedHashMap<>(); + for (PodReceipt receipt : receipts) { + ExpectedPod expected = expectedByUid.get(receipt.podUid()); + if (expected == null + || receiptsByUid.putIfAbsent(receipt.podUid(), receipt) != null + || !receipt.rotationOperationId().equals(entry.rotationOperationId()) + || !receipt.planDigest().equals(entry.planDigest()) + || !receipt.validatorId().equals(entry.validatorId()) + || !receipt.tokenProfile().equals(entry.tokenProfile()) + || !receipt.audience().equals(entry.audience()) + || receipt.probeKind() != entry.probeKind() + || !receipt.jti().equals(entry.jti()) + || receipt.sourceEntryVersion() != entry.entryVersion() + || !receipt.compactTokenSha256().equals(entry.compactTokenSha256().orElseThrow()) + || !receipt.targetGeneration().equals(entry.targetGeneration()) + || !receipt.targetKid().equals(entry.targetKid()) + || !receipt.expectedActive().equals(entry.expectedActive()) + || receipt.outcome() != expected.target().expectation() + || !receipt.observedPodUid().equals(expected.target().podUid()) + || !receipt.image().equals(expected.target().image()) + || !receipt.verifierConfigSha256().equals(expected.target().verifierConfigSha256()) + || !receipt.receiverEndpoint().equals(expected.target().exactPodEndpoint().orElseThrow()) + || !receipt + .receiverServiceUri() + .equals(expected.target().canonicalServiceUri().orElseThrow()) + || !receipt + .receiverPeerSpkiSha256() + .equals(expected.target().podLeafSpkiSha256().orElseThrow()) + || !receipt.receiptSha256().equals(podReceiptDigest(receipt))) { + throw new QuarantinedStateException( + "Readiness Pod receipt does not match its exact target"); + } + } + if (expectedByUid.size() != receiptsByUid.size() + || expectedByUid.isEmpty() + || expectedByUid.size() > MAX_POD_RECEIPTS_PER_OPERATION) { + throw new QuarantinedStateException("Readiness Pod receipt closure is incomplete"); + } + ProbeExpectation expectedOutcome = null; + List> closurePods = new ArrayList<>(); + List ordered = + expectedPods.stream() + .sorted(java.util.Comparator.comparing(value -> value.target().podUid())) + .toList(); + long observedAt = 0L; + for (ExpectedPod expected : ordered) { + PodTarget target = expected.target(); + PodReceipt receipt = receiptsByUid.get(target.podUid()); + if (receipt == null || (expectedOutcome != null && expectedOutcome != target.expectation())) { + throw new QuarantinedStateException("Readiness Pod expectations are not a closed matrix"); + } + expectedOutcome = target.expectation(); + observedAt = Math.max(observedAt, receipt.observedAtEpochSecond()); + Map pod = new LinkedHashMap<>(); + pod.put("podUid", target.podUid()); + pod.put("podIpEndpoint", target.exactPodEndpoint().orElseThrow().toString()); + pod.put("serviceUri", target.canonicalServiceUri().orElseThrow()); + pod.put("leafSpkiSha256", target.podLeafSpkiSha256().orElseThrow()); + pod.put("image", target.image()); + pod.put("verifierConfigSha256", target.verifierConfigSha256()); + pod.put("receiptSha256", receipt.receiptSha256()); + closurePods.add(pod); + } + ExpectedPod first = ordered.get(0); + PodTarget firstTarget = first.target(); + Map closure = new LinkedHashMap<>(); + closure.put("domain", "account-jwt-readiness-per-pod-closure/v1"); + closure.put("rotationOperationId", plan.operationId().toString()); + closure.put("planDigest", plan.planDigest()); + closure.put("applicabilityMatrixDigest", plan.applicabilityMatrixDigest()); + closure.put("inventorySnapshotDigest", plan.inventorySnapshotDigest().orElseThrow()); + closure.put("validatorId", entry.validatorId()); + closure.put("tokenProfile", entry.tokenProfile()); + closure.put("audience", entry.audience()); + closure.put("probeKind", entry.probeKind().name()); + closure.put("jti", entry.jti().toString()); + closure.put("sourceEntryVersion", entry.entryVersion()); + closure.put("compactTokenSha256", entry.compactTokenSha256().orElseThrow()); + closure.put("targetGeneration", entry.targetGeneration()); + closure.put("targetKid", entry.targetKid()); + closure.put("expectedActive", activeMap(entry.expectedActive())); + closure.put("pods", closurePods); + String closureSha256 = digest(closure); + return new VerificationReceipt( + 2, + entry.entryVersion(), + entry.entryVersion() + 1L, + observedAt, + closureSha256, + entry.targetKid(), + firstTarget.podUid(), + firstTarget.inventoryBindingDigest(), + firstTarget.inventoryBindingRevision(), + firstTarget.canonicalServiceUri().orElseThrow(), + firstTarget.podLeafSpkiSha256().orElseThrow(), + expectedPods.size(), + closureSha256); + } + + private ReadinessProbePlan selectPlan(UUID operationId, boolean lock) { + Record row = + dsl.fetchOne( + "SELECT * FROM " + + PLAN_TABLE + + " WHERE rotation_operation_id = ?" + + (lock ? " FOR UPDATE" : ""), + operationId); + return row == null ? null : decodePlan(row, selectEntries(operationId, lock)); + } + + private ReadinessProbePlan readbackPlan(ReadinessProbePlan plan, boolean lock) { + List entries = selectEntries(plan.operationId(), lock); + if (!entries.equals(plan.entries())) { + throw new QuarantinedStateException("Readiness probe entries changed after plan persistence"); + } + if (!plan.planDigest().equals(planDigest(plan))) { + throw new QuarantinedStateException("Readiness probe plan digest is invalid"); + } + plan.inventorySnapshotDigest() + .ifPresent( + digest -> inventoryRepository.readRequired(digest, plan.binding(), plan.trustFence())); + return plan; + } + + private List selectEntries(UUID operationId, boolean lock) { + Result rows = + dsl.fetch( + "SELECT * FROM " + + ENTRY_TABLE + + " WHERE rotation_operation_id = ? ORDER BY validator_id, CASE token_profile WHEN '" + + CANARY_PROFILE + + "' THEN 0 WHEN '" + + CONTROL_UI_PROFILE + + "' THEN 1 WHEN '" + + PLAYER_BOOTSTRAP_PROFILE + + "' THEN 2 WHEN '" + + REPRESENTATIVE_PROFILE + + "' THEN 3 ELSE 4 END, token_profile, audience, probe_kind" + + (lock ? " FOR UPDATE" : ""), + operationId); + List entries = new ArrayList<>(rows.size()); + for (Record row : rows) { + entries.add(decodeEntry(row)); + } + return List.copyOf(entries); + } + + // V1 digests bind the established canary/control/player/delegation profile order. V2 adds + // validator identity as the leading key; per-Pod requirements remain separately bound rows. + private static final Comparator PROBE_ENTRY_ORDER = + Comparator.comparing(ProbeEntry::validatorId) + .thenComparingInt(entry -> profileOrder(entry.tokenProfile())) + .thenComparing(ProbeEntry::audience) + .thenComparing(entry -> entry.probeKind().name()); + + private static int profileOrder(String profile) { + if (CANARY_PROFILE.equals(profile)) return 0; + if (CONTROL_UI_PROFILE.equals(profile)) return 1; + if (PLAYER_BOOTSTRAP_PROFILE.equals(profile)) return 2; + if (REPRESENTATIVE_PROFILE.equals(profile)) return 3; + throw new QuarantinedStateException("Readiness probe profile has no canonical plan order"); + } + + private ProbeEntry selectEntry( + UUID operationId, + String validatorId, + String tokenProfile, + String audience, + ProbeKind probeKind, + boolean lock) { + Record row = + dsl.fetchOne( + "SELECT * FROM " + + ENTRY_TABLE + + " WHERE rotation_operation_id = ? AND validator_id = ? AND token_profile = ? " + + "AND audience = ? AND probe_kind = ?" + + (lock ? " FOR UPDATE" : ""), + operationId, + validatorId, + tokenProfile, + audience, + probeKind.name()); + return row == null ? null : decodeEntry(row); + } + + private ProbeEntry selectEntry(ProbeEntry entry, boolean lock) { + return selectEntry( + entry.rotationOperationId(), + entry.validatorId(), + entry.tokenProfile(), + entry.audience(), + entry.probeKind(), + lock); + } + + private ProbeEntry decodeEntry(Record row) { + Long activeGeneration = row.get("expected_active_generation", Long.class); + String activeKid = row.get("expected_active_kid", String.class); + Optional expectedActive = decodeActive(activeGeneration, activeKid); + Long attemptAt = row.get("signing_attempted_at_epoch_seconds", Long.class); + String hash = row.get("compact_token_sha256", String.class); + String terminalOutcome = row.get("terminal_outcome", String.class); + VerificationReceipt receipt = decodeVerificationReceipt(row); + return new ProbeEntry( + row.get("rotation_operation_id", UUID.class), + row.get("plan_digest", String.class), + row.get("validator_id", String.class), + row.get("token_profile", String.class), + row.get("audience", String.class), + ProbeKind.valueOf(row.get("probe_kind", String.class)), + row.get("jti", UUID.class), + String.valueOf(row.get("target_generation", Long.class)), + row.get("target_kid", String.class), + expectedActive, + row.get("registry_version", Short.class).intValue(), + row.get("entry_version", Long.class), + row.get("planned_issued_at_epoch_seconds", Long.class), + row.get("expires_at_epoch_seconds", Long.class), + ProbeState.valueOf(row.get("state", String.class)), + Optional.ofNullable(terminalOutcome), + Optional.ofNullable(attemptAt), + Optional.ofNullable(hash), + Optional.ofNullable(receipt)); + } + + private VerificationReceipt decodeVerificationReceipt(Record row) { + Short version = row.get("verification_receipt_version", Short.class); + Long sourceVersion = row.get("verification_source_entry_version", Long.class); + Long verifiedAt = row.get("verified_at_epoch_seconds", Long.class); + String verifiedKid = row.get("verified_kid", String.class); + String validatorInstanceId = row.get("validator_instance_id", String.class); + String bindingDigest = row.get("validator_binding_digest", String.class); + String configRevision = row.get("validator_config_revision", String.class); + String peerUri = row.get("validator_peer_uri", String.class); + String peerSpki = row.get("validator_peer_spki_sha256", String.class); + String receiptSha256 = row.get("verification_receipt_sha256", String.class); + Short podReceiptCount = row.get("pod_receipt_count", Short.class); + String podReceiptClosureSha256 = row.get("pod_receipt_closure_sha256", String.class); + if (version == null + && sourceVersion == null + && verifiedAt == null + && verifiedKid == null + && validatorInstanceId == null + && bindingDigest == null + && configRevision == null + && peerUri == null + && peerSpki == null + && receiptSha256 == null + && podReceiptCount == null + && podReceiptClosureSha256 == null) { + return null; + } + if (version == null + || sourceVersion == null + || verifiedAt == null + || validatorInstanceId == null + || bindingDigest == null + || configRevision == null + || peerUri == null + || peerSpki == null + || receiptSha256 == null) { + throw new QuarantinedStateException("Readiness verification receipt is partial"); + } + if ((version == 1 + && (verifiedKid == null || podReceiptCount != null || podReceiptClosureSha256 != null)) + || (version == 2 && (podReceiptCount == null || podReceiptClosureSha256 == null))) { + throw new QuarantinedStateException("Readiness verification receipt version is partial"); + } + Long resultVersion = Math.addExact(sourceVersion, 1L); + return new VerificationReceipt( + version.intValue(), + sourceVersion, + resultVersion, + verifiedAt, + receiptSha256, + verifiedKid, + validatorInstanceId, + bindingDigest, + configRevision, + peerUri, + peerSpki, + podReceiptCount == null ? 0 : podReceiptCount.intValue(), + podReceiptClosureSha256); + } + + private ReadinessProbePlan decodePlan(Record row, List entries) { + Long activeGeneration = row.get("expected_active_generation", Long.class); + String activeKid = row.get("expected_active_kid", String.class); + Long publishedGeneration = row.get("expected_published_generation", Long.class); + String publishedKid = row.get("expected_published_kid", String.class); + SignerFence fence = + new SignerFence( + decodeActive(activeGeneration, activeKid), + decodeActive(publishedGeneration, publishedKid)); + return new ReadinessProbePlan( + row.get("rotation_operation_id", UUID.class), + new Binding( + row.get("environment_id", String.class), + row.get("cluster_id", String.class), + row.get("kubernetes_namespace", String.class), + AccountJwtSignerDesiredStateRepository.CustodyMode + .INTERIM_ACCOUNT_ONLY_MOUNTED_FALLBACK), + new TrustFence( + row.get("expected_cluster_incarnation_uid", UUID.class).toString(), + row.get("expected_namespace_uid", UUID.class).toString(), + row.get("trust_binding_digest", String.class), + row.get("trust_config_revision", String.class)), + row.get("operation_digest", String.class), + row.get("generation_request_digest", String.class), + row.get("generation_receipt_digest", String.class), + row.get("desired_state_version", Long.class), + String.valueOf(row.get("target_generation", Long.class)), + row.get("target_kid", String.class), + row.get("target_public_key_fingerprint", String.class), + fence, + row.get("publication_intent_digest", String.class), + row.get("publication_receipt_digest", String.class), + row.get("mounted_observation_digest", String.class), + row.get("applicability_matrix_json", String.class), + row.get("applicability_matrix_digest", String.class), + row.get("validator_inventory_complete", Boolean.class), + row.get("maximum_cache_age_seconds", Short.class).intValue(), + row.get("planned_at_epoch_seconds", Long.class), + row.get("not_before_epoch_seconds", Long.class), + row.get("expires_at_epoch_seconds", Long.class), + row.get("plan_version", Short.class).intValue(), + row.get("plan_digest", String.class), + entries, + Optional.ofNullable(row.get("inventory_snapshot_digest", String.class))); + } + + private static Optional decodeActive(Long generation, String kid) { + if (generation == null && kid == null) { + return Optional.empty(); + } + if (generation == null || kid == null) { + throw new QuarantinedStateException("Readiness signer fence has a partial active pair"); + } + return Optional.of(new ActiveSigner(generation.toString(), kid)); + } + + private void requirePlanMatchesCurrent(ReadinessProbePlan plan, CurrentEvidence current) { + GenerationRequest request = current.request(); + GenerationResult result = current.result(); + AccountJwtJwksPublicationRepository.PublicationEvidence publication = current.publication(); + AccountJwtJwksPublicationRepository.PrepublicationIntent intent = publication.intent(); + AccountJwtJwksPublicationRepository.PublicationReceipt receipt = + publication.receipt().orElseThrow(); + AccountJwtJwksPublicationRepository.MountObservation mount = + publication.mountedCorrespondence().orElseThrow(); + if (!plan.operationId().equals(request.operationId()) + || !plan.binding().equals(request.binding()) + || !plan.trustFence().equals(request.trustFence()) + || !plan.operationDigest().equals(request.operationDigest()) + || !plan.generationRequestDigest().equals(result.generationRequestDigest()) + || !plan.generationReceiptDigest().equals(result.receiptDigest()) + || plan.desiredStateVersion() != result.desiredStateVersion() + || !plan.targetGeneration().equals(result.targetGeneration()) + || !plan.targetKid().equals(result.targetKid()) + || !plan.targetPublicKeyFingerprint().equals(result.publicKeyFingerprint()) + || !plan.expectedFence().durableActive().equals(request.expectedActive()) + || !plan.expectedFence().publishedActive().equals(request.expectedPublishedActive()) + || !plan.publicationIntentDigest().equals(intent.intentDigest()) + || !plan.publicationReceiptDigest().equals(receipt.receiptDigest()) + || !plan.mountedObservationDigest().equals(mount.observationDigest()) + || (plan.planVersion() == 1 + && !plan.applicabilityMatrixJson().equals(applicabilityMatrixJson())) + || !plan.applicabilityMatrixDigest() + .equals(sha256(plan.applicabilityMatrixJson().getBytes(StandardCharsets.UTF_8))) + || (plan.planVersion() == 1 && plan.validatorInventoryComplete()) + || (plan.planVersion() == INVENTORY_PLAN_VERSION && !matchesStoredV2Inventory(plan)) + || !plan.planDigest().equals(planDigest(plan))) { + throw new StaleOperationException( + "Readiness probe plan no longer matches current Account evidence"); + } + } + + private static AccountJwtJwksPublicationRepository.PromotionPublicationEvidence + promotionPublicationEvidence( + AccountJwtJwksPublicationRepository.PublicationEvidence publication) { + return new AccountJwtJwksPublicationRepository.PromotionPublicationEvidence( + publication.intent(), + publication.receipt().orElseThrow(() -> new MissingPublicationEvidenceException()), + publication + .mountedCorrespondence() + .orElseThrow(() -> new MissingPublicationEvidenceException())); + } + + private boolean matchesStoredV2Inventory(ReadinessProbePlan plan) { + String inventoryDigest = plan.inventorySnapshotDigest().orElse(null); + if (inventoryDigest == null) { + return false; + } + AccountJwtValidatorInventoryRepository.StoredSnapshot snapshot = + inventoryRepository.readRequired(inventoryDigest, plan.binding(), plan.trustFence()); + try { + JsonNode matrix = JSON.readTree(plan.applicabilityMatrixJson()); + JsonNode source = matrix == null ? null : matrix.get("source"); + if (matrix == null + || !matrix.isObject() + || !"2".equals(matrix.path("schemaVersion").asText()) + || !inventoryDigest.equals(matrix.path("inventorySnapshotDigest").asText()) + || source == null + || !snapshot.apiBindingRevision().equals(source.path("apiBindingRevision").asText()) + || !snapshot.apiBindingDigest().equals(source.path("apiBindingDigest").asText()) + || !snapshot + .inventoryBindingRevision() + .equals(source.path("inventoryBindingRevision").asText()) + || !snapshot + .inventoryBindingDigest() + .equals(source.path("inventoryBindingDigest").asText()) + || !snapshot.clusterIncarnationUid().equals(source.path("clusterIncarnationUid").asText()) + || !snapshot.namespace().equals(source.path("namespace").asText()) + || !snapshot.namespaceUid().equals(source.path("namespaceUid").asText()) + || !snapshot.environmentId().equals(source.path("environmentId").asText()) + || !snapshot.clusterId().equals(source.path("clusterId").asText())) { + return false; + } + JsonNode validators = matrix.get("validators"); + if (validators == null + || !validators.isArray() + || validators.isEmpty() + || validators.size() > 32) { + return false; + } + if (!plan.validatorInventoryComplete()) { + return "PARTIAL_UNCONFIRMED".equals(matrix.path("inventoryStatus").asText()); + } + if (!"PROTECTED_LIVE_COMPLETE".equals(matrix.path("inventoryStatus").asText()) + || validators.size() != 2) { + return false; + } + JsonNode accountProfiles = null; + JsonNode gameSessionProfiles = null; + for (JsonNode validator : validators) { + String validatorId = validator.path("validatorId").asText(); + if (VALIDATOR_ID.equals(validatorId)) { + accountProfiles = validator.get("applicableProfiles"); + } else if ("game-session-service".equals(validatorId)) { + gameSessionProfiles = validator.get("applicableProfiles"); + } else { + return false; + } + } + return hasExactProfiles(accountProfiles, PRODUCTION_PROFILE_CASES) + && hasExactProfiles( + gameSessionProfiles, + List.of(new ProfileCase(REPRESENTATIVE_PROFILE, REPRESENTATIVE_AUDIENCE))); + } catch (Exception failure) { + throw new QuarantinedStateException("V2 readiness inventory matrix cannot be read back"); + } + } + + private static boolean hasExactProfiles(JsonNode node, List expected) { + if (node == null || !node.isArray() || node.size() != expected.size()) { + return false; + } + Set actual = new java.util.HashSet<>(); + for (JsonNode profile : node) { + actual.add( + new ProfileCase( + profile.path("tokenProfile").asText(), profile.path("audience").asText())); + } + return actual.equals(Set.copyOf(expected)); + } + + private static void requirePreparedPlanMatches( + ReadinessProbePlan plan, + GenerationResult generation, + AccountJwtSignerDesiredStateRepository.PromotionOperationEvidence promotion, + AccountJwtJwksPublicationRepository.PromotionPublicationEvidence publication) { + AccountJwtJwksPublicationRepository.PrepublicationIntent intent = publication.intent(); + AccountJwtJwksPublicationRepository.PublicationReceipt receipt = publication.receipt(); + AccountJwtJwksPublicationRepository.MountObservation mount = + publication.mountedCorrespondence(); + if (!plan.operationId().equals(generation.operationId()) + || !plan.binding().equals(generation.binding()) + || !plan.trustFence().equals(generation.trustFence()) + || !plan.operationDigest().equals(generation.operationDigest()) + || !plan.generationRequestDigest().equals(generation.generationRequestDigest()) + || !plan.generationReceiptDigest().equals(generation.receiptDigest()) + || plan.desiredStateVersion() != generation.desiredStateVersion() + || !plan.targetGeneration().equals(generation.targetGeneration()) + || !plan.targetKid().equals(generation.targetKid()) + || !plan.targetPublicKeyFingerprint().equals(generation.publicKeyFingerprint()) + || !plan.expectedFence().durableActive().equals(promotion.expectedPreviousActive()) + || !plan.expectedFence().publishedActive().equals(promotion.expectedPublishedActive()) + || !plan.publicationIntentDigest().equals(intent.intentDigest()) + || !plan.publicationReceiptDigest().equals(receipt.receiptDigest()) + || !plan.mountedObservationDigest().equals(mount.observationDigest()) + || !plan.planDigest().equals(promotion.readinessPlanDigest()) + || !intent.operationId().equals(generation.operationId()) + || !receipt.operationId().equals(generation.operationId()) + || !mount.operationId().equals(generation.operationId()) + || !promotion.prepublicationIntentDigest().equals(intent.intentDigest()) + || !promotion.prepublicationReceiptDigest().equals(receipt.receiptDigest()) + || !promotion.mountedObservationDigest().equals(mount.observationDigest()) + || !promotion.publicConfigMapUid().equals(intent.configMapUid()) + || !promotion.expectedPublicResourceVersion().equals(receipt.observedResourceVersion()) + || !promotion.expectedPublicJwksJson().equals(intent.jwksJson()) + || !promotion.apiBindingDigest().equals(intent.apiBindingDigest()) + || !promotion.apiConfigRevision().equals(intent.apiConfigRevision()) + || !plan.planDigest().equals(planDigest(plan))) { + throw new QuarantinedStateException( + "Prepared readiness evidence differs from exact Account generation/publication owner records"); + } + } + + private CurrentEvidence lockCurrentEvidence(Binding binding, TrustFence trust) { + Objects.requireNonNull(binding, "Account signer binding is required"); + Objects.requireNonNull(trust, "Current signer trust fence is required"); + GenerationRequest request = desiredStateRepository.readCurrentGenerationRequest(binding, trust); + GenerationResult result = desiredStateRepository.readCurrentGenerationResult(binding, trust); + DesiredState state = desiredStateRepository.read(binding); + AccountJwtJwksPublicationRepository.PublicationEvidence publication = + publicationRepository + .readCurrentPublication(binding, trust) + .orElseThrow(() -> new MissingPublicationEvidenceException()); + if (request.phase() != GenerationPhase.GENERATION_RECORDED + || state.preparedOperationId().isPresent() + || !state.generationOperationId().equals(Optional.of(request.operationId())) + || !request.operationId().equals(result.operationId()) + || !request.binding().equals(binding) + || !result.binding().equals(binding) + || !request.trustFence().equals(trust) + || !result.trustFence().equals(trust) + || state.recordVersion() != result.desiredStateVersion() + || !request.targetGeneration().equals(result.targetGeneration()) + || !request.targetKid().equals(result.targetKid()) + || !request.expectedActive().equals(state.durableActive()) + || !request.expectedPublishedActive().equals(state.publishedActive()) + || !state.durableActive().equals(state.publishedActive())) { + throw new StaleOperationException( + "Current Account JWT signer evidence is incomplete or changed"); + } + AccountJwtJwksPublicationRepository.PrepublicationIntent intent = publication.intent(); + AccountJwtJwksPublicationRepository.PublicationReceipt receipt = + publication.receipt().orElseThrow(() -> new MissingPublicationEvidenceException()); + AccountJwtJwksPublicationRepository.MountObservation mount = + publication + .mountedCorrespondence() + .orElseThrow(() -> new MissingPublicationEvidenceException()); + if (!intent.operationId().equals(result.operationId()) + || !intent.operationDigest().equals(result.operationDigest()) + || !intent.generationRequestDigest().equals(result.generationRequestDigest()) + || !intent.generationReceiptDigest().equals(result.receiptDigest()) + || !intent.targetGeneration().equals(result.targetGeneration()) + || !intent.targetKid().equals(result.targetKid()) + || !intent.publicKeyFingerprint().equals(result.publicKeyFingerprint()) + || !receipt.operationId().equals(result.operationId()) + || !receipt.intentDigest().equals(intent.intentDigest()) + || !mount.operationId().equals(result.operationId()) + || !mount.intentDigest().equals(intent.intentDigest()) + || !mount.publicationReceiptDigest().equals(receipt.receiptDigest()) + || !mount.publicKeyFingerprint().equals(result.publicKeyFingerprint())) { + throw new StaleOperationException( + "Account JWT publication evidence is not exact for readiness"); + } + return new CurrentEvidence(state, request, result, publication); + } + + private ReadinessProbePlan requireStoredPlan(CurrentEvidence current) { + ReadinessProbePlan plan = selectPlan(current.request().operationId(), true); + if (plan == null) { + throw new MissingPlanException("Account JWT readiness probe plan is missing"); + } + requirePlanMatchesCurrent(plan, current); + return readbackPlan(plan, true); + } + + private static void requireCurrentOperation(CurrentEvidence current, String operationId) { + if (!current.request().operationId().toString().equals(operationId)) { + throw new StaleOperationException("Readiness probe belongs to a stale Account operation"); + } + } + + private static void requireSignedResultMatches( + ReadinessProbePlan plan, ProbeEntry entry, SignedProbeDigest signed) { + if (entry == null + || !signed.operationId().equals(plan.operationId().toString()) + || !signed.validatorId().equals(entry.validatorId()) + || signed.probeKind() != entry.probeKind() + || !signed.tokenProfile().equals(entry.tokenProfile()) + || !signed.audience().equals(entry.audience()) + || !signed.jti().equals(entry.jti()) + || !signed.targetGeneration().equals(entry.targetGeneration()) + || !signed.targetKid().equals(entry.targetKid()) + || !signed.publicKeyFingerprint().equals(plan.targetPublicKeyFingerprint()) + || signed.issuedAtEpochSecond() != entry.plannedIssuedAtEpochSecond() + || signed.expiresAtEpochSecond() != entry.expiresAtEpochSecond() + || !SHA256.matcher(signed.compactTokenSha256()).matches()) { + throw new IdempotencyConflictException( + "Mounted readiness signature does not match its exact plan"); + } + } + + private static VerificationReceipt verificationReceipt( + ReadinessProbePlan plan, + ProbeEntry entry, + VerifiedProbeObservation observation, + long resultEntryVersion) { + Map fields = new LinkedHashMap<>(); + fields.put("receiptVersion", 1); + fields.put("rotationOperationId", plan.operationId().toString()); + fields.put("planDigest", plan.planDigest()); + fields.put("operationDigest", plan.operationDigest()); + fields.put("generationRequestDigest", plan.generationRequestDigest()); + fields.put("generationReceiptDigest", plan.generationReceiptDigest()); + fields.put("desiredStateVersion", plan.desiredStateVersion()); + fields.put("environmentId", plan.binding().environmentId()); + fields.put("clusterId", plan.binding().clusterId()); + fields.put("namespace", plan.binding().namespace()); + fields.put( + "trustFence", + Map.of( + "clusterIncarnationUid", plan.trustFence().expectedClusterIncarnationUid(), + "namespaceUid", plan.trustFence().expectedNamespaceUid(), + "bindingDigest", plan.trustFence().bindingDigest(), + "configRevision", plan.trustFence().configRevision())); + fields.put("targetGeneration", entry.targetGeneration()); + fields.put("targetKid", entry.targetKid()); + fields.put("targetPublicKeyFingerprint", plan.targetPublicKeyFingerprint()); + fields.put("expectedActive", activeMap(plan.expectedFence().durableActive())); + fields.put("expectedPublishedActive", activeMap(plan.expectedFence().publishedActive())); + fields.put("validatorId", entry.validatorId()); + fields.put("tokenProfile", entry.tokenProfile()); + fields.put("audience", entry.audience()); + fields.put("probeKind", entry.probeKind().name()); + fields.put("jti", entry.jti().toString()); + fields.put("registryVersion", entry.registryVersion()); + fields.put("sourceEntryVersion", entry.entryVersion()); + fields.put("resultEntryVersion", resultEntryVersion); + fields.put("issuedAtEpochSecond", entry.plannedIssuedAtEpochSecond()); + fields.put("expiresAtEpochSecond", entry.expiresAtEpochSecond()); + fields.put("compactTokenSha256", observation.compactTokenSha256()); + fields.put("verifiedKid", observation.verifiedKid()); + fields.put("validatorInstanceId", observation.validatorInstanceId()); + fields.put("validatorBindingDigest", observation.validatorBindingDigest()); + fields.put("validatorConfigRevision", observation.validatorConfigRevision()); + fields.put("validatorPeerUri", observation.validatorPeerUri()); + fields.put("validatorPeerSpkiSha256", observation.validatorPeerSpkiSha256()); + fields.put("observedAtEpochSecond", observation.observedAtEpochSecond()); + return new VerificationReceipt( + 1, + entry.entryVersion(), + resultEntryVersion, + observation.observedAtEpochSecond(), + digest(fields), + observation.verifiedKid(), + observation.validatorInstanceId(), + observation.validatorBindingDigest(), + observation.validatorConfigRevision(), + observation.validatorPeerUri(), + observation.validatorPeerSpkiSha256()); + } + + private static void requireMatchingObservation( + VerificationReceipt receipt, VerifiedProbeObservation observation) { + if (!receipt.verifiedKid().equals(observation.verifiedKid()) + || !receipt.validatorInstanceId().equals(observation.validatorInstanceId()) + || !receipt.validatorBindingDigest().equals(observation.validatorBindingDigest()) + || !receipt.validatorConfigRevision().equals(observation.validatorConfigRevision()) + || !receipt.validatorPeerUri().equals(observation.validatorPeerUri()) + || !receipt.validatorPeerSpkiSha256().equals(observation.validatorPeerSpkiSha256())) { + throw new IdempotencyConflictException( + "Readiness verification retry differs from its immutable authenticated receipt"); + } + } + + private void requireNotExpired(ProbeEntry entry, long nowEpoch) { + if (nowEpoch >= entry.expiresAtEpochSecond()) { + throw new ProbeExpiredException(); + } + } + + static String applicabilityMatrixJson() { + List> applicableProfiles = + List.of( + Map.of("audience", CONTROL_UI_AUDIENCE, "tokenProfile", CONTROL_UI_PROFILE), + Map.of( + "audience", PLAYER_BOOTSTRAP_AUDIENCE, + "tokenProfile", PLAYER_BOOTSTRAP_PROFILE), + Map.of("audience", REPRESENTATIVE_AUDIENCE, "tokenProfile", REPRESENTATIVE_PROFILE)); + Map validator = new LinkedHashMap<>(); + validator.put("applicableProfiles", applicableProfiles); + validator.put("validatorId", VALIDATOR_ID); + Map matrix = new LinkedHashMap<>(); + matrix.put("inventoryStatus", INVENTORY_STATUS); + matrix.put("schemaVersion", 1); + matrix.put("validators", List.of(validator)); + try { + return new String( + Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(matrix)), + StandardCharsets.UTF_8); + } catch (IOException ex) { + throw new StorageUnavailableException( + "Readiness applicability matrix cannot be canonicalized"); + } + } + + private static String applicabilityMatrixJson( + InventorySnapshot snapshot, boolean inventoryComplete) { + List> validators = + snapshot.validators().stream() + .sorted(java.util.Comparator.comparing(ValidatorObservation::validatorId)) + .map( + validator -> { + List> applicable = + validator.profiles().stream() + .map( + profile -> + Map.of( + "audience", profile.audience(), + "tokenProfile", profile.tokenProfile())) + .sorted( + java.util.Comparator.comparing( + (Map value) -> + value.get("tokenProfile").toString()) + .thenComparing(value -> value.get("audience").toString())) + .toList(); + List> inapplicable = + PRODUCTION_PROFILE_CASES.stream() + .filter( + profile -> + validator.profiles().stream() + .noneMatch( + actual -> + actual.tokenProfile().equals(profile.tokenProfile()) + && actual.audience().equals(profile.audience()))) + .map( + profile -> + Map.of( + "audience", profile.audience(), + "tokenProfile", profile.tokenProfile())) + .toList(); + Map value = new LinkedHashMap<>(); + value.put("applicableProfiles", applicable); + value.put("deploymentUid", validator.deploymentUid()); + value.put("image", validator.image()); + value.put("podCount", validator.pods().size()); + value.put( + "pods", + validator.pods().stream() + .sorted(java.util.Comparator.comparing(PodObservation::uid)) + .map( + pod -> + Map.of( + "podUid", pod.uid(), + "podIp", pod.podIp(), + "exactPodEndpoint", pod.endpoint().toString(), + "canonicalServiceUri", pod.receiverServiceUri(), + "leafSpkiSha256", pod.leafSpkiSha256(), + "image", pod.image(), + "verifierConfigSha256", pod.verifierConfigSha256())) + .toList()); + value.put("inapplicableProfiles", inapplicable); + value.put("validatorId", validator.validatorId()); + value.put("verifierConfigSha256", validator.verifierConfigSha256()); + return value; + }) + .toList(); + Map source = new LinkedHashMap<>(); + source.put("apiBindingDigest", snapshot.apiBindingDigest()); + source.put("apiBindingRevision", snapshot.apiBindingRevision()); + source.put("clusterIncarnationUid", snapshot.clusterIncarnationUid()); + source.put("environmentId", snapshot.environmentId()); + source.put("inventoryBindingDigest", snapshot.inventoryBindingDigest()); + source.put("inventoryBindingRevision", snapshot.inventoryBindingRevision()); + source.put("namespace", snapshot.namespace()); + source.put("namespaceUid", snapshot.namespaceUid()); + Map matrix = new LinkedHashMap<>(); + matrix.put("inventoryStatus", inventoryComplete ? "PROTECTED_LIVE_COMPLETE" : INVENTORY_STATUS); + matrix.put("inventorySnapshotDigest", snapshot.digest()); + matrix.put( + "productionProfiles", + PRODUCTION_PROFILE_CASES.stream() + .map( + profile -> + Map.of( + "audience", profile.audience(), + "tokenProfile", profile.tokenProfile())) + .toList()); + matrix.put("schemaVersion", INVENTORY_PLAN_VERSION); + matrix.put("source", source); + matrix.put("validators", validators); + try { + String canonical = + new String( + Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(matrix)), + StandardCharsets.UTF_8); + if (canonical.getBytes(StandardCharsets.UTF_8).length > 8192) { + throw new InventoryPlanConflictException(); + } + return canonical; + } catch (IOException ex) { + throw new StorageUnavailableException( + "Readiness inventory applicability matrix cannot be canonicalized"); + } + } + + private static boolean inventoryPlanComplete(InventorySnapshot snapshot) { + Map> actual = new LinkedHashMap<>(); + for (ValidatorObservation validator : snapshot.validators()) { + Set profiles = new java.util.HashSet<>(); + for (var profile : validator.profiles()) { + ProfileCase candidate = new ProfileCase(profile.tokenProfile(), profile.audience()); + if (!PRODUCTION_PROFILE_CASES.contains(candidate) || !profiles.add(candidate)) { + return false; + } + } + if (validator.pods().isEmpty() + || actual.putIfAbsent(validator.validatorId(), profiles) != null) { + return false; + } + } + Set accountProfiles = actual.get(VALIDATOR_ID); + Set gameSessionProfiles = actual.get("game-session-service"); + return actual.keySet().equals(Set.of(VALIDATOR_ID, "game-session-service")) + && accountProfiles != null + && accountProfiles.equals(Set.copyOf(PRODUCTION_PROFILE_CASES)) + && gameSessionProfiles != null + && gameSessionProfiles.equals( + Set.of(new ProfileCase(REPRESENTATIVE_PROFILE, REPRESENTATIVE_AUDIENCE))); + } + + private static List expectedPods( + ReadinessProbePlan plan, InventorySnapshot snapshot) { + List expected = new ArrayList<>(); + for (ProbeEntry entry : plan.entries()) { + ValidatorObservation validator = + snapshot.validators().stream() + .filter(value -> value.validatorId().equals(entry.validatorId())) + .findFirst() + .orElseThrow(InventoryPlanConflictException::new); + ProbeExpectation expectation = + entry.probeKind() == ProbeKind.CANARY + ? ProbeExpectation.ACCEPT + : validator.profiles().stream() + .anyMatch( + profile -> + profile.tokenProfile().equals(entry.tokenProfile()) + && profile.audience().equals(entry.audience())) + ? ProbeExpectation.ACCEPT + : ProbeExpectation.INAPPLICABLE_REJECT; + for (PodObservation pod : validator.pods()) { + PodTarget target = + new PodTarget( + snapshot.digest(), + snapshot.environmentId(), + snapshot.clusterId(), + snapshot.clusterIncarnationUid(), + snapshot.namespace(), + snapshot.namespaceUid(), + snapshot.apiBindingRevision(), + snapshot.apiBindingDigest(), + snapshot.inventoryBindingRevision(), + snapshot.inventoryBindingDigest(), + validator.validatorId(), + validator.deploymentUid(), + pod.uid(), + pod.podIp(), + pod.image(), + pod.verifierConfigSha256(), + plan.applicabilityMatrixDigest(), + expectation, + Optional.of(pod.endpoint()), + Optional.of(pod.receiverServiceUri()), + Optional.of(pod.leafSpkiSha256())); + expected.add( + new ExpectedPod( + plan.operationId(), + plan.planDigest(), + entry.validatorId(), + entry.tokenProfile(), + entry.audience(), + entry.probeKind(), + entry.jti(), + target)); + } + } + if (expected.isEmpty() || expected.size() > MAX_POD_RECEIPTS_PER_OPERATION) { + throw new InventoryPlanConflictException(); + } + return List.copyOf(expected); + } + + private static String planDigest( + CurrentEvidence current, + String matrixJson, + String matrixDigest, + int planVersion, + boolean validatorInventoryComplete, + long plannedAt, + long notBefore, + long expiresAt, + List entries, + Optional inventorySnapshotDigest) { + Map preimage = new LinkedHashMap<>(); + GenerationRequest request = current.request(); + GenerationResult result = current.result(); + AccountJwtJwksPublicationRepository.PublicationEvidence publication = current.publication(); + preimage.put("digestVersion", "account-jwt-readiness-probe-plan/v" + planVersion); + preimage.put("rotationOperationId", request.operationId().toString()); + preimage.put("environmentId", request.binding().environmentId()); + preimage.put("clusterId", request.binding().clusterId()); + preimage.put("namespace", request.binding().namespace()); + preimage.put("custodyMode", request.binding().mode().value()); + preimage.put("operationDigest", request.operationDigest()); + preimage.put("generationRequestDigest", result.generationRequestDigest()); + preimage.put("generationReceiptDigest", result.receiptDigest()); + preimage.put("desiredStateVersion", result.desiredStateVersion()); + preimage.put( + "trustFence", + Map.of( + "clusterIncarnationUid", request.trustFence().expectedClusterIncarnationUid(), + "namespaceUid", request.trustFence().expectedNamespaceUid(), + "bindingDigest", request.trustFence().bindingDigest(), + "configRevision", request.trustFence().configRevision())); + preimage.put("targetGeneration", result.targetGeneration()); + preimage.put("targetKid", result.targetKid()); + preimage.put("targetPublicKeyFingerprint", result.publicKeyFingerprint()); + preimage.put("expectedActive", activeMap(request.expectedActive())); + preimage.put("expectedPublishedActive", activeMap(request.expectedPublishedActive())); + preimage.put("publicationIntentDigest", publication.intent().intentDigest()); + preimage.put("publicationReceiptDigest", publication.receipt().orElseThrow().receiptDigest()); + preimage.put( + "mountedObservationDigest", + publication.mountedCorrespondence().orElseThrow().observationDigest()); + preimage.put("applicabilityMatrixJson", matrixJson); + preimage.put("applicabilityMatrixDigest", matrixDigest); + preimage.put("validatorInventoryComplete", validatorInventoryComplete); + if (planVersion != 1) { + preimage.put("planVersion", planVersion); + } + inventorySnapshotDigest.ifPresent(digest -> preimage.put("inventorySnapshotDigest", digest)); + preimage.put("maximumCacheAgeSeconds", MAX_VALIDATOR_CACHE_AGE_SECONDS); + preimage.put("plannedAtEpochSecond", plannedAt); + preimage.put("notBeforeEpochSecond", notBefore); + preimage.put("expiresAtEpochSecond", expiresAt); + preimage.put( + "entries", + entries.stream().map(AccountJwtReadinessProbeRepository::entryDigestMap).toList()); + return digest(preimage); + } + + private static String planDigest(ReadinessProbePlan plan) { + Map preimage = planDigestMap(plan); + return digest(preimage); + } + + private static Map planDigestMap(ReadinessProbePlan plan) { + Map preimage = new LinkedHashMap<>(); + preimage.put("digestVersion", "account-jwt-readiness-probe-plan/v" + plan.planVersion()); + preimage.put("rotationOperationId", plan.operationId().toString()); + preimage.put("environmentId", plan.binding().environmentId()); + preimage.put("clusterId", plan.binding().clusterId()); + preimage.put("namespace", plan.binding().namespace()); + preimage.put("custodyMode", plan.binding().mode().value()); + preimage.put("operationDigest", plan.operationDigest()); + preimage.put("generationRequestDigest", plan.generationRequestDigest()); + preimage.put("generationReceiptDigest", plan.generationReceiptDigest()); + preimage.put("desiredStateVersion", plan.desiredStateVersion()); + preimage.put( + "trustFence", + Map.of( + "clusterIncarnationUid", plan.trustFence().expectedClusterIncarnationUid(), + "namespaceUid", plan.trustFence().expectedNamespaceUid(), + "bindingDigest", plan.trustFence().bindingDigest(), + "configRevision", plan.trustFence().configRevision())); + preimage.put("targetGeneration", plan.targetGeneration()); + preimage.put("targetKid", plan.targetKid()); + preimage.put("targetPublicKeyFingerprint", plan.targetPublicKeyFingerprint()); + preimage.put("expectedActive", activeMap(plan.expectedFence().durableActive())); + preimage.put("expectedPublishedActive", activeMap(plan.expectedFence().publishedActive())); + preimage.put("publicationIntentDigest", plan.publicationIntentDigest()); + preimage.put("publicationReceiptDigest", plan.publicationReceiptDigest()); + preimage.put("mountedObservationDigest", plan.mountedObservationDigest()); + preimage.put("applicabilityMatrixJson", plan.applicabilityMatrixJson()); + preimage.put("applicabilityMatrixDigest", plan.applicabilityMatrixDigest()); + preimage.put("validatorInventoryComplete", plan.validatorInventoryComplete()); + if (plan.planVersion() != 1) { + preimage.put("planVersion", plan.planVersion()); + } + plan.inventorySnapshotDigest() + .ifPresent(digest -> preimage.put("inventorySnapshotDigest", digest)); + preimage.put("maximumCacheAgeSeconds", plan.maximumCacheAgeSeconds()); + preimage.put("plannedAtEpochSecond", plan.plannedAtEpochSecond()); + preimage.put("notBeforeEpochSecond", plan.notBeforeEpochSecond()); + preimage.put("expiresAtEpochSecond", plan.expiresAtEpochSecond()); + preimage.put( + "entries", + plan.entries().stream().map(AccountJwtReadinessProbeRepository::entryDigestMap).toList()); + return preimage; + } + + private static Map entryDigestMap(ProbeEntry entry) { + Map item = new LinkedHashMap<>(); + item.put("validatorId", entry.validatorId()); + item.put("tokenProfile", entry.tokenProfile()); + item.put("audience", entry.audience()); + item.put("probeKind", entry.probeKind().name()); + item.put("jti", entry.jti().toString()); + item.put("targetGeneration", entry.targetGeneration()); + item.put("targetKid", entry.targetKid()); + item.put("expectedActive", activeMap(entry.expectedActive())); + item.put("registryVersion", entry.registryVersion()); + item.put("entryVersion", 1); + item.put("plannedIssuedAtEpochSecond", entry.plannedIssuedAtEpochSecond()); + item.put("expiresAtEpochSecond", entry.expiresAtEpochSecond()); + return item; + } + + private static Map activeMap(Optional active) { + if (active.isEmpty()) { + return Map.of("present", false); + } + ActiveSigner signer = active.orElseThrow(); + return Map.of("present", true, "generation", signer.generation(), "kid", signer.kid()); + } + + private static String deliveryClaimDigest(DeliveryClaim claim) { + Map value = new LinkedHashMap<>(); + value.put("rotationOperationId", claim.rotationOperationId().toString()); + value.put("planDigest", claim.planDigest()); + value.put("expectedClusterUid", claim.expectedClusterUid()); + value.put("expectedNamespaceUid", claim.expectedNamespaceUid()); + value.put("materializerTrustBindingDigest", claim.materializerTrustBindingDigest()); + value.put("materializerTrustConfigRevision", claim.materializerTrustConfigRevision()); + value.put("targetGeneration", claim.targetGeneration()); + value.put("targetKid", claim.targetKid()); + value.put("expectedActive", activeMap(claim.expectedActive())); + value.put("readinessBindingDigest", claim.readinessBindingDigest()); + value.put("readinessConfigRevision", claim.readinessConfigRevision()); + value.put( + "readinessBindingValidUntilEpochSecond", claim.readinessBindingValidUntilEpochSecond()); + value.put("validatorId", claim.validatorId()); + value.put("validatorInstanceId", claim.validatorInstanceId()); + value.put("validatorPeerUri", claim.validatorPeerUri()); + value.put("validatorPeerSpkiSha256", claim.validatorPeerSpkiSha256()); + value.put("claimedAtEpochSecond", claim.claimedAtEpochSecond()); + value.put("expiresAtEpochSecond", claim.expiresAtEpochSecond()); + try { + return sha256(Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value))); + } catch (IOException failure) { + throw new StorageUnavailableException("Readiness delivery claim cannot be canonicalized"); + } + } + + private static String readinessPromotionDigest( + ReadinessProbePlan plan, + GenerationResult generation, + AccountJwtJwksPublicationRepository.PromotionPublicationEvidence publication, + String inventoryEvidenceReference, + String inventoryEvidenceDigest, + List verifiedProbes) { + Map preimage = new LinkedHashMap<>(); + preimage.put("digestVersion", "account-jwt-readiness-promotion-proof/v1"); + preimage.put("plan", planDigestMap(plan)); + preimage.put("planDigest", plan.planDigest()); + preimage.put("generation", generationEvidenceMap(generation)); + preimage.put("publication", promotionPublicationEvidenceMap(publication)); + preimage.put("inventoryEvidenceReference", inventoryEvidenceReference); + preimage.put("inventoryEvidenceDigest", inventoryEvidenceDigest); + preimage.put( + "verifiedProbes", + verifiedProbes.stream() + .map(AccountJwtReadinessProbeRepository::verifiedProbeEvidenceMap) + .toList()); + return digest(preimage); + } + + private static Map generationEvidenceMap(GenerationResult result) { + Map value = new LinkedHashMap<>(); + value.put("operationId", result.operationId().toString()); + value.put("environmentId", result.binding().environmentId()); + value.put("clusterId", result.binding().clusterId()); + value.put("namespace", result.binding().namespace()); + value.put("custodyMode", result.binding().mode().value()); + value.put("operationDigest", result.operationDigest()); + value.put("generationRequestDigest", result.generationRequestDigest()); + value.put("desiredStateVersion", result.desiredStateVersion()); + value.put("trustFence", trustFenceMap(result.trustFence())); + value.put("privateSecretName", result.privateSecretName()); + value.put("secretUid", result.secretUid()); + value.put("expectedPriorResourceVersion", result.expectedPriorResourceVersion()); + value.put("observedResourceVersion", result.observedResourceVersion()); + value.put("targetGeneration", result.targetGeneration()); + value.put("targetKid", result.targetKid()); + value.put("targetAlgorithm", result.targetAlgorithm()); + value.put("publicKeyFingerprint", result.publicKeyFingerprint()); + value.put("publicJwkJson", result.publicJwkJson()); + value.put("receiptDigest", result.receiptDigest()); + return value; + } + + private static Map trustFenceMap(TrustFence trust) { + return Map.of( + "clusterIncarnationUid", trust.expectedClusterIncarnationUid(), + "namespaceUid", trust.expectedNamespaceUid(), + "bindingDigest", trust.bindingDigest(), + "configRevision", trust.configRevision()); + } + + private static Map promotionPublicationEvidenceMap( + AccountJwtJwksPublicationRepository.PromotionPublicationEvidence evidence) { + var intent = evidence.intent(); + var receipt = evidence.receipt(); + var mount = evidence.mountedCorrespondence(); + Map intentValue = new LinkedHashMap<>(); + intentValue.put("operationId", intent.operationId().toString()); + intentValue.put("environmentId", intent.binding().environmentId()); + intentValue.put("clusterId", intent.binding().clusterId()); + intentValue.put("namespace", intent.binding().namespace()); + intentValue.put("operationDigest", intent.operationDigest()); + intentValue.put("generationRequestDigest", intent.generationRequestDigest()); + intentValue.put("generationReceiptDigest", intent.generationReceiptDigest()); + intentValue.put("desiredStateVersion", intent.desiredStateVersion()); + intentValue.put("trustFence", trustFenceMap(intent.trustFence())); + intentValue.put("apiBindingDigest", intent.apiBindingDigest()); + intentValue.put("apiConfigRevision", intent.apiConfigRevision()); + intentValue.put("configMapName", intent.configMapName()); + intentValue.put("configMapUid", intent.configMapUid()); + intentValue.put("expectedResourceVersion", intent.expectedResourceVersion()); + intentValue.put("expectedSnapshotDigest", intent.expectedSnapshotDigest()); + intentValue.put("targetGeneration", intent.targetGeneration()); + intentValue.put("targetKid", intent.targetKid()); + intentValue.put("publicKeyFingerprint", intent.publicKeyFingerprint()); + intentValue.put("expectedDurableActive", activeMap(intent.expectedDurableActive())); + intentValue.put("expectedPublishedActive", activeMap(intent.expectedPublishedActive())); + intentValue.put("publicDataDigest", intent.publicDataDigest()); + intentValue.put("generationMarkerDigest", intent.generationMarkerDigest()); + intentValue.put("intentDigest", intent.intentDigest()); + + Map receiptValue = new LinkedHashMap<>(); + receiptValue.put("operationId", receipt.operationId().toString()); + receiptValue.put("intentDigest", receipt.intentDigest()); + receiptValue.put("configMapUid", receipt.configMapUid()); + receiptValue.put("expectedResourceVersion", receipt.expectedResourceVersion()); + receiptValue.put("observedResourceVersion", receipt.observedResourceVersion()); + receiptValue.put("publicDataDigest", receipt.publicDataDigest()); + receiptValue.put("receiptDigest", receipt.receiptDigest()); + + Map mountValue = new LinkedHashMap<>(); + mountValue.put("operationId", mount.operationId().toString()); + mountValue.put("intentDigest", mount.intentDigest()); + mountValue.put("publicationReceiptDigest", mount.publicationReceiptDigest()); + mountValue.put("generationMarkerDigest", mount.generationMarkerDigest()); + mountValue.put("publicDataDigest", mount.publicDataDigest()); + mountValue.put("publicKeyFingerprint", mount.publicKeyFingerprint()); + mountValue.put("observationDigest", mount.observationDigest()); + return Map.of("intent", intentValue, "receipt", receiptValue, "mount", mountValue); + } + + private static Map verifiedProbeEvidenceMap(VerifiedProbeEvidence probe) { + VerificationReceipt receipt = probe.receipt(); + Map value = new LinkedHashMap<>(); + value.put("rotationOperationId", probe.rotationOperationId().toString()); + value.put("planDigest", probe.planDigest()); + value.put("validatorId", probe.validatorId()); + value.put("tokenProfile", probe.tokenProfile()); + value.put("audience", probe.audience()); + value.put("probeKind", probe.probeKind().name()); + value.put("jti", probe.jti().toString()); + value.put("targetGeneration", probe.targetGeneration()); + value.put("targetKid", probe.targetKid()); + value.put("expectedActive", activeMap(probe.expectedActive())); + value.put("registryVersion", probe.registryVersion()); + value.put("entryVersion", probe.entryVersion()); + value.put("plannedIssuedAtEpochSecond", probe.plannedIssuedAtEpochSecond()); + value.put("expiresAtEpochSecond", probe.expiresAtEpochSecond()); + value.put("compactTokenSha256", probe.compactTokenSha256()); + Map receiptValue = new LinkedHashMap<>(); + receiptValue.put("receiptVersion", receipt.receiptVersion()); + receiptValue.put("sourceEntryVersion", receipt.sourceEntryVersion()); + receiptValue.put("resultEntryVersion", receipt.resultEntryVersion()); + receiptValue.put("observedAtEpochSecond", receipt.observedAtEpochSecond()); + receiptValue.put("receiptSha256", receipt.receiptSha256()); + receiptValue.put("verifiedKid", receipt.verifiedKid()); + receiptValue.put("validatorInstanceId", receipt.validatorInstanceId()); + receiptValue.put("validatorBindingDigest", receipt.validatorBindingDigest()); + receiptValue.put("validatorConfigRevision", receipt.validatorConfigRevision()); + receiptValue.put("validatorPeerUri", receipt.validatorPeerUri()); + receiptValue.put("validatorPeerSpkiSha256", receipt.validatorPeerSpkiSha256()); + receiptValue.put("podReceiptCount", receipt.podReceiptCount()); + receiptValue.put("podReceiptClosureSha256", receipt.podReceiptClosureSha256()); + value.put("verificationReceipt", receiptValue); + return value; + } + + private static String digest(Map value) { + try { + return sha256(Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value))); + } catch (IOException ex) { + throw new StorageUnavailableException("Readiness evidence cannot be canonicalized"); + } + } + + private static String sha256(byte[] bytes) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException ex) { + throw new StorageUnavailableException("SHA-256 is unavailable"); + } + } + + private static long exactEpochSecond(Instant instant) { + Objects.requireNonNull(instant, "Readiness timestamp is required"); + if (instant.getNano() != 0 || instant.getEpochSecond() <= 0L) { + throw new IllegalArgumentException("Readiness time must be a positive exact epoch second"); + } + return instant.getEpochSecond(); + } + + private static long add(long value, long amount) { + try { + return Math.addExact(value, amount); + } catch (ArithmeticException ex) { + throw new IllegalArgumentException("Readiness timestamp overflow", ex); + } + } + + private static void requireOperationId(UUID operationId) { + if (operationId == null || operationId.version() != 4 || operationId.variant() != 2) { + throw new IllegalArgumentException("Account JWT readiness operation ID must be UUIDv4"); + } + } + + private static String requireCanonicalKubeUuid(String value, String label) { + try { + UUID parsed = UUID.fromString(value); + String canonical = parsed.toString(); + if (!canonical.equals(value) + || parsed.equals(new UUID(0L, 0L)) + || parsed.version() < 1 + || parsed.version() > 8 + || parsed.variant() != 2) { + throw new IllegalArgumentException(); + } + return canonical; + } catch (RuntimeException invalid) { + throw new QuarantinedStateException(label + " is malformed"); + } + } + + private static void requireAccountTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException("An owning Account transaction is required"); + } + } + + private static void requireWritableAccountTransaction() { + requireAccountTransaction(); + if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException("A writable Account transaction is required"); + } + } + + private static void insertOne(DSLContext dsl, String table, Map fields) { + String columns = String.join(", ", fields.keySet()); + String placeholders = String.join(", ", java.util.Collections.nCopies(fields.size(), "?")); + dsl.execute( + "INSERT INTO " + table + " (" + columns + ") VALUES (" + placeholders + ")", + fields.values().toArray()); + } + + private record CurrentEvidence( + DesiredState state, + GenerationRequest request, + GenerationResult result, + AccountJwtJwksPublicationRepository.PublicationEvidence publication) {} + + private record ProfileCase(String tokenProfile, String audience) {} + + /** Exact immutable per-Pod requirement for one logical registry entry. */ + public record ExpectedPod( + UUID rotationOperationId, + String planDigest, + String validatorId, + String tokenProfile, + String audience, + ProbeKind probeKind, + UUID jti, + PodTarget target) { + public ExpectedPod { + requireOperationId(rotationOperationId); + requireDigest(planDigest, "expected Pod plan digest"); + requireValidatorId(validatorId); + requireProfile(tokenProfile); + requireAudience(audience); + Objects.requireNonNull(probeKind); + Objects.requireNonNull(jti); + Objects.requireNonNull(target); + if (jti.version() != 4 || jti.variant() != 2 || !validatorId.equals(target.validatorId())) { + throw new QuarantinedStateException("Expected readiness Pod binding is malformed"); + } + } + } + + /** Owner-derived current plan, ISSUED entry, and exact expected Pod; contains no JWT. */ + public record OwnerProbeEvidence( + ReadinessProbePlan plan, ProbeEntry entry, ExpectedPod expectedPod) { + public OwnerProbeEvidence { + Objects.requireNonNull(plan); + Objects.requireNonNull(entry); + Objects.requireNonNull(expectedPod); + if (plan.planVersion() != INVENTORY_PLAN_VERSION + || !plan.validatorInventoryComplete() + || entry.state() != ProbeState.ISSUED + || !plan.operationId().equals(entry.rotationOperationId()) + || !plan.planDigest().equals(entry.planDigest()) + || !entry.rotationOperationId().equals(expectedPod.rotationOperationId()) + || !entry.planDigest().equals(expectedPod.planDigest()) + || !entry.jti().equals(expectedPod.jti())) { + throw new ReceiverUnavailableException(); + } + } + } + + /** Immutable digest-covered one-Pod verifier receipt; no token or private key material. */ + private record PodReceipt( + UUID rotationOperationId, + String planDigest, + String validatorId, + String tokenProfile, + String audience, + ProbeKind probeKind, + String podUid, + UUID jti, + long sourceEntryVersion, + String compactTokenSha256, + String targetGeneration, + String targetKid, + Optional expectedActive, + ProbeExpectation outcome, + String observedPodUid, + String image, + String verifierConfigSha256, + String verifiedKid, + URI receiverEndpoint, + String receiverServiceUri, + String receiverPeerSpkiSha256, + long observedAtEpochSecond, + String receiptSha256) { + private PodReceipt { + requireOperationId(rotationOperationId); + requireDigest(planDigest, "per-Pod readiness plan digest"); + requireValidatorId(validatorId); + requireProfile(tokenProfile); + requireAudience(audience); + Objects.requireNonNull(probeKind); + requireCanonicalKubeUuid(podUid, "per-Pod readiness target UID"); + Objects.requireNonNull(jti); + if (jti.version() != 4 || jti.variant() != 2 || sourceEntryVersion <= 0L) { + throw new QuarantinedStateException("Per-Pod readiness receipt identity is malformed"); + } + requireDigest(compactTokenSha256, "per-Pod readiness token digest"); + requireGeneration(targetGeneration); + requireKid(targetKid); + expectedActive = Objects.requireNonNull(expectedActive); + Objects.requireNonNull(outcome); + requireCanonicalKubeUuid(observedPodUid, "observed readiness Pod UID"); + if (image == null || !image.matches("[^\\s@]+@sha256:[0-9a-f]{64}")) { + throw new QuarantinedStateException("Per-Pod verifier image is not pinned"); + } + requireDigest(verifierConfigSha256, "per-Pod verifier config digest"); + if (verifiedKid == null || !verifiedKid.equals(targetKid)) { + throw new QuarantinedStateException("Per-Pod verifier outcome does not match its key ID"); + } + Objects.requireNonNull(receiverEndpoint); + requireDigest(receiverPeerSpkiSha256, "per-Pod receiver SPKI digest"); + if (receiverServiceUri == null + || !receiverServiceUri.matches( + "spiffe://firemud/ns/[a-z0-9-]{1,63}/sa/[a-z0-9][a-z0-9-]{0,62}") + || observedAtEpochSecond <= 0L) { + throw new QuarantinedStateException("Per-Pod receiver identity is malformed"); + } + requireDigest(receiptSha256, "per-Pod readiness receipt digest"); + } + } + + public enum ProbeState { + PLANNED, + ISSUED, + VERIFIED, + CLEANED, + EXPIRED, + ABORTED + } + + public record SignerFence( + Optional durableActive, Optional publishedActive) { + public SignerFence { + durableActive = Objects.requireNonNull(durableActive); + publishedActive = Objects.requireNonNull(publishedActive); + if (!durableActive.equals(publishedActive)) { + throw new QuarantinedStateException("Durable and published signer fences disagree"); + } + } + } + + public record ProbeEntry( + UUID rotationOperationId, + String planDigest, + String validatorId, + String tokenProfile, + String audience, + ProbeKind probeKind, + UUID jti, + String targetGeneration, + String targetKid, + Optional expectedActive, + int registryVersion, + long entryVersion, + long plannedIssuedAtEpochSecond, + long expiresAtEpochSecond, + ProbeState state, + Optional terminalOutcome, + Optional signingAttemptedAtEpochSecond, + Optional compactTokenSha256, + Optional verificationReceipt) { + public ProbeEntry { + Objects.requireNonNull(rotationOperationId); + requireDigest(planDigest, "probe plan digest"); + Objects.requireNonNull(probeKind); + Objects.requireNonNull(jti); + Objects.requireNonNull(expectedActive); + Objects.requireNonNull(state); + terminalOutcome = Objects.requireNonNull(terminalOutcome); + signingAttemptedAtEpochSecond = Objects.requireNonNull(signingAttemptedAtEpochSecond); + compactTokenSha256 = Objects.requireNonNull(compactTokenSha256); + verificationReceipt = Objects.requireNonNull(verificationReceipt); + requireValidatorId(validatorId); + requireProfile(tokenProfile); + requireAudience(audience); + requireGeneration(targetGeneration); + requireKid(targetKid); + if (jti.version() != 4 + || jti.variant() != 2 + || registryVersion != 1 + || entryVersion <= 0L + || plannedIssuedAtEpochSecond <= 0L + || expiresAtEpochSecond <= plannedIssuedAtEpochSecond + || expiresAtEpochSecond - plannedIssuedAtEpochSecond > PROBE_LIFETIME_SECONDS) { + throw new QuarantinedStateException("Readiness probe entry identity is malformed"); + } + compactTokenSha256.ifPresent(value -> requireDigest(value, "compact probe hash")); + if (compactTokenSha256.isPresent() != signingAttemptedAtEpochSecond.isPresent()) { + throw new QuarantinedStateException("Readiness signing-attempt evidence is partial"); + } + signingAttemptedAtEpochSecond.ifPresent( + attemptedAt -> { + if (attemptedAt < plannedIssuedAtEpochSecond || attemptedAt >= expiresAtEpochSecond) { + throw new QuarantinedStateException( + "Readiness signing-attempt time is outside its plan"); + } + }); + if ((state == ProbeState.ABORTED + || state == ProbeState.EXPIRED + || state == ProbeState.CLEANED) + != terminalOutcome.isPresent() + || (state == ProbeState.ABORTED && terminalOutcome.filter("ABORTED"::equals).isEmpty()) + || (state == ProbeState.EXPIRED && terminalOutcome.filter("EXPIRED"::equals).isEmpty()) + || (state == ProbeState.CLEANED + && terminalOutcome + .filter(value -> value.equals("ABORTED") || value.equals("EXPIRED")) + .isEmpty())) { + throw new QuarantinedStateException("Readiness terminal outcome does not match its state"); + } + if ((state == ProbeState.ISSUED || state == ProbeState.VERIFIED) + && compactTokenSha256.isEmpty()) { + throw new QuarantinedStateException("Issued readiness probe has no exact token hash"); + } + if ((state == ProbeState.VERIFIED && verificationReceipt.isEmpty()) + || ((state == ProbeState.PLANNED || state == ProbeState.ISSUED) + && verificationReceipt.isPresent())) { + throw new QuarantinedStateException("Readiness state and verification receipt disagree"); + } + verificationReceipt.ifPresent( + receipt -> { + if ((receipt.receiptVersion() == 1 && !receipt.verifiedKid().equals(targetKid)) + || (receipt.receiptVersion() == 2 + && receipt.verifiedKid() != null + && !receipt.verifiedKid().equals(targetKid)) + || receipt.resultEntryVersion() > entryVersion + || receipt.sourceEntryVersion() + 1L != receipt.resultEntryVersion() + || (state == ProbeState.VERIFIED && receipt.resultEntryVersion() != entryVersion)) { + throw new QuarantinedStateException( + "Readiness verification receipt differs from its immutable entry"); + } + }); + if (verificationReceipt.isPresent() + && verificationReceipt.orElseThrow().resultEntryVersion() > entryVersion) { + throw new QuarantinedStateException("Terminal readiness receipt version is invalid"); + } + if (state == ProbeState.CLEANED && terminalOutcome.isEmpty()) { + throw new QuarantinedStateException("Cleaned readiness probe lost its terminal evidence"); + } + } + + private ProbeEntry withPlanDigest(String value) { + return new ProbeEntry( + rotationOperationId, + value, + validatorId, + tokenProfile, + audience, + probeKind, + jti, + targetGeneration, + targetKid, + expectedActive, + registryVersion, + entryVersion, + plannedIssuedAtEpochSecond, + expiresAtEpochSecond, + state, + terminalOutcome, + signingAttemptedAtEpochSecond, + compactTokenSha256, + verificationReceipt); + } + } + + /** Exact authenticated transport and cryptographic verification evidence; contains no token. */ + public record VerifiedProbeObservation( + String compactTokenSha256, + String verifiedKid, + String validatorInstanceId, + String validatorBindingDigest, + String validatorConfigRevision, + String validatorPeerUri, + String validatorPeerSpkiSha256, + long observedAtEpochSecond) { + public VerifiedProbeObservation { + requireDigest(compactTokenSha256, "verified compact token hash"); + requireKid(verifiedKid); + if (validatorInstanceId == null + || !validatorInstanceId.matches("[A-Za-z0-9][A-Za-z0-9._:-]{0,127}") + || validatorConfigRevision == null + || !validatorConfigRevision.matches("[A-Za-z0-9][A-Za-z0-9._:-]{0,127}") + || validatorPeerUri == null + || !validatorPeerUri.matches( + "spiffe://firemud/ns/[a-z0-9-]{1,63}/sa/account-jwt-readiness-harness") + || observedAtEpochSecond <= 0L) { + throw new QuarantinedStateException("Readiness verification observation is malformed"); + } + requireDigest(validatorBindingDigest, "validator trust binding digest"); + requireDigest(validatorPeerSpkiSha256, "validator peer SPKI digest"); + } + } + + /** Immutable digest and identity fields read back from the readiness entry row. */ + public record VerificationReceipt( + int receiptVersion, + long sourceEntryVersion, + long resultEntryVersion, + long observedAtEpochSecond, + String receiptSha256, + String verifiedKid, + String validatorInstanceId, + String validatorBindingDigest, + String validatorConfigRevision, + String validatorPeerUri, + String validatorPeerSpkiSha256, + int podReceiptCount, + String podReceiptClosureSha256) { + public VerificationReceipt( + int receiptVersion, + long sourceEntryVersion, + long resultEntryVersion, + long observedAtEpochSecond, + String receiptSha256, + String verifiedKid, + String validatorInstanceId, + String validatorBindingDigest, + String validatorConfigRevision, + String validatorPeerUri, + String validatorPeerSpkiSha256) { + this( + receiptVersion, + sourceEntryVersion, + resultEntryVersion, + observedAtEpochSecond, + receiptSha256, + verifiedKid, + validatorInstanceId, + validatorBindingDigest, + validatorConfigRevision, + validatorPeerUri, + validatorPeerSpkiSha256, + 0, + null); + } + + public VerificationReceipt { + if ((receiptVersion != 1 && receiptVersion != 2) + || sourceEntryVersion <= 0L + || resultEntryVersion != sourceEntryVersion + 1L + || observedAtEpochSecond <= 0L) { + throw new QuarantinedStateException("Readiness verification receipt version is malformed"); + } + requireDigest(receiptSha256, "readiness verification receipt digest"); + if (receiptVersion == 1) { + requireKid(verifiedKid); + if (podReceiptCount != 0 || podReceiptClosureSha256 != null) { + throw new QuarantinedStateException("Legacy receipt cannot carry per-Pod closure fields"); + } + } else { + requireKid(verifiedKid); + if (podReceiptCount <= 0 || podReceiptCount > MAX_POD_RECEIPTS_PER_OPERATION) { + throw new QuarantinedStateException("Per-Pod receipt closure count is malformed"); + } + requireDigest(podReceiptClosureSha256, "per-Pod receipt closure digest"); + if (!receiptSha256.equals(podReceiptClosureSha256)) { + throw new QuarantinedStateException("Per-Pod closure and verification digests differ"); + } + } + if (validatorInstanceId == null + || !validatorInstanceId.matches("[A-Za-z0-9][A-Za-z0-9._:-]{0,127}") + || validatorConfigRevision == null + || !validatorConfigRevision.matches("[A-Za-z0-9][A-Za-z0-9._:-]{0,127}") + || validatorPeerUri == null + || !validatorPeerUri.matches( + "spiffe://firemud/ns/[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?/sa/[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?")) { + throw new QuarantinedStateException("Readiness verification receipt identity is malformed"); + } + requireDigest(validatorBindingDigest, "validator trust binding digest"); + requireDigest(validatorPeerSpkiSha256, "validator peer SPKI digest"); + } + } + + public record ReadinessProbePlan( + UUID operationId, + Binding binding, + TrustFence trustFence, + String operationDigest, + String generationRequestDigest, + String generationReceiptDigest, + long desiredStateVersion, + String targetGeneration, + String targetKid, + String targetPublicKeyFingerprint, + SignerFence expectedFence, + String publicationIntentDigest, + String publicationReceiptDigest, + String mountedObservationDigest, + String applicabilityMatrixJson, + String applicabilityMatrixDigest, + boolean validatorInventoryComplete, + int maximumCacheAgeSeconds, + long plannedAtEpochSecond, + long notBeforeEpochSecond, + long expiresAtEpochSecond, + int planVersion, + String planDigest, + List entries, + Optional inventorySnapshotDigest) { + public ReadinessProbePlan( + UUID operationId, + Binding binding, + TrustFence trustFence, + String operationDigest, + String generationRequestDigest, + String generationReceiptDigest, + long desiredStateVersion, + String targetGeneration, + String targetKid, + String targetPublicKeyFingerprint, + SignerFence expectedFence, + String publicationIntentDigest, + String publicationReceiptDigest, + String mountedObservationDigest, + String applicabilityMatrixJson, + String applicabilityMatrixDigest, + boolean validatorInventoryComplete, + int maximumCacheAgeSeconds, + long plannedAtEpochSecond, + long notBeforeEpochSecond, + long expiresAtEpochSecond, + int planVersion, + String planDigest, + List entries) { + this( + operationId, + binding, + trustFence, + operationDigest, + generationRequestDigest, + generationReceiptDigest, + desiredStateVersion, + targetGeneration, + targetKid, + targetPublicKeyFingerprint, + expectedFence, + publicationIntentDigest, + publicationReceiptDigest, + mountedObservationDigest, + applicabilityMatrixJson, + applicabilityMatrixDigest, + validatorInventoryComplete, + maximumCacheAgeSeconds, + plannedAtEpochSecond, + notBeforeEpochSecond, + expiresAtEpochSecond, + planVersion, + planDigest, + entries, + Optional.empty()); + } + + public ReadinessProbePlan { + requireOperationId(operationId); + Objects.requireNonNull(binding); + Objects.requireNonNull(trustFence); + Objects.requireNonNull(expectedFence); + requireDigest(operationDigest, "operation digest"); + requireDigest(generationRequestDigest, "generation request digest"); + requireDigest(generationReceiptDigest, "generation receipt digest"); + requireGeneration(targetGeneration); + requireKid(targetKid); + requireDigest(targetPublicKeyFingerprint, "target public key fingerprint"); + requireDigest(publicationIntentDigest, "publication intent digest"); + requireDigest(publicationReceiptDigest, "publication receipt digest"); + requireDigest(mountedObservationDigest, "mounted observation digest"); + Objects.requireNonNull(applicabilityMatrixJson); + requireDigest(applicabilityMatrixDigest, "applicability matrix digest"); + requireDigest(planDigest, "plan digest"); + Objects.requireNonNull(inventorySnapshotDigest); + inventorySnapshotDigest.ifPresent( + value -> requireDigest(value, "validator inventory snapshot digest")); + entries = List.copyOf(entries); + if (desiredStateVersion <= 1L + || maximumCacheAgeSeconds != MAX_VALIDATOR_CACHE_AGE_SECONDS + || plannedAtEpochSecond <= 0L + || notBeforeEpochSecond < plannedAtEpochSecond + maximumCacheAgeSeconds + || expiresAtEpochSecond <= notBeforeEpochSecond + || expiresAtEpochSecond - notBeforeEpochSecond > PROBE_LIFETIME_SECONDS + || (planVersion != 1 && planVersion != INVENTORY_PLAN_VERSION) + || (planVersion == INVENTORY_PLAN_VERSION && inventorySnapshotDigest.isEmpty()) + || entries.isEmpty() + || entries.size() > MAX_ENTRIES_PER_OPERATION) { + throw new QuarantinedStateException("Readiness probe plan is malformed"); + } + } + + private static ReadinessProbePlan fromCurrent( + CurrentEvidence current, + String matrixJson, + String matrixDigest, + boolean inventoryComplete, + int maxCacheAge, + long plannedAt, + long notBefore, + long expiresAt, + String planDigest, + List entries, + Optional inventorySnapshotDigest, + int planVersion) { + GenerationRequest request = current.request(); + GenerationResult result = current.result(); + var publication = current.publication(); + return new ReadinessProbePlan( + request.operationId(), + request.binding(), + request.trustFence(), + request.operationDigest(), + result.generationRequestDigest(), + result.receiptDigest(), + result.desiredStateVersion(), + result.targetGeneration(), + result.targetKid(), + result.publicKeyFingerprint(), + new SignerFence(request.expectedActive(), request.expectedPublishedActive()), + publication.intent().intentDigest(), + publication.receipt().orElseThrow().receiptDigest(), + publication.mountedCorrespondence().orElseThrow().observationDigest(), + matrixJson, + matrixDigest, + inventoryComplete, + maxCacheAge, + plannedAt, + notBefore, + expiresAt, + planVersion, + planDigest, + entries, + inventorySnapshotDigest); + } + } + + /** + * Owner-created, non-secret readiness evidence accepted by the Account promotion owner. Its + * constructor is private: callers cannot turn an applicability matrix or receipt DTO into proof. + */ + public static final class ReadinessPromotionProof { + private final ReadinessProbePlan plan; + private final GenerationResult generationResult; + private final AccountJwtJwksPublicationRepository.PromotionPublicationEvidence publication; + private final String inventoryEvidenceReference; + private final String inventoryEvidenceDigest; + private final List verifiedProbes; + private final String readinessEvidenceDigest; + + private ReadinessPromotionProof( + ReadinessProbePlan plan, + GenerationResult generationResult, + AccountJwtJwksPublicationRepository.PromotionPublicationEvidence publication, + String inventoryEvidenceReference, + String inventoryEvidenceDigest) { + this.plan = Objects.requireNonNull(plan); + this.generationResult = Objects.requireNonNull(generationResult); + this.publication = Objects.requireNonNull(publication); + if (!plan.validatorInventoryComplete()) { + throw new QuarantinedStateException( + "Partial readiness inventory cannot create promotion proof"); + } + if (inventoryEvidenceReference == null + || !inventoryEvidenceReference.matches("[A-Za-z0-9][A-Za-z0-9._:/-]{0,511}")) { + throw new QuarantinedStateException("Protected readiness inventory reference is malformed"); + } + requireDigest(inventoryEvidenceDigest, "protected readiness inventory digest"); + this.inventoryEvidenceReference = inventoryEvidenceReference; + this.inventoryEvidenceDigest = inventoryEvidenceDigest; + List verifiedProbes = + plan.entries().stream().map(VerifiedProbeEvidence::from).toList(); + if (verifiedProbes.isEmpty() + || verifiedProbes.size() > MAX_ENTRIES_PER_OPERATION + || plan.planVersion() != INVENTORY_PLAN_VERSION + || verifiedProbes.stream().anyMatch(probe -> probe.receipt().receiptVersion() != 2) + || !plan.operationId().equals(generationResult.operationId()) + || !plan.operationDigest().equals(generationResult.operationDigest()) + || !plan.generationRequestDigest().equals(generationResult.generationRequestDigest()) + || !plan.generationReceiptDigest().equals(generationResult.receiptDigest()) + || plan.desiredStateVersion() != generationResult.desiredStateVersion() + || !plan.targetGeneration().equals(generationResult.targetGeneration()) + || !plan.targetKid().equals(generationResult.targetKid()) + || !plan.targetPublicKeyFingerprint().equals(generationResult.publicKeyFingerprint()) + || !plan.planDigest().equals(planDigest(plan))) { + throw new QuarantinedStateException( + "Readiness proof differs from exact generation and verified probe evidence"); + } + this.verifiedProbes = List.copyOf(verifiedProbes); + this.readinessEvidenceDigest = + readinessPromotionDigest( + plan, + generationResult, + publication, + inventoryEvidenceReference, + inventoryEvidenceDigest, + this.verifiedProbes); + } + + public ReadinessProbePlan plan() { + return plan; + } + + public GenerationResult generationResult() { + return generationResult; + } + + public AccountJwtJwksPublicationRepository.PromotionPublicationEvidence publication() { + return publication; + } + + public String inventoryEvidenceReference() { + return inventoryEvidenceReference; + } + + public String inventoryEvidenceDigest() { + return inventoryEvidenceDigest; + } + + public List verifiedProbes() { + return verifiedProbes; + } + + /** Digest computed by Account over all canonical proof fields except this digest itself. */ + public String readinessEvidenceDigest() { + return readinessEvidenceDigest; + } + } + + /** Ordered immutable row and authenticated receipt identity for one VERIFIED registry entry. */ + public record VerifiedProbeEvidence( + UUID rotationOperationId, + String planDigest, + String validatorId, + String tokenProfile, + String audience, + ProbeKind probeKind, + UUID jti, + String targetGeneration, + String targetKid, + Optional expectedActive, + int registryVersion, + long entryVersion, + long plannedIssuedAtEpochSecond, + long expiresAtEpochSecond, + String compactTokenSha256, + VerificationReceipt receipt) { + public VerifiedProbeEvidence { + Objects.requireNonNull(rotationOperationId); + requireDigest(planDigest, "verified probe plan digest"); + requireValidatorId(validatorId); + requireProfile(tokenProfile); + requireAudience(audience); + Objects.requireNonNull(probeKind); + Objects.requireNonNull(jti); + requireGeneration(targetGeneration); + requireKid(targetKid); + expectedActive = Objects.requireNonNull(expectedActive); + requireDigest(compactTokenSha256, "verified probe token digest"); + Objects.requireNonNull(receipt); + if (registryVersion != 1 + || entryVersion <= 0L + || plannedIssuedAtEpochSecond <= 0L + || expiresAtEpochSecond <= plannedIssuedAtEpochSecond + || (receipt.receiptVersion() == 1 && !targetKid.equals(receipt.verifiedKid())) + || (receipt.receiptVersion() == 2 + && receipt.verifiedKid() != null + && !targetKid.equals(receipt.verifiedKid())) + || receipt.resultEntryVersion() != entryVersion) { + throw new QuarantinedStateException( + "Verified probe evidence does not match its immutable receipt"); + } + } + + private static VerifiedProbeEvidence from(ProbeEntry entry) { + if (entry.state() != ProbeState.VERIFIED) { + throw new QuarantinedStateException( + "Every promotion readiness entry must be owner-recorded VERIFIED"); + } + return new VerifiedProbeEvidence( + entry.rotationOperationId(), + entry.planDigest(), + entry.validatorId(), + entry.tokenProfile(), + entry.audience(), + entry.probeKind(), + entry.jti(), + entry.targetGeneration(), + entry.targetKid(), + entry.expectedActive(), + entry.registryVersion(), + entry.entryVersion(), + entry.plannedIssuedAtEpochSecond(), + entry.expiresAtEpochSecond(), + entry.compactTokenSha256().orElseThrow(), + entry.verificationReceipt().orElseThrow()); + } + } + + /** Immutable winner of the only permitted transient delivery for a readiness operation. */ + public record DeliveryClaim( + UUID rotationOperationId, + String planDigest, + String expectedClusterUid, + String expectedNamespaceUid, + String materializerTrustBindingDigest, + String materializerTrustConfigRevision, + String targetGeneration, + String targetKid, + Optional expectedActive, + String readinessBindingDigest, + String readinessConfigRevision, + long readinessBindingValidUntilEpochSecond, + String validatorId, + String validatorInstanceId, + String validatorPeerUri, + String validatorPeerSpkiSha256, + long claimedAtEpochSecond, + long expiresAtEpochSecond, + String claimDigest) { + public DeliveryClaim { + requireOperationId(rotationOperationId); + requireDigest(planDigest, "delivery plan digest"); + requireUuid(expectedClusterUid, "delivery cluster UID"); + requireUuid(expectedNamespaceUid, "delivery namespace UID"); + requireDigest(materializerTrustBindingDigest, "materializer trust digest"); + requireRevision(materializerTrustConfigRevision, "materializer trust revision"); + requireGeneration(targetGeneration); + requireKid(targetKid); + expectedActive = Objects.requireNonNull(expectedActive); + expectedActive.ifPresent( + active -> { + requireGeneration(active.generation()); + requireKid(active.kid()); + if (Long.parseLong(targetGeneration) <= Long.parseLong(active.generation()) + || targetKid.equals(active.kid())) { + throw new QuarantinedStateException("Delivery active fence is not older than target"); + } + }); + requireDigest(readinessBindingDigest, "readiness trust digest"); + requireRevision(readinessConfigRevision, "readiness trust revision"); + if (readinessBindingValidUntilEpochSecond <= claimedAtEpochSecond) { + throw new QuarantinedStateException("Readiness binding expires before delivery claim"); + } + requireValidatorId(validatorId); + if (!VALIDATOR_ID.equals(validatorId) + || validatorInstanceId == null + || !validatorInstanceId.matches("[A-Za-z0-9][A-Za-z0-9._:-]{0,127}") + || validatorPeerUri == null + || !validatorPeerUri.matches( + "spiffe://firemud/ns/[a-z0-9-]{1,63}/sa/account-jwt-readiness-harness")) { + throw new QuarantinedStateException("Readiness delivery identity is malformed"); + } + requireDigest(validatorPeerSpkiSha256, "readiness peer SPKI digest"); + if (claimedAtEpochSecond <= 0L || expiresAtEpochSecond <= claimedAtEpochSecond) { + throw new QuarantinedStateException("Readiness delivery claim window is malformed"); + } + requireDigest(claimDigest, "readiness delivery claim digest"); + } + + private static DeliveryClaim create( + ReadinessProbePlan plan, + TrustFence trust, + net.firedevops.firemud.accountservice.config.AccountJwtReadinessTrustBinding.Binding + readinessBinding, + PeerIdentity peer, + long claimedAt) { + DeliveryClaim unsigned = + new DeliveryClaim( + plan.operationId(), + plan.planDigest(), + trust.expectedClusterIncarnationUid(), + trust.expectedNamespaceUid(), + trust.bindingDigest(), + trust.configRevision(), + plan.targetGeneration(), + plan.targetKid(), + plan.expectedFence().durableActive(), + readinessBinding.bindingDigest(), + readinessBinding.configRevision(), + readinessBinding.validUntilEpochSecond(), + readinessBinding.validatorId(), + readinessBinding.validatorInstanceId(), + peer.uri(), + peer.spkiSha256(), + claimedAt, + plan.expiresAtEpochSecond(), + "0".repeat(64)); + return new DeliveryClaim( + unsigned.rotationOperationId(), + unsigned.planDigest(), + unsigned.expectedClusterUid(), + unsigned.expectedNamespaceUid(), + unsigned.materializerTrustBindingDigest(), + unsigned.materializerTrustConfigRevision(), + unsigned.targetGeneration(), + unsigned.targetKid(), + unsigned.expectedActive(), + unsigned.readinessBindingDigest(), + unsigned.readinessConfigRevision(), + unsigned.readinessBindingValidUntilEpochSecond(), + unsigned.validatorId(), + unsigned.validatorInstanceId(), + unsigned.validatorPeerUri(), + unsigned.validatorPeerSpkiSha256(), + unsigned.claimedAtEpochSecond(), + unsigned.expiresAtEpochSecond(), + deliveryClaimDigest(unsigned)); + } + } + + private static String requireDigest(String value, String label) { + if (value == null || !SHA256.matcher(value).matches()) { + throw new QuarantinedStateException(label + " is malformed"); + } + return value; + } + + private static String requireUuid(String value, String label) { + try { + UUID parsed = UUID.fromString(value); + if (!parsed.toString().equals(value) + || parsed.version() != 4 + || parsed.variant() != 2 + || parsed.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException(); + } + return value; + } catch (RuntimeException invalid) { + throw new QuarantinedStateException(label + " is malformed"); + } + } + + private static String requireRevision(String value, String label) { + if (value == null || !value.matches("[A-Za-z0-9][A-Za-z0-9._:-]{0,127}")) { + throw new QuarantinedStateException(label + " is malformed"); + } + return value; + } + + private static String requireValidatorId(String value) { + if (value == null || !value.matches("[a-z0-9][a-z0-9-]{0,62}")) { + throw new QuarantinedStateException("Readiness validator ID is malformed"); + } + return value; + } + + private static String requireProfile(String value) { + if (value == null || !value.matches("[a-z0-9][a-z0-9-]{0,127}")) { + throw new QuarantinedStateException("Readiness token profile is malformed"); + } + return value; + } + + private static String requireAudience(String value) { + if (value == null || !value.matches("[A-Za-z0-9][A-Za-z0-9._:-]{0,127}")) { + throw new QuarantinedStateException("Readiness audience is malformed"); + } + return value; + } + + private static String requireGeneration(String value) { + if (value == null || !value.matches("[1-9][0-9]{0,63}")) { + throw new QuarantinedStateException("Readiness signer generation is malformed"); + } + return value; + } + + private static String requireKid(String value) { + if (value == null || !value.matches("[A-Za-z0-9_-]{1,64}")) { + throw new QuarantinedStateException("Readiness signer kid is malformed"); + } + return value; + } + + public static final class MissingPlanException extends IllegalStateException { + public MissingPlanException(String message) { + super(message); + } + } + + public static final class DeliveryAlreadyClaimedException extends IllegalStateException { + public DeliveryAlreadyClaimedException() { + super("Readiness probe delivery was already claimed"); + } + } + + public static final class DeliveryClaimRejectedException extends SecurityException { + public DeliveryClaimRejectedException() { + super("Authenticated readiness delivery caller is not bound to the current plan"); + } + } + + public static final class MissingPublicationEvidenceException extends IllegalStateException { + public MissingPublicationEvidenceException() { + super("Current JWKS publication evidence is incomplete"); + } + } + + public static final class InventoryPlanConflictException extends IllegalStateException { + public InventoryPlanConflictException() { + super("Account validator inventory snapshot does not match the immutable readiness plan"); + } + } + + public static final class StaleOperationException extends IllegalStateException { + public StaleOperationException(String message) { + super(message); + } + } + + public static final class CacheAgeNotElapsedException extends IllegalStateException { + public CacheAgeNotElapsedException() { + super("Validator maximum cache age has not elapsed"); + } + } + + public static final class ProbeExpiredException extends IllegalStateException { + public ProbeExpiredException() { + super("Readiness probe is expired"); + } + } + + public static final class AmbiguousDeliveryException extends IllegalStateException { + public AmbiguousDeliveryException(String message) { + super(message); + } + } + + public static final class VersionConflictException extends IllegalStateException { + public VersionConflictException(String message) { + super(message); + } + } + + public static final class IdempotencyConflictException extends IllegalStateException { + public IdempotencyConflictException(String message) { + super(message); + } + } + + public static final class QuarantinedStateException extends IllegalStateException { + public QuarantinedStateException(String message) { + super(message); + } + } + + public static final class StorageUnavailableException extends IllegalStateException { + public StorageUnavailableException(String message) { + super(message); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtSignerDesiredStateRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtSignerDesiredStateRepository.java new file mode 100644 index 0000000000..cc819f0e1d --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtSignerDesiredStateRepository.java @@ -0,0 +1,4178 @@ +package net.firedevops.firemud.accountservice.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.io.IOException; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +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.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository.ReadinessPromotionProof; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.Result; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; + +/** + * Account-owned persistence for the interim mounted JWT signer. + * + *

Account chooses and persists the operation, generation, and {@code kid}. The materializer can + * only observe the fixed Secret, then perform one pending-slot generation/CAS or an exact + * PREPARED-only slot promotion and return public-only results. Account remains the sole durable + * commit authority; public prepublication, cache convergence, validator probes, and correspondence + * evidence are separately owned prerequisites and are never inferred by this repository. + */ +@Repository +public class AccountJwtSignerDesiredStateRepository { + public static final String PRIVATE_SECRET_NAME = "jwt-signing-keys"; + public static final String PUBLIC_JWKS_CONFIG_MAP_NAME = "jwt-jwks"; + public static final String REQUEST_DIGEST_VERSION = "account-jwt-signer-generation-operation/v1"; + public static final String OBSERVATION_DIGEST_VERSION = + "account-jwt-signer-secret-observation/v1"; + public static final String GENERATION_REQUEST_DIGEST_VERSION = + "account-jwt-signer-generation-request/v1"; + public static final String RECEIPT_DIGEST_VERSION = "account-jwt-signer-generation-receipt/v1"; + private static final String PROMOTION_DIGEST_VERSION = + "account-jwt-signer-promotion-operation/v1"; + + private static final String STATE_TABLE = "account_jwt_signer_desired_states"; + private static final String OPERATION_TABLE = "account_jwt_signer_generation_operations"; + private static final String OBSERVATION_TABLE = "account_jwt_signer_secret_observations"; + private static final String RESULT_TABLE = "account_jwt_signer_generation_results"; + private static final String PROMOTION_TABLE = "account_jwt_signer_promotion_operations"; + private static final String MODE = "INTERIM_ACCOUNT_ONLY_MOUNTED_FALLBACK"; + private static final String ALGORITHM = "RS256"; + private static final String ACTION = "MATERIALIZE_PENDING"; + private static final String PENDING_SLOT = "pending"; + private static final byte[] PENDING_SLOT_CANONICAL_BYTES = + "[\"pending\"]".getBytes(StandardCharsets.UTF_8); + private static final byte[] PROMOTION_SLOTS_CANONICAL_BYTES = + "[\"current\",\"pending\",\"previous\"]".getBytes(StandardCharsets.UTF_8); + private static final Pattern ENVIRONMENT_ID = + Pattern.compile("[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?"); + private static final Pattern CLUSTER_ID = Pattern.compile("[A-Za-z0-9][A-Za-z0-9._:-]{0,127}"); + private static final Pattern RESOURCE_VERSION = Pattern.compile("[!-~]{1,256}"); + private static final Pattern KID = Pattern.compile("[A-Za-z0-9_-]{1,64}"); + private static final Pattern SHA256_HEX = Pattern.compile("[0-9a-f]{64}"); + private static final Pattern POSITIVE_DECIMAL = Pattern.compile("[1-9][0-9]{0,18}"); + private static final Set PUBLIC_JWK_FIELDS = + Set.of("kty", "use", "alg", "kid", "key_ops", "n", "e"); + private static final JsonMapper JSON = JsonMapper.builder().build(); + private static final JsonMapper STRICT_JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + private final DSLContext dsl; + + @Autowired + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "The constructor only validates its trusted injected DSLContext; it performs no I/O or resource acquisition and defines no finalizer.") + public AccountJwtSignerDesiredStateRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl, "DSLContext is required"); + } + + /** + * Enrolls the fixed Account environment only after both protected trust bindings and a live + * fixed-ConfigMap observation have been reconciled by the enrollment owner. + */ + @Transactional(propagation = Propagation.MANDATORY) + public DesiredState initialize(Binding binding, EnrollmentIdentity enrollmentIdentity) { + requireWritableAccountTransaction(); + Objects.requireNonNull(binding, "JWT signer binding is required"); + Objects.requireNonNull(enrollmentIdentity, "Pinned JWT signer enrollment is required"); + int inserted = + dsl.execute( + "INSERT INTO " + + STATE_TABLE + + " (environment_id, cluster_id, kubernetes_namespace, custody_mode, " + + "private_secret_name, public_jwks_config_map_name, record_version, " + + "durable_active_generation, durable_active_kid, published_active_generation, " + + "published_active_kid, generation_operation_id, prepared_operation_id, " + + "enrollment_cluster_incarnation_uid, enrollment_namespace_uid, " + + "enrollment_materializer_binding_digest, enrollment_materializer_config_revision, " + + "enrollment_api_binding_digest, enrollment_api_config_revision, " + + "enrollment_public_config_map_uid, enrollment_public_config_map_resource_version, " + + "enrollment_public_config_map_snapshot_digest) " + + "VALUES (?, ?, ?, ?, 'jwt-signing-keys', 'jwt-jwks', 1, NULL, NULL, NULL, NULL, NULL, NULL, ?, ?, ?, ?, ?, ?, ?, ?, ?) " + + "ON CONFLICT (environment_id) DO NOTHING", + binding.environmentId(), + binding.clusterId(), + binding.namespace(), + binding.mode().value(), + UUID.fromString(enrollmentIdentity.expectedClusterIncarnationUid()), + UUID.fromString(enrollmentIdentity.expectedNamespaceUid()), + enrollmentIdentity.materializerTrustBindingDigest(), + enrollmentIdentity.materializerTrustConfigRevision(), + enrollmentIdentity.apiBindingDigest(), + enrollmentIdentity.apiConfigRevision(), + UUID.fromString(enrollmentIdentity.publicConfigMapUid()), + enrollmentIdentity.publicConfigMapResourceVersion(), + enrollmentIdentity.publicConfigMapSnapshotDigest()); + if (inserted < 0 || inserted > 1) { + throw new StorageUnavailableException("Account JWT signer initialization was ambiguous"); + } + Record row = selectState(binding.environmentId(), true); + if (row == null) { + throw new QuarantinedStateException("Initialized Account JWT signer state did not read back"); + } + DesiredState state = decodeState(row); + requireBinding(state, binding); + if (state.enrollmentIdentity().isEmpty() + || !state.enrollmentIdentity().orElseThrow().sameStablePins(enrollmentIdentity)) { + throw new BindingMismatchException( + "Account JWT signer enrollment trust or precreated resource identity changed"); + } + if (inserted == 1 && !state.enrollmentIdentity().orElseThrow().equals(enrollmentIdentity)) { + throw new QuarantinedStateException( + "Initial Account JWT signer enrollment receipt did not read back exactly"); + } + if (inserted == 1 + && (state.recordVersion() != 1 + || state.durableActive().isPresent() + || state.publishedActive().isPresent() + || state.generationOperationId().isPresent() + || state.preparedOperationId().isPresent())) { + throw new QuarantinedStateException( + "New Account JWT signer state contains inferred or unexpected authority"); + } + return state; + } + + /** + * Returns a pinned enrollment row even while PREPARED so startup reconciliation can inspect it. + * Ordinary desired-state reads continue to quarantine PREPARED signer state. + */ + @Transactional(propagation = Propagation.MANDATORY, readOnly = true) + public Optional readEnrollmentState(Binding expectedBinding) { + requireAccountTransaction(); + Objects.requireNonNull(expectedBinding, "Expected JWT signer binding is required"); + Record row = selectState(expectedBinding.environmentId(), false); + if (row == null) { + return Optional.empty(); + } + DesiredState state = decodeState(row); + requireBinding(state, expectedBinding); + if (state.enrollmentIdentity().isEmpty()) { + throw new QuarantinedStateException( + "Account JWT signer state has no independently protected enrollment identity"); + } + return Optional.of(state); + } + + /** Reads an explicitly enrolled state; a missing row never initializes desired state. */ + @Transactional(propagation = Propagation.MANDATORY, readOnly = true) + public DesiredState read(Binding expectedBinding) { + requireAccountTransaction(); + Objects.requireNonNull(expectedBinding, "Expected JWT signer binding is required"); + Record row = selectState(expectedBinding.environmentId(), false); + if (row == null) { + throw new MissingDesiredStateException(expectedBinding.environmentId()); + } + DesiredState state = decodeState(row); + requireBinding(state, expectedBinding); + if (state.enrollmentIdentity().isEmpty()) { + throw new QuarantinedStateException( + "Account JWT signer state has no independently protected enrollment identity"); + } + verifyPreparedIsUnavailable(state); + if (state.generationOperationId().isPresent()) { + StoredGenerationOperation operation = + selectGenerationOperation(state.generationOperationId().orElseThrow(), false); + if (operation == null) { + throw new QuarantinedStateException("Account JWT signer generation operation is missing"); + } + verifyOperationMatchesState(operation, state); + } + return state; + } + + /** + * Account's internal operation entrypoint. It receives no caller-selected operation, key + * identity, resource name, fingerprint, or material. Account creates one immutable operation if + * absent, or returns the same operation under the same protected trust snapshot. + */ + @Transactional(propagation = Propagation.MANDATORY) + public GenerationRequest ensureCurrentGenerationRequest( + Binding expectedBinding, TrustFence trust) { + requireWritableAccountTransaction(); + Objects.requireNonNull(expectedBinding, "Expected JWT signer binding is required"); + Objects.requireNonNull(trust, "Protected JWT materializer trust fence is required"); + Record stateRow = selectState(expectedBinding.environmentId(), true); + if (stateRow == null) { + throw new MissingDesiredStateException(expectedBinding.environmentId()); + } + DesiredState state = decodeState(stateRow); + requireBinding(state, expectedBinding); + verifyPreparedIsUnavailable(state); + requireEnrollmentTrust(state, trust); + + if (state.generationOperationId().isEmpty()) { + if (state.durableActive().isPresent()) { + throw new MissingGenerationOperationException( + "Account has no durable rotation request for its committed signer"); + } + return createGenerationRequest(state, trust); + } + + StoredGenerationOperation operation = + selectGenerationOperation(state.generationOperationId().orElseThrow(), true); + if (operation == null) { + throw new QuarantinedStateException("Account JWT signer generation operation is missing"); + } + verifyOperationMatchesState(operation, state); + requireCurrentTrust(operation, trust); + return readGenerationRequest(operation, state, true); + } + + /** + * Returns the same current Account-selected request and exact phase for an authenticated peer. + */ + @Transactional(propagation = Propagation.MANDATORY) + public GenerationRequest readCurrentGenerationRequest(Binding expectedBinding, TrustFence trust) { + requireWritableAccountTransaction(); + Objects.requireNonNull(expectedBinding, "Expected JWT signer binding is required"); + Objects.requireNonNull(trust, "Protected JWT materializer trust fence is required"); + Record stateRow = selectState(expectedBinding.environmentId(), true); + if (stateRow == null) { + throw new MissingDesiredStateException(expectedBinding.environmentId()); + } + DesiredState state = decodeState(stateRow); + requireBinding(state, expectedBinding); + verifyPreparedIsUnavailable(state); + requireEnrollmentTrust(state, trust); + UUID operationId = + state + .generationOperationId() + .orElseThrow( + () -> + new MissingGenerationOperationException( + "Account has no owner-selected JWT generation operation")); + StoredGenerationOperation operation = selectGenerationOperation(operationId, true); + if (operation == null) { + throw new QuarantinedStateException("Account JWT signer generation operation is missing"); + } + verifyOperationMatchesState(operation, state); + requireCurrentTrust(operation, trust); + return readGenerationRequest(operation, state, true); + } + + /** + * Reads the exact immutable result for Account's current generation operation while locking the + * desired-state, operation, and result rows in their canonical order. A historical result is + * never returned after the Account operation or protected trust fence has moved. + */ + @Transactional(propagation = Propagation.MANDATORY) + public GenerationResult readCurrentGenerationResult(Binding expectedBinding, TrustFence trust) { + requireWritableAccountTransaction(); + Objects.requireNonNull(expectedBinding, "Expected JWT signer binding is required"); + Objects.requireNonNull(trust, "Protected JWT materializer trust fence is required"); + Record stateRow = selectState(expectedBinding.environmentId(), true); + if (stateRow == null) { + throw new MissingDesiredStateException(expectedBinding.environmentId()); + } + DesiredState state = decodeState(stateRow); + requireBinding(state, expectedBinding); + verifyPreparedIsUnavailable(state); + requireEnrollmentTrust(state, trust); + UUID operationId = + state + .generationOperationId() + .orElseThrow( + () -> + new MissingGenerationOperationException( + "Account has no owner-selected JWT generation operation")); + StoredGenerationOperation operation = selectGenerationOperation(operationId, true); + if (operation == null) { + throw new QuarantinedStateException("Account JWT signer generation operation is missing"); + } + verifyOperationMatchesState(operation, state); + requireCurrentTrust(operation, trust); + GenerationResult result = selectGenerationResult(operationId, true); + if (result == null) { + throw new MissingGenerationObservationException( + "Account JWT generation result is not recorded for the current operation"); + } + verifyGenerationResultMatchesOperation(result, operation, state); + return result; + } + + /** + * Recovery-only read for the exact generation that owns the current PREPARED operation. It is + * intentionally distinct from ordinary serving/generation reads, which continue to fail closed + * while a promotion is unresolved. + */ + @Transactional(propagation = Propagation.MANDATORY) + public PreparedGenerationEvidence readPreparedGenerationForRecovery( + Binding expectedBinding, TrustFence trust) { + requireWritableAccountTransaction(); + Objects.requireNonNull(expectedBinding, "Expected JWT signer binding is required"); + Objects.requireNonNull(trust, "Protected JWT materializer trust fence is required"); + Record stateRow = selectState(expectedBinding.environmentId(), true); + if (stateRow == null) { + throw new MissingDesiredStateException(expectedBinding.environmentId()); + } + DesiredState state = decodeState(stateRow); + requireBinding(state, expectedBinding); + requireEnrollmentTrust(state, trust); + UUID promotionId = + state.preparedOperationId().orElseThrow(() -> new NoPreparedPromotionException()); + if (state.generationOperationId().isPresent()) { + throw new QuarantinedStateException( + "Account PREPARED signer state also contains a generation pointer"); + } + StoredPromotion promotion = selectPromotion(promotionId, true); + if (promotion == null || !"PREPARED".equals(promotion.status())) { + throw new QuarantinedStateException("Account PREPARED JWT signer operation is missing"); + } + requirePromotionMatchesState(promotion, state); + requireCurrentTrust(promotion, trust); + StoredGenerationOperation operation = + selectGenerationOperation(promotion.generationOperationId(), true); + GenerationResult result = selectGenerationResult(promotion.generationOperationId(), true); + if (operation == null || result == null) { + throw new QuarantinedStateException( + "Prepared JWT signer operation has incomplete generation evidence"); + } + verifyPreparedGenerationMatches(promotion, operation, result); + return new PreparedGenerationEvidence(state, promotion.publicEvidence(), result); + } + + /** + * Atomically records that the authenticated materializer may receive the immutable private-slot + * promotion operation. This marker is deliberately sticky: after it is committed, a lost RPC + * response is an uncertain external mutation and the operation must remain PREPARED for forward + * reconciliation. + */ + @Transactional(propagation = Propagation.MANDATORY) + public PreparedGenerationEvidence readAndMarkPreparedPromotionDispatched( + Binding expectedBinding, TrustFence trust) { + requireWritableAccountTransaction(); + PreparedGenerationEvidence evidence = readPreparedGenerationForRecovery(expectedBinding, trust); + UUID operationId = evidence.promotion().operationId(); + StoredPromotion promotion = selectPromotion(operationId, true); + if (promotion == null || !"PREPARED".equals(promotion.status())) { + throw new QuarantinedStateException("Account PREPARED JWT signer operation is missing"); + } + if (!promotion.privatePromotionDispatched()) { + int changed = + dsl.execute( + "UPDATE " + + PROMOTION_TABLE + + " SET private_promotion_dispatched_at = CURRENT_TIMESTAMP " + + "WHERE operation_id = ? AND status = 'PREPARED' " + + "AND private_promotion_dispatched_at IS NULL " + + "AND private_promotion_receipt_digest IS NULL " + + "AND active_jwks_receipt_digest IS NULL", + operationId); + if (changed != 1) { + throw new VersionConflictException( + "Account private promotion dispatch authorization CAS did not apply"); + } + promotion = selectPromotion(operationId, true); + } + if (promotion == null + || !promotion.privatePromotionDispatched() + || !"PREPARED".equals(promotion.status())) { + throw new QuarantinedStateException( + "Account private promotion dispatch authorization did not read back exactly"); + } + return evidence; + } + + /** + * Records one authenticated materializer readback of the exact fixed-Secret slot transition. Only + * public key identities, resource UID/RV, and slot names cross this boundary; private bytes and + * hashes of private bytes are neither accepted nor persisted. + */ + @Transactional(propagation = Propagation.MANDATORY) + public PrivatePromotionReceipt recordPrivatePromotionResult( + Binding expectedBinding, TrustFence trust, PrivatePromotionObservation observation) { + requireWritableAccountTransaction(); + Objects.requireNonNull(expectedBinding, "Expected JWT signer binding is required"); + Objects.requireNonNull(trust, "Protected JWT materializer trust fence is required"); + Objects.requireNonNull(observation, "Exact private promotion observation is required"); + Record stateRow = selectState(expectedBinding.environmentId(), true); + if (stateRow == null) { + throw new MissingDesiredStateException(expectedBinding.environmentId()); + } + DesiredState state = decodeState(stateRow); + requireBinding(state, expectedBinding); + requireEnrollmentTrust(state, trust); + StoredPromotion promotion = selectPromotion(observation.promotionOperationId(), true); + if (promotion == null) { + throw new StaleGenerationOperationException( + "Private promotion result does not target an Account-owned operation"); + } + requireCurrentTrust(promotion, trust); + if (!promotion.requestDigest().equals(observation.promotionRequestDigest()) + || !promotion.generationOperationId().equals(observation.generationOperationId()) + || !promotion.generationOperationDigest().equals(observation.generationOperationDigest())) { + throw new IdempotencyConflictException( + "Private promotion result does not match the exact Account operation"); + } + if (!promotion.privatePromotionDispatched()) { + throw new PromotionPrerequisitesIncompleteException( + "Private promotion result has no prior durable Account dispatch authorization"); + } + StoredGenerationOperation operation = + selectGenerationOperation(promotion.generationOperationId(), true); + GenerationResult result = selectGenerationResult(promotion.generationOperationId(), true); + if (operation == null || result == null) { + throw new QuarantinedStateException( + "Prepared JWT signer operation has incomplete generation evidence"); + } + verifyPreparedGenerationMatches(promotion, operation, result); + requirePrivatePromotionObservation(promotion, observation); + PrivatePromotionReceipt candidate = PrivatePromotionReceipt.from(promotion, observation); + + if ("COMMITTED".equals(promotion.status())) { + ActiveSigner target = new ActiveSigner(promotion.targetGeneration(), promotion.targetKid()); + if (!promotion.binding().equals(expectedBinding) + || !promotion.requestDigest().equals(promotionRequestDigest(promotion)) + || state.preparedOperationId().isPresent() + || state.durableActive().filter(target::equals).isEmpty() + || state.publishedActive().filter(target::equals).isEmpty() + || promotion.expectedRecordVersion() > Long.MAX_VALUE - 2 + || state.recordVersion() < promotion.expectedRecordVersion() + 2 + || promotion.privatePromotionReceiptDigest() == null + || promotion.activeJwksReceiptDigest() == null + || !candidate.receiptDigest().equals(promotion.privatePromotionReceiptDigest()) + || !candidate + .observedResourceVersion() + .equals(promotion.privatePromotionObservedResourceVersion())) { + throw new IdempotencyConflictException( + "Committed private promotion retry does not match current Account evidence"); + } + return candidate; + } + + if (!"PREPARED".equals(promotion.status()) + || !state.preparedOperationId().equals(Optional.of(observation.promotionOperationId())) + || state.generationOperationId().isPresent()) { + throw new StaleGenerationOperationException( + "Private promotion result does not target Account's current PREPARED operation"); + } + requirePromotionMatchesState(promotion, state); + if (promotion.privatePromotionReceiptDigest() != null) { + if (!candidate.receiptDigest().equals(promotion.privatePromotionReceiptDigest()) + || !candidate + .observedResourceVersion() + .equals(promotion.privatePromotionObservedResourceVersion())) { + throw new IdempotencyConflictException( + "Private promotion readback changed for the same Account operation"); + } + return candidate; + } + int updated = + dsl.execute( + "UPDATE " + + PROMOTION_TABLE + + " SET private_promotion_observed_resource_version = ?, " + + "private_promotion_receipt_digest = ? WHERE operation_id = ? " + + "AND status = 'PREPARED' AND private_promotion_dispatched_at IS NOT NULL " + + "AND private_promotion_receipt_digest IS NULL", + candidate.observedResourceVersion(), + candidate.receiptDigest(), + candidate.promotionOperationId()); + if (updated != 1) { + throw new VersionConflictException("Account private promotion receipt CAS did not apply"); + } + StoredPromotion readback = selectPromotion(candidate.promotionOperationId(), true); + if (readback == null + || !candidate.receiptDigest().equals(readback.privatePromotionReceiptDigest()) + || !candidate + .observedResourceVersion() + .equals(readback.privatePromotionObservedResourceVersion())) { + throw new QuarantinedStateException( + "Account private promotion receipt did not read back exactly"); + } + return candidate; + } + + /** + * Records Account's exact readback after its fixed public ConfigMap CAS changes only the + * generation marker from PREPUBLISHED to ACTIVE. The public receipt contains no private Secret + * bytes or digest of private material. + */ + @Transactional(propagation = Propagation.MANDATORY) + public ActiveJwksPromotionReceipt recordActiveJwksPromotionResult( + Binding expectedBinding, TrustFence trust, ActiveJwksPromotionObservation observation) { + requireWritableAccountTransaction(); + Objects.requireNonNull(expectedBinding, "Expected JWT signer binding is required"); + Objects.requireNonNull(trust, "Protected JWT materializer trust fence is required"); + Objects.requireNonNull(observation, "Exact Account ConfigMap promotion readback is required"); + Record stateRow = selectState(expectedBinding.environmentId(), true); + if (stateRow == null) { + throw new MissingDesiredStateException(expectedBinding.environmentId()); + } + DesiredState state = decodeState(stateRow); + requireBinding(state, expectedBinding); + requireEnrollmentTrust(state, trust); + UUID promotionId = + state + .preparedOperationId() + .orElseThrow( + () -> + new PromotionPrerequisitesIncompleteException( + "Account has no PREPARED JWT signer promotion")); + StoredPromotion promotion = selectPromotion(promotionId, true); + if (promotion == null || !"PREPARED".equals(promotion.status())) { + throw new QuarantinedStateException("Account PREPARED JWT signer operation is missing"); + } + requirePromotionMatchesState(promotion, state); + requireCurrentTrust(promotion, trust); + if (promotion.privatePromotionReceiptDigest() == null) { + throw new PromotionPrerequisitesIncompleteException( + "Account cannot publish ACTIVE before the exact private-slot readback"); + } + requireActiveJwksObservation(promotion, observation); + ActiveJwksPromotionReceipt candidate = ActiveJwksPromotionReceipt.from(promotion, observation); + if (promotion.activeJwksReceiptDigest() != null) { + if (!candidate.receiptDigest().equals(promotion.activeJwksReceiptDigest()) + || !candidate.publicDataDigest().equals(promotion.activeJwksPublicDataDigest()) + || !candidate + .observedResourceVersion() + .equals(promotion.activeJwksObservedResourceVersion())) { + throw new IdempotencyConflictException( + "Active Account JWT JWKS readback changed for the same promotion operation"); + } + return candidate; + } + int updated = + dsl.execute( + "UPDATE " + + PROMOTION_TABLE + + " SET active_jwks_observed_resource_version = ?, active_jwks_public_data_digest = ?, " + + "active_jwks_receipt_digest = ? WHERE operation_id = ? AND status = 'PREPARED' " + + "AND private_promotion_receipt_digest IS NOT NULL " + + "AND active_jwks_receipt_digest IS NULL", + candidate.observedResourceVersion(), + candidate.publicDataDigest(), + candidate.receiptDigest(), + candidate.promotionOperationId()); + if (updated != 1) { + throw new VersionConflictException("Account active JWKS promotion receipt CAS did not apply"); + } + StoredPromotion readback = selectPromotion(candidate.promotionOperationId(), true); + if (readback == null + || !candidate.receiptDigest().equals(readback.activeJwksReceiptDigest()) + || !candidate.publicDataDigest().equals(readback.activeJwksPublicDataDigest()) + || !candidate + .observedResourceVersion() + .equals(readback.activeJwksObservedResourceVersion())) { + throw new QuarantinedStateException("Account active JWKS receipt did not read back exactly"); + } + return candidate; + } + + /** + * Commits only after both exact external-resource receipts are durably read back. The promotion + * row and desired-state active fences transition in one Account transaction. + */ + @Transactional(propagation = Propagation.MANDATORY) + public CommittedSignerEvidence commitPreparedPromotion( + Binding expectedBinding, + TrustFence trust, + UUID promotionOperationId, + ReadinessPromotionProof readinessProof) { + requireWritableAccountTransaction(); + Objects.requireNonNull(expectedBinding, "Expected JWT signer binding is required"); + Objects.requireNonNull(trust, "Protected JWT materializer trust fence is required"); + requireOperationId(promotionOperationId); + Objects.requireNonNull(readinessProof, "Current Account readiness proof is required"); + Record stateRow = selectState(expectedBinding.environmentId(), true); + if (stateRow == null) { + throw new MissingDesiredStateException(expectedBinding.environmentId()); + } + DesiredState state = decodeState(stateRow); + requireBinding(state, expectedBinding); + requireEnrollmentTrust(state, trust); + if (!state.preparedOperationId().equals(Optional.of(promotionOperationId))) { + throw new StaleGenerationOperationException( + "Commit does not target Account's exact PREPARED promotion"); + } + StoredPromotion promotion = selectPromotion(promotionOperationId, true); + if (promotion == null || !"PREPARED".equals(promotion.status())) { + throw new QuarantinedStateException("Account PREPARED JWT signer operation is missing"); + } + requirePromotionMatchesState(promotion, state); + requireCurrentTrust(promotion, trust); + if (promotion.privatePromotionReceiptDigest() == null + || promotion.activeJwksReceiptDigest() == null) { + throw new PromotionPrerequisitesIncompleteException( + "Account promotion lacks exact private and public resource receipts"); + } + if (!promotion.privatePromotionDispatched()) { + throw new QuarantinedStateException( + "Account promotion receipts have no durable private dispatch authorization"); + } + StoredGenerationOperation generation = + selectGenerationOperation(promotion.generationOperationId(), true); + GenerationResult result = selectGenerationResult(promotion.generationOperationId(), true); + if (generation == null || result == null) { + throw new QuarantinedStateException("Committed signer generation evidence is missing"); + } + verifyPreparedGenerationMatches(promotion, generation, result); + PromotionPreparation commitPreparation = + new PromotionPreparation( + promotion.generationOperationId(), + result, + state.enrollmentIdentity().orElseThrow(), + promotion.apiBindingDigest(), + promotion.apiConfigRevision(), + promotion.publicConfigMapUid(), + promotion.expectedPublicResourceVersion(), + promotion.prepublicationIntentDigest(), + promotion.prepublicationReceiptDigest(), + promotion.mountedObservationDigest(), + promotion.readinessPlanDigest(), + promotion.readinessEvidenceDigest(), + promotion.expectedPublicJwksJson()); + requireReadinessProofMatches( + result, commitPreparation, promotion, expectedBinding, trust, readinessProof); + requireUnexpiredCurrentReadinessProof(promotion, result, readinessProof); + + // State is locked first above, matching readiness expiry/cleanup's owner lock order. The + // terminal UPDATE repeats the clock and complete-entry fence atomically; the count query in + // the helper is a validation read, not an entry-row lock. + int changed = + dsl.execute( + "UPDATE " + + PROMOTION_TABLE + + " SET status = 'COMMITTED' WHERE operation_id = ? " + + "AND status = 'PREPARED' AND private_promotion_dispatched_at IS NOT NULL " + + "AND private_promotion_receipt_digest IS NOT NULL " + + "AND active_jwks_receipt_digest IS NOT NULL " + + "AND EXISTS (SELECT 1 FROM account_jwt_readiness_probe_plans plan " + + "WHERE plan.rotation_operation_id = ? AND plan.plan_digest = ? " + + "AND plan.validator_inventory_complete = TRUE " + + "AND plan.not_before_epoch_seconds <= " + + "floor(extract(epoch FROM clock_timestamp()))::BIGINT " + + "AND plan.expires_at_epoch_seconds > " + + "floor(extract(epoch FROM clock_timestamp()))::BIGINT) " + + "AND (SELECT count(*) FROM account_jwt_readiness_probe_entries entry " + + "WHERE entry.rotation_operation_id = ? AND entry.plan_digest = ?) = ? " + + "AND (SELECT count(*) FROM account_jwt_readiness_probe_entries entry " + + "WHERE entry.rotation_operation_id = ? AND entry.plan_digest = ? " + + "AND entry.state = 'VERIFIED' AND entry.verification_receipt_sha256 IS NOT NULL " + + "AND entry.verified_at_epoch_seconds < entry.expires_at_epoch_seconds " + + "AND entry.expires_at_epoch_seconds > " + + "floor(extract(epoch FROM clock_timestamp()))::BIGINT) = ?", + promotionOperationId, + promotion.generationOperationId(), + promotion.readinessPlanDigest(), + promotion.generationOperationId(), + promotion.readinessPlanDigest(), + readinessProof.verifiedProbes().size(), + promotion.generationOperationId(), + promotion.readinessPlanDigest(), + readinessProof.verifiedProbes().size()); + if (changed != 1) { + throw new VersionConflictException("Account promotion terminal CAS did not apply"); + } + int advanced = + dsl.execute( + "UPDATE " + + STATE_TABLE + + " SET record_version = record_version + 1, durable_active_generation = ?, " + + "durable_active_kid = ?, published_active_generation = ?, published_active_kid = ?, " + + "prepared_operation_id = NULL, updated_at = CURRENT_TIMESTAMP " + + "WHERE environment_id = ? AND cluster_id = ? AND kubernetes_namespace = ? " + + "AND custody_mode = ? AND record_version = ? AND prepared_operation_id = ? " + + "AND generation_operation_id IS NULL " + + "AND durable_active_generation IS NOT DISTINCT FROM ? " + + "AND durable_active_kid IS NOT DISTINCT FROM ? " + + "AND published_active_generation IS NOT DISTINCT FROM ? " + + "AND published_active_kid IS NOT DISTINCT FROM ?", + parseGeneration(promotion.targetGeneration()), + promotion.targetKid(), + parseGeneration(promotion.targetGeneration()), + promotion.targetKid(), + state.binding().environmentId(), + state.binding().clusterId(), + state.binding().namespace(), + state.binding().mode().value(), + state.recordVersion(), + promotionOperationId, + generationValue(state.durableActive()), + kidValue(state.durableActive()), + generationValue(state.publishedActive()), + kidValue(state.publishedActive())); + if (advanced != 1) { + throw new VersionConflictException("Account committed active-signer CAS did not apply"); + } + StoredPromotion committed = selectPromotion(promotionOperationId, true); + Record committedStateRow = selectState(expectedBinding.environmentId(), true); + if (committed == null || committedStateRow == null || !"COMMITTED".equals(committed.status())) { + throw new QuarantinedStateException("Account committed promotion did not read back"); + } + DesiredState committedState = decodeState(committedStateRow); + requireCommittedStateMatches(committed, committedState); + return new CommittedSignerEvidence( + committed.publicEvidence(), + result, + committedState, + PrivatePromotionReceipt.fromStored(committed), + ActiveJwksPromotionReceipt.fromStored(committed)); + } + + /** + * Aborts only before either Kubernetes mutation was recorded. Once either external write may have + * happened, the operation remains PREPARED for exact forward recovery rather than guessing + * rollback state. + */ + @Transactional(propagation = Propagation.MANDATORY) + public AbortedPromotion abortPreparedBeforeMutation( + Binding expectedBinding, TrustFence trust, UUID promotionOperationId) { + requireWritableAccountTransaction(); + Objects.requireNonNull(expectedBinding, "Expected JWT signer binding is required"); + Objects.requireNonNull(trust, "Protected JWT materializer trust fence is required"); + requireOperationId(promotionOperationId); + Record stateRow = selectState(expectedBinding.environmentId(), true); + if (stateRow == null) { + throw new MissingDesiredStateException(expectedBinding.environmentId()); + } + DesiredState state = decodeState(stateRow); + requireBinding(state, expectedBinding); + requireEnrollmentTrust(state, trust); + if (!state.preparedOperationId().equals(Optional.of(promotionOperationId))) { + throw new StaleGenerationOperationException( + "Abort does not target the exact PREPARED operation"); + } + StoredPromotion promotion = selectPromotion(promotionOperationId, true); + if (promotion == null || !"PREPARED".equals(promotion.status())) { + throw new QuarantinedStateException("Account PREPARED JWT signer operation is missing"); + } + requirePromotionMatchesState(promotion, state); + requireCurrentTrust(promotion, trust); + if (promotion.privatePromotionDispatched() + || promotion.privatePromotionReceiptDigest() != null + || promotion.activeJwksReceiptDigest() != null) { + throw new PromotionPrerequisitesIncompleteException( + "A dispatched promotion must remain PREPARED for forward reconciliation"); + } + int changed = + dsl.execute( + "UPDATE " + + PROMOTION_TABLE + + " SET status = 'ABORTED' WHERE operation_id = ? " + + "AND status = 'PREPARED' AND private_promotion_receipt_digest IS NULL " + + "AND active_jwks_receipt_digest IS NULL " + + "AND private_promotion_dispatched_at IS NULL", + promotionOperationId); + if (changed != 1) + throw new VersionConflictException("Account promotion abort CAS did not apply"); + int advanced = + dsl.execute( + "UPDATE " + + STATE_TABLE + + " SET record_version = record_version + 1, prepared_operation_id = NULL, " + + "updated_at = CURRENT_TIMESTAMP WHERE environment_id = ? AND record_version = ? " + + "AND prepared_operation_id = ? AND generation_operation_id IS NULL", + expectedBinding.environmentId(), + state.recordVersion(), + promotionOperationId); + if (advanced != 1) + throw new VersionConflictException("Account signer abort state CAS did not apply"); + StoredPromotion aborted = selectPromotion(promotionOperationId, true); + DesiredState abortedState = decodeState(selectState(expectedBinding.environmentId(), true)); + if (aborted == null + || !"ABORTED".equals(aborted.status()) + || abortedState.preparedOperationId().isPresent()) { + throw new QuarantinedStateException("Account aborted promotion did not read back exactly"); + } + return new AbortedPromotion( + promotionOperationId, + abortedState.recordVersion(), + abortedState.durableActive(), + abortedState.publishedActive()); + } + + /** Reads only the exact Account-committed generation and both durable resource receipts. */ + @Transactional(propagation = Propagation.MANDATORY) + public Optional readCurrentCommittedSigner( + Binding expectedBinding, + TrustFence trust, + String currentApiBindingDigest, + String currentApiConfigRevision) { + requireWritableAccountTransaction(); + Objects.requireNonNull(expectedBinding, "Expected JWT signer binding is required"); + Objects.requireNonNull(trust, "Protected JWT materializer trust fence is required"); + Record stateRow = selectState(expectedBinding.environmentId(), true); + if (stateRow == null) return Optional.empty(); + DesiredState state = decodeState(stateRow); + requireBinding(state, expectedBinding); + requireEnrollmentTrust(state, trust); + EnrollmentIdentity enrollment = state.enrollmentIdentity().orElseThrow(); + requireMatch(SHA256_HEX, currentApiBindingDigest, "current public API binding digest"); + requireMatch(CLUSTER_ID, currentApiConfigRevision, "current public API config revision"); + if (!enrollment.apiBindingDigest().equals(currentApiBindingDigest) + || !enrollment.apiConfigRevision().equals(currentApiConfigRevision)) { + throw new BindingMismatchException("Protected Account JWKS API binding changed"); + } + if (state.preparedOperationId().isPresent()) { + throw new PromotionPrerequisitesIncompleteException( + "Account signer lifecycle is unresolved and cannot serve a committed signer"); + } + if (state.durableActive().isEmpty() || !state.durableActive().equals(state.publishedActive())) { + throw new QuarantinedStateException( + "Account durable and published active signer fences disagree"); + } + ActiveSigner active = state.durableActive().orElseThrow(); + if (state.generationOperationId().isPresent()) { + StoredGenerationOperation pending = + selectGenerationOperation(state.generationOperationId().orElseThrow(), false); + if (pending == null) { + throw new QuarantinedStateException("Current Account generation operation is missing"); + } + verifyOperationMatchesState(pending, state); + requireCurrentTrust(pending, trust); + } + StoredPromotion promotion = selectCommittedPromotion(state, active); + if (promotion == null) { + throw new QuarantinedStateException( + "Account active signer has no exact committed promotion receipt"); + } + requireCurrentTrust(promotion, trust); + requireCommittedActiveStillCurrent(promotion, state); + if (!promotion.apiBindingDigest().equals(currentApiBindingDigest) + || !promotion.apiConfigRevision().equals(currentApiConfigRevision)) { + throw new BindingMismatchException( + "Committed signer uses an obsolete Account JWKS API binding"); + } + StoredGenerationOperation generation = + selectGenerationOperation(promotion.generationOperationId(), false); + GenerationResult result = selectGenerationResult(promotion.generationOperationId(), false); + if (generation == null || result == null) { + throw new QuarantinedStateException("Committed Account generation result is missing"); + } + verifyPreparedGenerationMatches(promotion, generation, result); + if (promotion.privatePromotionReceiptDigest() == null + || promotion.activeJwksReceiptDigest() == null) { + throw new QuarantinedStateException( + "Committed Account signer is missing exact resource receipts"); + } + return Optional.of( + new CommittedSignerEvidence( + promotion.publicEvidence(), + result, + state, + PrivatePromotionReceipt.fromStored(promotion), + ActiveJwksPromotionReceipt.fromStored(promotion))); + } + + /** + * Reads the original committed signer after ordinary rotation. This authenticates retained + * lifecycle provenance only; the caller must separately verify that the original public JWK is + * still accepted by the current protected JWKS source. No current-active equality is imposed. + */ + @Transactional(propagation = Propagation.MANDATORY) + public Optional readOriginalCommittedSigner( + Binding expectedBinding, + TrustFence trust, + String currentApiBindingDigest, + String currentApiConfigRevision, + UUID promotionOperationId, + UUID generationOperationId) { + requireWritableAccountTransaction(); + Objects.requireNonNull(expectedBinding); + Objects.requireNonNull(trust); + requireOperationId(promotionOperationId); + requireOperationId(generationOperationId); + requireMatch(SHA256_HEX, currentApiBindingDigest, "current public API binding digest"); + requireMatch(CLUSTER_ID, currentApiConfigRevision, "current public API config revision"); + Record stateRow = selectState(expectedBinding.environmentId(), true); + if (stateRow == null) return Optional.empty(); + DesiredState current = decodeState(stateRow); + requireBinding(current, expectedBinding); + requireEnrollmentTrust(current, trust); + EnrollmentIdentity enrollment = current.enrollmentIdentity().orElseThrow(); + if (!enrollment.apiBindingDigest().equals(currentApiBindingDigest) + || !enrollment.apiConfigRevision().equals(currentApiConfigRevision)) { + throw new BindingMismatchException("Protected Account JWKS API binding changed"); + } + StoredPromotion promotion = selectPromotion(promotionOperationId, false); + if (promotion == null) return Optional.empty(); + requireCurrentTrust(promotion, trust); + if (!"COMMITTED".equals(promotion.status()) + || !expectedBinding.equals(promotion.binding()) + || !generationOperationId.equals(promotion.generationOperationId()) + || !currentApiBindingDigest.equals(promotion.apiBindingDigest()) + || !currentApiConfigRevision.equals(promotion.apiConfigRevision())) { + throw new QuarantinedStateException("Original committed signer identity differs"); + } + StoredGenerationOperation generation = selectGenerationOperation(generationOperationId, false); + GenerationResult result = selectGenerationResult(generationOperationId, false); + if (generation == null || result == null) { + throw new QuarantinedStateException("Original committed signer generation is absent"); + } + requireCurrentTrust(generation, trust); + verifyPreparedGenerationMatches(promotion, generation, result); + if (promotion.privatePromotionReceiptDigest() == null + || promotion.activeJwksReceiptDigest() == null) { + throw new QuarantinedStateException("Original committed signer resource receipts are absent"); + } + return Optional.of( + new OriginalCommittedSignerEvidence( + promotion.publicEvidence(), + result, + PrivatePromotionReceipt.fromStored(promotion), + ActiveJwksPromotionReceipt.fromStored(promotion))); + } + + /** Immutable historical owner readback, not an active-key or authenticated-actor grant. */ + public record OriginalCommittedSignerEvidence( + PromotionOperationEvidence promotion, + GenerationResult generationResult, + PrivatePromotionReceipt privateReceipt, + ActiveJwksPromotionReceipt publicReceipt) { + public OriginalCommittedSignerEvidence { + Objects.requireNonNull(promotion); + Objects.requireNonNull(generationResult); + Objects.requireNonNull(privateReceipt); + Objects.requireNonNull(publicReceipt); + if (!"COMMITTED".equals(promotion.status()) + || !promotion.generationOperationId().equals(generationResult.operationId()) + || !promotion.operationId().equals(privateReceipt.promotionOperationId()) + || !promotion.operationId().equals(publicReceipt.promotionOperationId())) { + throw new QuarantinedStateException("Original committed signer linkage is inconsistent"); + } + } + } + + /** Persists the pinned materializer's read-only observation of the fixed pre-created Secret. */ + @Transactional(propagation = Propagation.MANDATORY) + public GenerationRequest recordSecretObservation( + Binding expectedBinding, + TrustFence trust, + UUID operationId, + String operationDigest, + String secretUid, + String observedResourceVersion) { + requireWritableAccountTransaction(); + Objects.requireNonNull(expectedBinding, "Expected JWT signer binding is required"); + Objects.requireNonNull(trust, "Protected JWT materializer trust fence is required"); + requireOperationId(operationId); + requireMatch(SHA256_HEX, operationDigest, "JWT generation operation digest"); + requireUuid(secretUid, "fixed Secret UID"); + requireMatch(RESOURCE_VERSION, observedResourceVersion, "observed Secret resourceVersion"); + + LockedCurrent current = lockCurrentOperation(expectedBinding, trust, operationId); + if (!current.operation().operationDigest().equals(operationDigest)) { + throw new IdempotencyConflictException( + "JWT signer Secret observation does not match the Account operation digest"); + } + SecretObservation candidate = + SecretObservation.from(current.operation(), secretUid, observedResourceVersion); + SecretObservation existing = selectSecretObservation(operationId, true); + if (existing != null) { + if (!existing.equals(candidate)) { + throw new IdempotencyConflictException( + "JWT signer Secret observation changed for the same Account operation"); + } + return readGenerationRequest(current.operation(), current.state(), true); + } + + insertSecretObservation(candidate); + SecretObservation readback = selectSecretObservation(operationId, true); + if (readback == null || !readback.equals(candidate)) { + throw new QuarantinedStateException( + "Account JWT signer Secret observation did not read back exactly"); + } + return toGenerationRequest(current.operation(), current.state(), readback, null); + } + + /** + * Persists one public-only key-generation result. Account validates the canonical RSA JWK and + * derives the RFC 7638 fingerprint; private members, tokens, and caller fingerprints are not + * accepted. Exact retries return the immutable receipt; changed/stale retries fail closed. + */ + @Transactional(propagation = Propagation.MANDATORY) + public GenerationResult recordGenerationResult( + Binding expectedBinding, + TrustFence trust, + UUID operationId, + String generationRequestDigest, + String secretUid, + String expectedPriorResourceVersion, + String observedResourceVersion, + String publicJwkJson) { + requireWritableAccountTransaction(); + Objects.requireNonNull(expectedBinding, "Expected JWT signer binding is required"); + Objects.requireNonNull(trust, "Protected JWT materializer trust fence is required"); + requireOperationId(operationId); + requireMatch(SHA256_HEX, generationRequestDigest, "JWT generation request digest"); + requireUuid(secretUid, "fixed Secret UID"); + requireMatch(RESOURCE_VERSION, expectedPriorResourceVersion, "expected Secret resourceVersion"); + requireMatch(RESOURCE_VERSION, observedResourceVersion, "observed Secret resourceVersion"); + if (expectedPriorResourceVersion.equals(observedResourceVersion)) { + throw new QuarantinedStateException("JWT signer Secret resourceVersion did not advance"); + } + PublicJwk publicJwk = parsePublicJwk(publicJwkJson); + + LockedCurrent current = lockCurrentOperation(expectedBinding, trust, operationId); + StoredGenerationOperation operation = current.operation(); + SecretObservation observation = selectSecretObservation(operationId, true); + if (observation == null) { + throw new MissingGenerationObservationException( + "JWT signer generation cannot precede exact Secret observation"); + } + if (!observation.secretUid().equals(secretUid) + || !observation.observedResourceVersion().equals(expectedPriorResourceVersion) + || !observation.generationRequestDigest().equals(generationRequestDigest)) { + throw new StaleGenerationOperationException( + "JWT signer generation result does not match the observed Secret fence"); + } + if (!publicJwk.kid().equals(operation.targetKid()) + || !ALGORITHM.equals(operation.targetAlgorithm())) { + throw new QuarantinedStateException( + "JWT signer public JWK does not match the Account-selected key identity"); + } + + GenerationResult candidate = + GenerationResult.from( + operation, + current.state().recordVersion(), + observation, + observedResourceVersion, + publicJwk); + GenerationResult existing = selectGenerationResult(operationId, true); + if (existing != null) { + if (!existing.equals(candidate)) { + throw new IdempotencyConflictException( + "JWT signer generation result changed for the same Account operation"); + } + return existing; + } + + insertGenerationResult(candidate); + GenerationResult readback = selectGenerationResult(operationId, true); + if (readback == null || !readback.equals(candidate)) { + throw new QuarantinedStateException( + "Account JWT signer generation result did not read back exactly"); + } + return readback; + } + + /** + * Persists PREPARED only for exact owner-readback generation, prepublication, and readiness + * evidence supplied by the lifecycle coordinator. The database independently locks and checks the + * generation/publication/readiness rows; caller booleans and signer/JWKS agreement alone cannot + * enter PREPARED. + */ + @Transactional(propagation = Propagation.MANDATORY) + public PreparedPromotion prepareCurrentGeneration( + Binding expectedBinding, + TrustFence trust, + PromotionPreparation preparation, + ReadinessPromotionProof readinessProof) { + requireWritableAccountTransaction(); + Objects.requireNonNull(expectedBinding, "Expected JWT signer binding is required"); + Objects.requireNonNull(trust, "Protected JWT materializer trust fence is required"); + Objects.requireNonNull(preparation, "Owner-readback promotion preparation is required"); + Objects.requireNonNull(readinessProof, "Account-verified readiness proof is required"); + Record stateRow = selectState(expectedBinding.environmentId(), true); + if (stateRow == null) { + throw new MissingDesiredStateException(expectedBinding.environmentId()); + } + DesiredState state = decodeState(stateRow); + requireBinding(state, expectedBinding); + requireEnrollmentTrust(state, trust); + EnrollmentIdentity enrollment = state.enrollmentIdentity().orElseThrow(); + if (!enrollment.sameStablePins(preparation.enrollmentIdentity()) + || !enrollment.apiBindingDigest().equals(preparation.apiBindingDigest()) + || !enrollment.apiConfigRevision().equals(preparation.apiConfigRevision()) + || !enrollment.publicConfigMapUid().equals(preparation.publicConfigMapUid())) { + throw new BindingMismatchException( + "JWT signer promotion trust does not match the independently pinned enrollment"); + } + if (state.preparedOperationId().isPresent()) { + StoredPromotion replay = selectPromotion(state.preparedOperationId().orElseThrow(), true); + if (replay == null || !"PREPARED".equals(replay.status())) { + throw new QuarantinedStateException("Account PREPARED promotion is missing"); + } + requirePromotionMatchesState(replay, state); + requireCurrentTrust(replay, trust); + StoredGenerationOperation replayGeneration = + selectGenerationOperation(replay.generationOperationId(), true); + GenerationResult replayResult = selectGenerationResult(replay.generationOperationId(), true); + if (replayGeneration == null || replayResult == null) { + throw new QuarantinedStateException("Prepared promotion source generation is missing"); + } + verifyPreparedGenerationMatches(replay, replayGeneration, replayResult); + if (!replay.matchesPreparation(preparation, replayGeneration, replayResult, enrollment)) { + throw new IdempotencyConflictException( + "JWT signer promotion retry changed its immutable evidence"); + } + requireReadinessProofMatches( + replayResult, preparation, replay, expectedBinding, trust, readinessProof); + return new PreparedPromotion(replay.operationId(), replay.requestDigest(), "PREPARED"); + } + UUID generationOperationId = + state + .generationOperationId() + .orElseThrow( + () -> + new MissingGenerationOperationException( + "Account has no current generation operation to promote")); + StoredGenerationOperation generation = selectGenerationOperation(generationOperationId, true); + GenerationResult result = selectGenerationResult(generationOperationId, true); + if (generation == null || result == null) { + throw new PromotionPrerequisitesIncompleteException( + "Account generation operation has no exact persisted result"); + } + verifyOperationMatchesState(generation, state); + requireCurrentTrust(generation, trust); + verifyGenerationResultMatchesOperation(result, generation, state); + if (!result.equals(preparation.generationResult()) + || !preparation.generationOperationId().equals(generationOperationId)) { + throw new StaleGenerationOperationException( + "Promotion preparation does not match the exact current generation result"); + } + requireReadinessProofMatches(result, preparation, null, expectedBinding, trust, readinessProof); + requireCurrentPublicationForPreparation(result, preparation); + requireCurrentReadinessForPreparation(result, preparation); + + StoredPromotion candidate = + StoredPromotion.create(preparation, state, generation, result, trust, expectedBinding); + StoredPromotion existing = selectPromotion(candidate.operationId(), true); + if (existing != null) { + requirePromotionMatchesState(existing, state); + if (!existing.equals(candidate)) { + throw new IdempotencyConflictException( + "JWT signer promotion request changed for the same operation"); + } + return new PreparedPromotion(existing.operationId(), existing.requestDigest(), "PREPARED"); + } + insertPromotion(candidate); + int advanced = advanceToPrepared(state, candidate.operationId()); + if (advanced != 1) { + throw new VersionConflictException("Account desired state changed while entering PREPARED"); + } + StoredPromotion readback = selectPromotion(candidate.operationId(), true); + Record stateReadbackRow = selectState(expectedBinding.environmentId(), true); + if (readback == null || stateReadbackRow == null || !readback.equals(candidate)) { + throw new QuarantinedStateException("Account PREPARED promotion did not read back exactly"); + } + DesiredState stateReadback = decodeState(stateReadbackRow); + requirePromotionMatchesState(readback, stateReadback); + return new PreparedPromotion(readback.operationId(), readback.requestDigest(), "PREPARED"); + } + + private static void requireReadinessProofMatches( + GenerationResult result, + PromotionPreparation preparation, + StoredPromotion preparedReplay, + Binding expectedBinding, + TrustFence trust, + ReadinessPromotionProof proof) { + var plan = proof.plan(); + var publication = proof.publication(); + if (!proof.generationResult().equals(result) + || !preparation.generationResult().equals(result) + || !plan.operationId().equals(result.operationId()) + || !plan.binding().equals(expectedBinding) + || !plan.trustFence().equals(trust) + || !plan.planDigest().equals(preparation.readinessPlanDigest()) + || !proof.readinessEvidenceDigest().equals(preparation.readinessEvidenceDigest()) + || !plan.operationDigest().equals(result.operationDigest()) + || !plan.generationRequestDigest().equals(result.generationRequestDigest()) + || !plan.generationReceiptDigest().equals(result.receiptDigest()) + || plan.desiredStateVersion() != result.desiredStateVersion() + || !plan.targetGeneration().equals(result.targetGeneration()) + || !plan.targetKid().equals(result.targetKid()) + || !plan.targetPublicKeyFingerprint().equals(result.publicKeyFingerprint()) + || !publication.intent().intentDigest().equals(preparation.prepublicationIntentDigest()) + || !publication.receipt().receiptDigest().equals(preparation.prepublicationReceiptDigest()) + || !publication + .mountedCorrespondence() + .observationDigest() + .equals(preparation.mountedObservationDigest()) + || !publication.intent().configMapUid().equals(preparation.publicConfigMapUid()) + || !publication + .receipt() + .observedResourceVersion() + .equals(preparation.expectedPublicResourceVersion()) + || !publication.intent().apiBindingDigest().equals(preparation.apiBindingDigest()) + || !publication.intent().apiConfigRevision().equals(preparation.apiConfigRevision()) + || !publication.intent().jwksJson().equals(preparation.expectedPublicJwksJson())) { + throw new PromotionPrerequisitesIncompleteException( + "Account readiness proof does not match the exact generation and publication"); + } + if (preparedReplay != null + && (!preparedReplay.readinessPlanDigest().equals(plan.planDigest()) + || !preparedReplay.readinessEvidenceDigest().equals(proof.readinessEvidenceDigest()))) { + throw new IdempotencyConflictException( + "Readiness recovery proof changed for the exact PREPARED promotion"); + } + if (!plan.validatorInventoryComplete() + || proof.inventoryEvidenceReference() == null + || !proof.inventoryEvidenceReference().matches("[A-Za-z0-9][A-Za-z0-9._:/-]{0,511}") + || proof.inventoryEvidenceDigest() == null + || !proof.inventoryEvidenceDigest().matches("[0-9a-f]{64}") + || proof.verifiedProbes().isEmpty() + || !proof.readinessEvidenceDigest().matches("[0-9a-f]{64}") + || !publication.intent().operationId().equals(result.operationId()) + || !publication.receipt().operationId().equals(result.operationId()) + || !publication.mountedCorrespondence().operationId().equals(result.operationId()) + || !publication.intent().intentDigest().equals(plan.publicationIntentDigest()) + || !publication.receipt().receiptDigest().equals(plan.publicationReceiptDigest()) + || !publication + .mountedCorrespondence() + .observationDigest() + .equals(plan.mountedObservationDigest())) { + throw new PromotionPrerequisitesIncompleteException( + "Account readiness proof lacks exact publication or protected inventory evidence"); + } + } + + private GenerationRequest createGenerationRequest(DesiredState state, TrustFence trust) { + if (state.recordVersion() == Long.MAX_VALUE) { + throw new VersionConflictException("Account JWT signer state version is exhausted"); + } + long previousGeneration = + Math.max( + state.durableActive().map(value -> parseGeneration(value.generation())).orElse(0L), + state.publishedActive().map(value -> parseGeneration(value.generation())).orElse(0L)); + if (previousGeneration == Long.MAX_VALUE) { + throw new VersionConflictException("Account JWT signer generation is exhausted"); + } + long targetGeneration = previousGeneration + 1; + UUID operationId = UUID.randomUUID(); + String targetKid = "jwt-" + targetGeneration + "-" + operationId.toString().substring(0, 12); + StoredGenerationOperation operation = + StoredGenerationOperation.create(state, trust, operationId, targetGeneration, targetKid); + insertGenerationOperation(operation); + int changed = advanceToGenerationRequest(state, operationId); + if (changed != 1) { + throw new VersionConflictException( + "Account JWT signer state changed during request creation"); + } + Record readbackStateRow = selectState(state.binding().environmentId(), true); + Record readbackOperationRow = selectGenerationOperationRow(operationId, true); + if (readbackStateRow == null || readbackOperationRow == null) { + throw new QuarantinedStateException("Account JWT generation request did not read back"); + } + DesiredState readbackState = decodeState(readbackStateRow); + StoredGenerationOperation readbackOperation = decodeGenerationOperation(readbackOperationRow); + requireBinding(readbackState, state.binding()); + verifyOperationMatchesState(readbackOperation, readbackState); + if (!readbackOperation.equals(operation)) { + throw new QuarantinedStateException("Account JWT generation request changed on readback"); + } + return readGenerationRequest(readbackOperation, readbackState, true); + } + + private GenerationRequest readGenerationRequest( + StoredGenerationOperation operation, DesiredState state, boolean lockEvidence) { + GenerationResult result = selectGenerationResult(operation.operationId(), lockEvidence); + if (result != null) { + verifyGenerationResultMatchesOperation(result, operation, state); + return toGenerationRequest(operation, state, null, result); + } + SecretObservation observation = selectSecretObservation(operation.operationId(), lockEvidence); + if (observation != null) { + verifySecretObservationMatchesOperation(observation, operation, state); + } + return toGenerationRequest(operation, state, observation, null); + } + + private static void verifySecretObservationMatchesOperation( + SecretObservation observation, StoredGenerationOperation operation, DesiredState state) { + if (!observation.operationId().equals(operation.operationId()) + || !observation.binding().equals(operation.binding()) + || !observation.operationDigest().equals(operation.operationDigest()) + || observation.expectedRecordVersion() != operation.expectedRecordVersion() + || !observation.trustFence().equals(operation.trustFence()) + || state.recordVersion() != operation.expectedRecordVersion() + 1) { + throw new QuarantinedStateException( + "JWT signer Secret observation is not bound to its operation"); + } + } + + private static void verifyGenerationResultMatchesOperation( + GenerationResult result, StoredGenerationOperation operation, DesiredState state) { + if (!result.operationId().equals(operation.operationId()) + || !result.binding().equals(operation.binding()) + || !result.operationDigest().equals(operation.operationDigest()) + || !result.trustFence().equals(operation.trustFence()) + || result.desiredStateVersion() != state.recordVersion() + || !result.targetGeneration().equals(operation.targetGeneration()) + || !result.targetKid().equals(operation.targetKid()) + || !result.targetAlgorithm().equals(operation.targetAlgorithm())) { + throw new QuarantinedStateException( + "JWT signer generation result is not bound to its operation"); + } + } + + private GenerationRequest toGenerationRequest( + StoredGenerationOperation operation, + DesiredState state, + SecretObservation observation, + GenerationResult result) { + GenerationPhase phase = + result != null + ? GenerationPhase.GENERATION_RECORDED + : observation != null + ? GenerationPhase.GENERATE_PENDING + : GenerationPhase.OBSERVE_PRIVATE_SECRET; + return new GenerationRequest( + phase, + operation.operationId(), + operation.operationDigest(), + result != null + ? result.generationRequestDigest() + : observation == null ? "" : observation.generationRequestDigest(), + state.recordVersion(), + operation.binding(), + operation.trustFence(), + PRIVATE_SECRET_NAME, + operation.targetGeneration(), + operation.targetKid(), + operation.targetAlgorithm(), + ACTION, + List.of(PENDING_SLOT), + operation.expectedPreviousActive(), + operation.expectedPublishedActive(), + result != null ? result.secretUid() : observation == null ? "" : observation.secretUid(), + result != null + ? result.expectedPriorResourceVersion() + : observation == null ? "" : observation.observedResourceVersion(), + result == null ? "" : result.receiptDigest(), + result == null ? "" : result.publicKeyFingerprint(), + result == null ? "" : result.publicJwkJson(), + result == null ? "" : result.observedResourceVersion()); + } + + private LockedCurrent lockCurrentOperation( + Binding expectedBinding, TrustFence trust, UUID operationId) { + Record stateRow = selectState(expectedBinding.environmentId(), true); + if (stateRow == null) { + throw new MissingDesiredStateException(expectedBinding.environmentId()); + } + DesiredState state = decodeState(stateRow); + requireBinding(state, expectedBinding); + verifyPreparedIsUnavailable(state); + if (!state.generationOperationId().equals(Optional.of(operationId))) { + throw new StaleGenerationOperationException( + "JWT signer request does not target Account's current generation operation"); + } + StoredGenerationOperation operation = selectGenerationOperation(operationId, true); + if (operation == null) { + throw new QuarantinedStateException("Account JWT signer generation operation is missing"); + } + verifyOperationMatchesState(operation, state); + requireCurrentTrust(operation, trust); + return new LockedCurrent(state, operation); + } + + private void requireCurrentTrust(StoredGenerationOperation operation, TrustFence current) { + if (!operation.trustFence().equals(current)) { + throw new BindingMismatchException( + "JWT materializer trust or namespace incarnation changed for the generation operation"); + } + } + + private static void requireEnrollmentTrust(DesiredState state, TrustFence trust) { + EnrollmentIdentity enrolled = + state + .enrollmentIdentity() + .orElseThrow( + () -> + new QuarantinedStateException( + "Account JWT signer state has no independently protected enrollment identity")); + if (!enrolled.expectedClusterIncarnationUid().equals(trust.expectedClusterIncarnationUid()) + || !enrolled.expectedNamespaceUid().equals(trust.expectedNamespaceUid()) + || !enrolled.materializerTrustBindingDigest().equals(trust.bindingDigest()) + || !enrolled.materializerTrustConfigRevision().equals(trust.configRevision())) { + throw new BindingMismatchException( + "JWT materializer trust no longer matches Account's pinned enrollment"); + } + } + + private void verifyOperationMatchesState( + StoredGenerationOperation operation, DesiredState state) { + if (!state.generationOperationId().equals(Optional.of(operation.operationId())) + || !operation.binding().equals(state.binding()) + || operation.expectedRecordVersion() == Long.MAX_VALUE + || state.recordVersion() != operation.expectedRecordVersion() + 1 + || !operation.expectedPreviousActive().equals(state.durableActive()) + || !operation.expectedPublishedActive().equals(state.publishedActive()) + || !REQUEST_DIGEST_VERSION.equals(operation.digestVersion()) + || !generationOperationDigest(operation).equals(operation.operationDigest())) { + throw new QuarantinedStateException( + "Account JWT signer generation request does not match current desired state"); + } + } + + private Record selectState(String environmentId, boolean lock) { + return dsl.fetchOne( + "SELECT environment_id, cluster_id, kubernetes_namespace, custody_mode, " + + "private_secret_name, public_jwks_config_map_name, record_version, " + + "durable_active_generation, durable_active_kid, published_active_generation, " + + "published_active_kid, generation_operation_id, prepared_operation_id, " + + "enrollment_cluster_incarnation_uid, enrollment_namespace_uid, " + + "enrollment_materializer_binding_digest, enrollment_materializer_config_revision, " + + "enrollment_api_binding_digest, enrollment_api_config_revision, " + + "enrollment_public_config_map_uid, enrollment_public_config_map_resource_version, " + + "enrollment_public_config_map_snapshot_digest FROM " + + STATE_TABLE + + " WHERE environment_id = ?" + + (lock ? " FOR UPDATE" : ""), + environmentId); + } + + private StoredPromotion selectPromotion(UUID operationId, boolean lock) { + Record row = + dsl.fetchOne( + "SELECT p.operation_id, p.environment_id, p.cluster_id, p.kubernetes_namespace, p.custody_mode, " + + "p.request_digest_version, p.request_digest, p.expected_record_version, " + + "p.expected_previous_generation, p.expected_previous_kid, p.target_generation, p.target_kid, " + + "p.target_algorithm, p.target_public_key_fingerprint, " + + "p.expected_private_secret_resource_version, p.expected_public_jwks_resource_version, " + + "p.expected_public_active_generation, p.expected_public_active_kid, p.operation_action, " + + "p.allowed_private_slots_canonical_bytes, p.status, p.generation_operation_id, " + + "p.expected_cluster_incarnation_uid, p.expected_namespace_uid, " + + "p.materializer_trust_binding_digest, p.materializer_trust_config_revision, " + + "p.api_binding_digest, p.api_config_revision, p.expected_private_secret_uid, " + + "p.expected_public_config_map_uid, p.prepublication_intent_digest, " + + "p.prepublication_receipt_digest, p.mounted_observation_digest, p.readiness_plan_digest, " + + "p.readiness_evidence_digest, p.expected_public_jwks_json, " + + "p.expected_active_generation_marker_json, " + + "(p.private_promotion_dispatched_at IS NOT NULL) AS private_promotion_dispatched, " + + "p.private_promotion_observed_resource_version, " + + "p.private_promotion_receipt_digest, p.active_jwks_observed_resource_version, " + + "p.active_jwks_public_data_digest, p.active_jwks_receipt_digest, " + + "generation.operation_digest AS generation_operation_digest, " + + "generation_result.receipt_digest AS generation_receipt_digest " + + "FROM " + + PROMOTION_TABLE + + " AS p " + + "JOIN " + + OPERATION_TABLE + + " AS generation " + + "ON generation.operation_id = p.generation_operation_id " + + "JOIN " + + RESULT_TABLE + + " AS generation_result " + + "ON generation_result.operation_id = p.generation_operation_id " + + "WHERE p.operation_id = ?" + + (lock ? " FOR UPDATE OF p, generation, generation_result" : ""), + operationId); + return row == null ? null : decodePromotion(row); + } + + private StoredPromotion selectCommittedPromotion(DesiredState state, ActiveSigner active) { + Result rows = + dsl.fetch( + "SELECT operation_id FROM " + + PROMOTION_TABLE + + " WHERE environment_id = ? AND cluster_id = ? AND kubernetes_namespace = ? " + + "AND custody_mode = ? AND status = 'COMMITTED' AND target_generation = ? " + + "AND target_kid = ? ORDER BY created_at DESC LIMIT 2", + state.binding().environmentId(), + state.binding().clusterId(), + state.binding().namespace(), + state.binding().mode().value(), + parseGeneration(active.generation()), + active.kid()); + if (rows.size() != 1) { + throw new QuarantinedStateException( + "Account active signer does not resolve to exactly one committed promotion"); + } + UUID operationId = rows.get(0).get("operation_id", UUID.class); + return selectPromotion(operationId, false); + } + + private static void requireCommittedStateMatches(StoredPromotion promotion, DesiredState state) { + ActiveSigner expected = new ActiveSigner(promotion.targetGeneration(), promotion.targetKid()); + if (!"COMMITTED".equals(promotion.status()) + || !promotion.binding().equals(state.binding()) + || state.preparedOperationId().isPresent() + || state.generationOperationId().isPresent() + || state.durableActive().filter(expected::equals).isEmpty() + || state.publishedActive().filter(expected::equals).isEmpty() + || promotion.expectedRecordVersion() > Long.MAX_VALUE - 2 + || state.recordVersion() != promotion.expectedRecordVersion() + 2 + || promotion.privatePromotionReceiptDigest() == null + || promotion.activeJwksReceiptDigest() == null) { + throw new QuarantinedStateException( + "Committed Account signer does not match its exact operation and active fences"); + } + } + + private static void requireCommittedActiveStillCurrent( + StoredPromotion promotion, DesiredState state) { + ActiveSigner expected = new ActiveSigner(promotion.targetGeneration(), promotion.targetKid()); + if (!"COMMITTED".equals(promotion.status()) + || !promotion.binding().equals(state.binding()) + || state.preparedOperationId().isPresent() + || state.durableActive().filter(expected::equals).isEmpty() + || state.publishedActive().filter(expected::equals).isEmpty() + || promotion.expectedRecordVersion() > Long.MAX_VALUE - 2 + || state.recordVersion() < promotion.expectedRecordVersion() + 2) { + throw new QuarantinedStateException( + "Committed Account promotion is not the current active signer"); + } + } + + private static void requireActiveJwksObservation( + StoredPromotion promotion, ActiveJwksPromotionObservation observation) { + if (!promotion.publicConfigMapUid().equals(observation.configMapUid()) + || !promotion.expectedPublicResourceVersion().equals(observation.priorResourceVersion()) + || observation.priorResourceVersion().equals(observation.observedResourceVersion()) + || !promotion.expectedPublicJwksJson().equals(observation.jwksJson()) + || !promotion.expectedActiveMarkerJson().equals(observation.activeMarkerJson())) { + throw new QuarantinedStateException( + "Account ConfigMap CAS did not read back the exact authorized ACTIVE projection"); + } + requireActiveMarkerMatchesPromotion(promotion, observation.activeMarkerJson()); + } + + private static void requireActiveMarkerMatchesPromotion( + StoredPromotion promotion, String marker) { + try { + JsonNode root = STRICT_JSON.readTree(marker); + if (root == null + || !root.isObject() + || root.size() != 11 + || !root.path("schemaVersion").isIntegralNumber() + || root.path("schemaVersion").intValue() != 1 + || !"ACTIVE".equals(requiredText(root, "phase", 16)) + || !promotion + .generationOperationId() + .toString() + .equals(requiredText(root, "operationId", 36)) + || !promotion + .generationOperationDigest() + .equals(requiredText(root, "operationDigest", 64)) + || !promotion + .generationReceiptDigest() + .equals(requiredText(root, "generationReceiptDigest", 64)) + || !markerBindingMatches(promotion, root.get("binding")) + || !markerFenceMatches( + promotion, root.get("expectedDurableActive"), promotion.expectedPreviousActive()) + || !markerFenceMatches( + promotion, root.get("expectedPublishedActive"), promotion.expectedPublishedActive()) + || !markerPublicMapMatches(root.get("publicConfigMap")) + || !markerPromotionMatches(promotion, root.get("promotion"))) { + throw new IllegalArgumentException("Active marker mismatch"); + } + JsonNode active = root.get("active"); + if (active == null + || !active.isObject() + || active.size() != 4 + || !promotion.targetGeneration().equals(requiredText(active, "generation", 19)) + || !promotion.targetKid().equals(requiredText(active, "kid", 64)) + || !ALGORITHM.equals(requiredText(active, "algorithm", 16)) + || !promotion + .targetPublicKeyFingerprint() + .equals(requiredText(active, "publicKeyFingerprint", 64))) { + throw new IllegalArgumentException("Active signer mismatch"); + } + } catch (RuntimeException ex) { + throw new QuarantinedStateException("Account ACTIVE generation marker is malformed", ex); + } + } + + private static boolean markerBindingMatches(StoredPromotion promotion, JsonNode binding) { + return binding != null + && binding.isObject() + && binding.size() == 9 + && promotion.binding().environmentId().equals(requiredText(binding, "environmentId", 64)) + && promotion.binding().clusterId().equals(requiredText(binding, "clusterId", 128)) + && promotion.binding().namespace().equals(requiredText(binding, "namespace", 64)) + && promotion + .trustFence() + .expectedClusterIncarnationUid() + .equals(requiredText(binding, "expectedClusterIncarnationUid", 36)) + && promotion + .trustFence() + .expectedNamespaceUid() + .equals(requiredText(binding, "expectedNamespaceUid", 36)) + && promotion + .trustFence() + .bindingDigest() + .equals(requiredText(binding, "trustBindingDigest", 64)) + && promotion + .trustFence() + .configRevision() + .equals(requiredText(binding, "trustConfigRevision", 128)) + && promotion.apiBindingDigest().equals(requiredText(binding, "apiBindingDigest", 64)) + && promotion.apiConfigRevision().equals(requiredText(binding, "apiConfigRevision", 128)); + } + + private static boolean markerFenceMatches( + StoredPromotion promotion, JsonNode fence, Optional expected) { + return fence != null && parseMarkerActive(fence).equals(expected); + } + + private static Optional parseMarkerActive(JsonNode fence) { + if (fence == null || !fence.isObject()) { + throw new IllegalArgumentException("Active marker fence is malformed"); + } + if (fence.size() == 1 + && fence.path("present").isBoolean() + && !fence.path("present").booleanValue()) { + return Optional.empty(); + } + if (fence.size() == 3 + && fence.path("present").isBoolean() + && fence.path("present").booleanValue()) { + return Optional.of( + new ActiveSigner(requiredText(fence, "generation", 19), requiredText(fence, "kid", 64))); + } + throw new IllegalArgumentException("Active marker fence is malformed"); + } + + private static boolean markerPublicMapMatches(JsonNode publicMap) { + return publicMap != null + && publicMap.isObject() + && publicMap.size() == 1 + && PUBLIC_JWKS_CONFIG_MAP_NAME.equals(requiredText(publicMap, "name", 64)); + } + + private static boolean markerPromotionMatches(StoredPromotion promotion, JsonNode proof) { + return proof != null + && proof.isObject() + && proof.size() == 7 + && promotion.operationId().toString().equals(requiredText(proof, "operationId", 36)) + && promotion.requestDigest().equals(requiredText(proof, "requestDigest", 64)) + && promotion + .prepublicationIntentDigest() + .equals(requiredText(proof, "prepublicationIntentDigest", 64)) + && promotion + .prepublicationReceiptDigest() + .equals(requiredText(proof, "prepublicationReceiptDigest", 64)) + && promotion + .mountedObservationDigest() + .equals(requiredText(proof, "mountedObservationDigest", 64)) + && promotion.readinessPlanDigest().equals(requiredText(proof, "readinessPlanDigest", 64)) + && promotion + .readinessEvidenceDigest() + .equals(requiredText(proof, "readinessEvidenceDigest", 64)); + } + + private static String activeMarkerJson(StoredPromotion promotion) { + Map marker = new LinkedHashMap<>(); + marker.put("schemaVersion", 1); + marker.put("phase", "ACTIVE"); + marker.put("operationId", promotion.generationOperationId().toString()); + marker.put("operationDigest", promotion.generationOperationDigest()); + marker.put("generationReceiptDigest", promotion.generationReceiptDigest()); + Map binding = new LinkedHashMap<>(); + binding.put("environmentId", promotion.binding().environmentId()); + binding.put("clusterId", promotion.binding().clusterId()); + binding.put("namespace", promotion.binding().namespace()); + binding.put( + "expectedClusterIncarnationUid", promotion.trustFence().expectedClusterIncarnationUid()); + binding.put("expectedNamespaceUid", promotion.trustFence().expectedNamespaceUid()); + binding.put("trustBindingDigest", promotion.trustFence().bindingDigest()); + binding.put("trustConfigRevision", promotion.trustFence().configRevision()); + binding.put("apiBindingDigest", promotion.apiBindingDigest()); + binding.put("apiConfigRevision", promotion.apiConfigRevision()); + marker.put("binding", binding); + marker.put("publicConfigMap", Map.of("name", PUBLIC_JWKS_CONFIG_MAP_NAME)); + marker.put("expectedDurableActive", activeMarker(promotion.expectedPreviousActive())); + marker.put("expectedPublishedActive", activeMarker(promotion.expectedPublishedActive())); + marker.put( + "active", + Map.of( + "generation", promotion.targetGeneration(), + "kid", promotion.targetKid(), + "algorithm", promotion.targetAlgorithm(), + "publicKeyFingerprint", promotion.targetPublicKeyFingerprint())); + marker.put( + "promotion", + Map.of( + "operationId", promotion.operationId().toString(), + "requestDigest", promotion.requestDigest(), + "prepublicationIntentDigest", promotion.prepublicationIntentDigest(), + "prepublicationReceiptDigest", promotion.prepublicationReceiptDigest(), + "mountedObservationDigest", promotion.mountedObservationDigest(), + "readinessPlanDigest", promotion.readinessPlanDigest(), + "readinessEvidenceDigest", promotion.readinessEvidenceDigest())); + try { + return new String( + Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(marker)), + StandardCharsets.UTF_8); + } catch (IOException ex) { + throw new StorageUnavailableException("Account ACTIVE JWT marker could not be canonicalized"); + } + } + + private static Map activeMarker(Optional active) { + Map marker = new LinkedHashMap<>(); + marker.put("present", active.isPresent()); + active.ifPresent( + signer -> { + marker.put("generation", signer.generation()); + marker.put("kid", signer.kid()); + }); + return marker; + } + + private static String requiredText(JsonNode object, String name, int maxLength) { + JsonNode value = object.get(name); + if (value == null + || !value.isTextual() + || value.textValue().isEmpty() + || value.textValue().length() > maxLength) { + throw new IllegalArgumentException("Account JWT signer JSON field is malformed"); + } + return value.textValue(); + } + + private static void requirePromotionMatchesState(StoredPromotion promotion, DesiredState state) { + if (!promotion.binding().equals(state.binding()) + || !state.preparedOperationId().equals(Optional.of(promotion.operationId())) + || state.generationOperationId().isPresent() + || state.recordVersion() != promotion.expectedRecordVersion() + 1 + || !promotion.expectedPreviousActive().equals(state.durableActive()) + || !promotion.expectedPublishedActive().equals(state.publishedActive()) + || !promotion.requestDigest().equals(promotionRequestDigest(promotion))) { + throw new QuarantinedStateException( + "Account PREPARED promotion does not match its exact desired-state fence"); + } + } + + private static void requireCurrentTrust(StoredPromotion promotion, TrustFence current) { + if (!promotion.trustFence().equals(current)) { + throw new BindingMismatchException( + "JWT materializer trust or namespace incarnation changed during promotion"); + } + } + + private static void verifyPreparedGenerationMatches( + StoredPromotion promotion, StoredGenerationOperation operation, GenerationResult result) { + if (!promotion.generationOperationId().equals(operation.operationId()) + || !promotion.binding().equals(operation.binding()) + || !promotion.operationDigestForGeneration().equals(operation.operationDigest()) + || !promotion.expectedPreviousActive().equals(operation.expectedPreviousActive()) + || !promotion.expectedPublishedActive().equals(operation.expectedPublishedActive()) + || !promotion.targetGeneration().equals(operation.targetGeneration()) + || !promotion.targetKid().equals(operation.targetKid()) + || !ALGORITHM.equals(operation.targetAlgorithm()) + || !promotion.trustFence().equals(operation.trustFence()) + || !promotion.generationOperationId().equals(result.operationId()) + || !promotion.generationReceiptDigest().equals(result.receiptDigest()) + || !promotion.secretUid().equals(result.secretUid()) + || !promotion.expectedPrivateResourceVersion().equals(result.observedResourceVersion()) + || !promotion.targetPublicKeyFingerprint().equals(result.publicKeyFingerprint())) { + throw new QuarantinedStateException( + "Prepared promotion is not bound to the exact source generation result"); + } + } + + private static void requirePrivatePromotionObservation( + StoredPromotion promotion, PrivatePromotionObservation observation) { + Optional expectedPrevious = + promotion + .expectedPreviousActive() + .map( + active -> + new PublicKeyIdentity( + active.generation(), + active.kid(), + publicFingerprintForKid(promotion.expectedPublicJwksJson(), active.kid()))); + PublicKeyIdentity expectedCurrent = + new PublicKeyIdentity( + promotion.targetGeneration(), + promotion.targetKid(), + promotion.targetPublicKeyFingerprint()); + List expectedSlots = + expectedPrevious.isPresent() ? List.of("current", "previous") : List.of("current"); + if (!observation.secretUid().equals(promotion.secretUid()) + || !observation + .expectedPriorResourceVersion() + .equals(promotion.expectedPrivateResourceVersion()) + || observation.expectedPriorResourceVersion().equals(observation.observedResourceVersion()) + || !expectedCurrent.equals(observation.current()) + || !expectedPrevious.equals(observation.previous()) + || !expectedSlots.equals(observation.resultingSlots())) { + throw new QuarantinedStateException( + "Materializer did not read back the exact authorized private slot transition"); + } + } + + private static String publicFingerprintForKid(String jwksJson, String kid) { + try { + JsonNode root = STRICT_JSON.readTree(jwksJson); + JsonNode keys = root == null ? null : root.get("keys"); + if (keys == null || !keys.isArray()) { + throw new IllegalArgumentException("JWKS keys are malformed"); + } + String found = null; + for (JsonNode key : keys) { + if (key != null && key.isObject() && kid.equals(requiredText(key, "kid", 64))) { + if (found != null) { + throw new IllegalArgumentException("JWKS contains a duplicate kid"); + } + found = + digest( + Map.of( + "e", + requiredText(key, "e", 16), + "kty", + "RSA", + "n", + requiredText(key, "n", 4096))); + } + } + if (found == null) { + throw new IllegalArgumentException("Expected prior public key is missing from JWKS"); + } + return found; + } catch (Exception ex) { + throw new QuarantinedStateException("Expected prior public key identity is unavailable", ex); + } + } + + private StoredPromotion decodePromotion(Record row) { + try { + byte[] slots = row.get("allowed_private_slots_canonical_bytes", byte[].class); + if (!Arrays.equals(PROMOTION_SLOTS_CANONICAL_BYTES, slots) + || !"PROMOTE_PENDING".equals(row.get("operation_action", String.class))) { + throw new QuarantinedStateException( + "Account promotion action or fixed Secret slots are malformed"); + } + StoredPromotion promotion = + new StoredPromotion( + row.get("operation_id", UUID.class), + new Binding( + row.get("environment_id", String.class), + row.get("cluster_id", String.class), + row.get("kubernetes_namespace", String.class), + CustodyMode.fromValue(row.get("custody_mode", String.class))), + Math.toIntExact( + positive( + row.get("request_digest_version", Short.class).longValue(), + "promotion digest version")), + row.get("request_digest", String.class), + positive( + row.get("expected_record_version", Long.class), "expected signer state version"), + activeOptional( + row.get("expected_previous_generation", Long.class), + row.get("expected_previous_kid", String.class), + "previous signer"), + activeOptional( + row.get("expected_public_active_generation", Long.class), + row.get("expected_public_active_kid", String.class), + "published previous signer"), + canonicalGeneration( + row.get("target_generation", Long.class), "promotion target generation"), + row.get("target_kid", String.class), + row.get("target_algorithm", String.class), + row.get("target_public_key_fingerprint", String.class), + row.get("expected_private_secret_resource_version", String.class), + row.get("expected_public_jwks_resource_version", String.class), + new TrustFence( + row.get("expected_cluster_incarnation_uid", UUID.class).toString(), + row.get("expected_namespace_uid", UUID.class).toString(), + row.get("materializer_trust_binding_digest", String.class), + row.get("materializer_trust_config_revision", String.class)), + row.get("generation_operation_id", UUID.class), + row.get("generation_operation_digest", String.class), + row.get("generation_receipt_digest", String.class), + row.get("api_binding_digest", String.class), + row.get("api_config_revision", String.class), + row.get("expected_private_secret_uid", UUID.class).toString(), + row.get("expected_public_config_map_uid", UUID.class).toString(), + row.get("prepublication_intent_digest", String.class), + row.get("prepublication_receipt_digest", String.class), + row.get("mounted_observation_digest", String.class), + row.get("readiness_plan_digest", String.class), + row.get("readiness_evidence_digest", String.class), + row.get("expected_public_jwks_json", String.class), + row.get("expected_active_generation_marker_json", String.class), + row.get("status", String.class), + Boolean.TRUE.equals(row.get("private_promotion_dispatched", Boolean.class)), + row.get("private_promotion_observed_resource_version", String.class), + row.get("private_promotion_receipt_digest", String.class), + row.get("active_jwks_observed_resource_version", String.class), + row.get("active_jwks_public_data_digest", String.class), + row.get("active_jwks_receipt_digest", String.class)); + if (promotion.requestDigestVersion() != 1 + || !promotionRequestDigest(promotion).equals(promotion.requestDigest())) { + throw new QuarantinedStateException("Account promotion operation digest is invalid"); + } + return promotion; + } catch (RuntimeException ex) { + if (ex instanceof QuarantinedStateException) { + throw ex; + } + throw new QuarantinedStateException("Account promotion operation is malformed", ex); + } + } + + private static String promotionRequestDigest(StoredPromotion promotion) { + Map preimage = new LinkedHashMap<>(); + preimage.put("digestVersion", PROMOTION_DIGEST_VERSION); + preimage.put("operationId", promotion.operationId().toString()); + preimage.put("generationOperationId", promotion.generationOperationId().toString()); + preimage.put("generationOperationDigest", promotion.generationOperationDigest()); + preimage.put("generationReceiptDigest", promotion.generationReceiptDigest()); + preimage.put("environmentId", promotion.binding().environmentId()); + preimage.put("clusterId", promotion.binding().clusterId()); + preimage.put("namespace", promotion.binding().namespace()); + preimage.put("custodyMode", promotion.binding().mode().value()); + preimage.put("expectedRecordVersion", Long.toString(promotion.expectedRecordVersion())); + preimage.put("expectedPreviousActive", activeDigestValue(promotion.expectedPreviousActive())); + preimage.put("expectedPublishedActive", activeDigestValue(promotion.expectedPublishedActive())); + preimage.put("targetGeneration", promotion.targetGeneration()); + preimage.put("targetKid", promotion.targetKid()); + preimage.put("targetAlgorithm", ALGORITHM); + preimage.put("targetPublicKeyFingerprint", promotion.targetPublicKeyFingerprint()); + preimage.put("expectedPrivateSecretUid", promotion.secretUid()); + preimage.put( + "expectedPrivateSecretResourceVersion", promotion.expectedPrivateResourceVersion()); + preimage.put("expectedPublicConfigMapUid", promotion.publicConfigMapUid()); + preimage.put("expectedPublicJwksResourceVersion", promotion.expectedPublicResourceVersion()); + preimage.put( + "expectedClusterIncarnationUid", promotion.trustFence().expectedClusterIncarnationUid()); + preimage.put("expectedNamespaceUid", promotion.trustFence().expectedNamespaceUid()); + preimage.put("materializerTrustBindingDigest", promotion.trustFence().bindingDigest()); + preimage.put("materializerTrustConfigRevision", promotion.trustFence().configRevision()); + preimage.put("apiBindingDigest", promotion.apiBindingDigest()); + preimage.put("apiConfigRevision", promotion.apiConfigRevision()); + preimage.put("prepublicationIntentDigest", promotion.prepublicationIntentDigest()); + preimage.put("prepublicationReceiptDigest", promotion.prepublicationReceiptDigest()); + preimage.put("mountedObservationDigest", promotion.mountedObservationDigest()); + preimage.put("readinessPlanDigest", promotion.readinessPlanDigest()); + preimage.put("readinessEvidenceDigest", promotion.readinessEvidenceDigest()); + preimage.put("publicJwksSha256", sha256(promotion.expectedPublicJwksJson())); + preimage.put("operationAction", "PROMOTE_PENDING"); + preimage.put("allowedPrivateSlots", List.of("current", "pending", "previous")); + return digest(preimage); + } + + private Record selectGenerationOperationRow(UUID operationId, boolean lock) { + return dsl.fetchOne( + "SELECT operation_id, environment_id, cluster_id, kubernetes_namespace, custody_mode, " + + "operation_digest_version, operation_digest, expected_record_version, " + + "expected_previous_generation, expected_previous_kid, " + + "expected_published_generation, expected_published_kid, target_generation, target_kid, " + + "target_algorithm, expected_cluster_incarnation_uid, expected_namespace_uid, " + + "trust_binding_digest, trust_config_revision, operation_action, " + + "allowed_private_slots_canonical_bytes FROM " + + OPERATION_TABLE + + " WHERE operation_id = ?" + + (lock ? " FOR UPDATE" : ""), + operationId); + } + + private StoredGenerationOperation selectGenerationOperation(UUID operationId, boolean lock) { + Record row = selectGenerationOperationRow(operationId, lock); + return row == null ? null : decodeGenerationOperation(row); + } + + private SecretObservation selectSecretObservation(UUID operationId, boolean lock) { + Record row = + dsl.fetchOne( + "SELECT operation_id, environment_id, cluster_id, kubernetes_namespace, custody_mode, " + + "operation_digest, expected_record_version, expected_cluster_incarnation_uid, " + + "expected_namespace_uid, trust_binding_digest, trust_config_revision, " + + "private_secret_name, secret_uid, observed_resource_version, observation_digest, " + + "generation_request_digest FROM " + + OBSERVATION_TABLE + + " WHERE operation_id = ?" + + (lock ? " FOR UPDATE" : ""), + operationId); + return row == null ? null : decodeSecretObservation(row); + } + + private GenerationResult selectGenerationResult(UUID operationId, boolean lock) { + Record row = + dsl.fetchOne( + "SELECT operation_id, environment_id, cluster_id, kubernetes_namespace, custody_mode, " + + "operation_digest, generation_request_digest, desired_state_version, " + + "expected_cluster_incarnation_uid, expected_namespace_uid, trust_binding_digest, " + + "trust_config_revision, private_secret_name, secret_uid, " + + "expected_prior_resource_version, observed_resource_version, target_generation, " + + "target_kid, target_algorithm, public_key_fingerprint, public_jwk_json, receipt_digest " + + "FROM " + + RESULT_TABLE + + " WHERE operation_id = ?" + + (lock ? " FOR UPDATE" : ""), + operationId); + return row == null ? null : decodeGenerationResult(row); + } + + private void insertGenerationOperation(StoredGenerationOperation operation) { + int inserted = + dsl.execute( + "INSERT INTO " + + OPERATION_TABLE + + " (operation_id, environment_id, cluster_id, kubernetes_namespace, custody_mode, " + + "operation_digest_version, operation_digest, expected_record_version, " + + "expected_previous_generation, expected_previous_kid, " + + "expected_published_generation, expected_published_kid, target_generation, target_kid, " + + "target_algorithm, expected_cluster_incarnation_uid, expected_namespace_uid, " + + "trust_binding_digest, trust_config_revision, operation_action, " + + "allowed_private_slots_canonical_bytes) " + + "VALUES (?, ?, ?, ?, ?, 1, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'MATERIALIZE_PENDING', ?) ", + operation.operationId(), + operation.binding().environmentId(), + operation.binding().clusterId(), + operation.binding().namespace(), + operation.binding().mode().value(), + operation.operationDigest(), + operation.expectedRecordVersion(), + generationValue(operation.expectedPreviousActive()), + kidValue(operation.expectedPreviousActive()), + generationValue(operation.expectedPublishedActive()), + kidValue(operation.expectedPublishedActive()), + parseGeneration(operation.targetGeneration()), + operation.targetKid(), + operation.targetAlgorithm(), + UUID.fromString(operation.trustFence().expectedClusterIncarnationUid()), + UUID.fromString(operation.trustFence().expectedNamespaceUid()), + operation.trustFence().bindingDigest(), + operation.trustFence().configRevision(), + PENDING_SLOT_CANONICAL_BYTES); + if (inserted != 1) { + throw new StorageUnavailableException( + "Account JWT generation operation insert was ambiguous"); + } + } + + private void requireCurrentPublicationForPreparation( + GenerationResult result, PromotionPreparation preparation) { + Record evidence = + dsl.fetchOne( + "SELECT intent.operation_id, intent.intent_digest, intent.environment_id, intent.cluster_id, " + + "intent.kubernetes_namespace, intent.custody_mode, intent.operation_digest, " + + "intent.generation_request_digest, intent.generation_receipt_digest, " + + "intent.desired_state_version, intent.expected_cluster_incarnation_uid, " + + "intent.expected_namespace_uid, intent.trust_binding_digest, " + + "intent.trust_config_revision, intent.api_binding_digest, intent.api_config_revision, " + + "intent.config_map_name, intent.config_map_uid, intent.jwks_json, " + + "receipt.receipt_digest, receipt.observed_resource_version, " + + "mount.observation_digest FROM account_jwt_jwks_prepublication_intents AS intent " + + "JOIN account_jwt_jwks_publication_receipts AS receipt " + + "ON receipt.operation_id = intent.operation_id " + + "AND receipt.intent_digest = intent.intent_digest " + + "JOIN account_jwt_jwks_mount_observations AS mount " + + "ON mount.operation_id = intent.operation_id " + + "WHERE intent.operation_id = ? FOR UPDATE OF intent, receipt, mount", + result.operationId()); + if (evidence == null + || !preparation + .prepublicationIntentDigest() + .equals(evidence.get("intent_digest", String.class)) + || !preparation + .prepublicationReceiptDigest() + .equals(evidence.get("receipt_digest", String.class)) + || !preparation + .mountedObservationDigest() + .equals(evidence.get("observation_digest", String.class)) + || !preparation + .publicConfigMapUid() + .equals(evidence.get("config_map_uid", UUID.class).toString()) + || !preparation + .expectedPublicResourceVersion() + .equals(evidence.get("observed_resource_version", String.class)) + || !preparation.apiBindingDigest().equals(evidence.get("api_binding_digest", String.class)) + || !preparation + .apiConfigRevision() + .equals(evidence.get("api_config_revision", String.class)) + || !preparation.expectedPublicJwksJson().equals(evidence.get("jwks_json", String.class)) + || !result.operationId().equals(evidence.get("operation_id", UUID.class)) + || !result.operationDigest().equals(evidence.get("operation_digest", String.class)) + || !result + .generationRequestDigest() + .equals(evidence.get("generation_request_digest", String.class)) + || !result.receiptDigest().equals(evidence.get("generation_receipt_digest", String.class)) + || result.desiredStateVersion() != evidence.get("desired_state_version", Long.class)) { + throw new PromotionPrerequisitesIncompleteException( + "Exact Account JWKS prepublication, API readback, or mount receipt is unavailable"); + } + } + + private void requireCurrentReadinessForPreparation( + GenerationResult result, PromotionPreparation preparation) { + Record plan = + dsl.fetchOne( + "SELECT plan_digest, operation_digest, generation_request_digest, " + + "generation_receipt_digest, desired_state_version, target_generation, target_kid, " + + "target_public_key_fingerprint, publication_intent_digest, " + + "publication_receipt_digest, mounted_observation_digest, " + + "validator_inventory_complete, expires_at_epoch_seconds " + + "FROM account_jwt_readiness_probe_plans WHERE rotation_operation_id = ? " + + "AND plan_digest = ? FOR UPDATE", + result.operationId(), + preparation.readinessPlanDigest()); + if (plan == null + || !Boolean.TRUE.equals(plan.get("validator_inventory_complete", Boolean.class)) + || plan.get("expires_at_epoch_seconds", Long.class) == null + || plan.get("expires_at_epoch_seconds", Long.class) == null + || !result.operationDigest().equals(plan.get("operation_digest", String.class)) + || !result + .generationRequestDigest() + .equals(plan.get("generation_request_digest", String.class)) + || !result.receiptDigest().equals(plan.get("generation_receipt_digest", String.class)) + || result.desiredStateVersion() != plan.get("desired_state_version", Long.class) + || !result + .targetGeneration() + .equals(String.valueOf(plan.get("target_generation", Long.class))) + || !result.targetKid().equals(plan.get("target_kid", String.class)) + || !result + .publicKeyFingerprint() + .equals(plan.get("target_public_key_fingerprint", String.class)) + || !preparation + .prepublicationIntentDigest() + .equals(plan.get("publication_intent_digest", String.class)) + || !preparation + .prepublicationReceiptDigest() + .equals(plan.get("publication_receipt_digest", String.class)) + || !preparation + .mountedObservationDigest() + .equals(plan.get("mounted_observation_digest", String.class))) { + throw new PromotionPrerequisitesIncompleteException( + "Complete current Account JWT readiness proof is unavailable"); + } + Record entries = + dsl.fetchOne( + "SELECT count(*) AS total, count(*) FILTER (WHERE state = 'VERIFIED' " + + "AND verification_receipt_sha256 IS NOT NULL " + + "AND verified_at_epoch_seconds < expires_at_epoch_seconds) AS verified " + + "FROM account_jwt_readiness_probe_entries WHERE rotation_operation_id = ? " + + "AND plan_digest = ? AND EXISTS (SELECT 1 FROM account_jwt_readiness_probe_plans " + + "WHERE rotation_operation_id = ? AND plan_digest = ? " + + "AND expires_at_epoch_seconds > floor(extract(epoch FROM CURRENT_TIMESTAMP))::BIGINT)", + result.operationId(), + preparation.readinessPlanDigest(), + result.operationId(), + preparation.readinessPlanDigest()); + if (entries == null + || entries.get("total", Long.class) == null + || entries.get("total", Long.class) <= 0 + || !entries.get("total", Long.class).equals(entries.get("verified", Long.class))) { + throw new PromotionPrerequisitesIncompleteException( + "Every exact current Account JWT validator probe must be VERIFIED"); + } + } + + /** + * Rechecks the owner-created typed proof at the durable COMMITTED boundary. A proof read before + * this transaction is insufficient: the plan and every VERIFIED entry must still be inside their + * recorded validity window when Account commits the promotion. + */ + private void requireUnexpiredCurrentReadinessProof( + StoredPromotion promotion, GenerationResult result, ReadinessPromotionProof proof) { + var expectedPlan = proof.plan(); + Record currentPlan = + dsl.fetchOne( + "SELECT plan_digest, operation_digest, generation_request_digest, " + + "generation_receipt_digest, desired_state_version, target_generation, target_kid, " + + "target_public_key_fingerprint, publication_intent_digest, " + + "publication_receipt_digest, mounted_observation_digest, " + + "applicability_matrix_digest, validator_inventory_complete, " + + "maximum_cache_age_seconds, not_before_epoch_seconds, expires_at_epoch_seconds, " + + "floor(extract(epoch FROM clock_timestamp()))::bigint AS checked_epoch " + + "FROM account_jwt_readiness_probe_plans WHERE rotation_operation_id = ? " + + "AND plan_digest = ? FOR UPDATE", + result.operationId(), + promotion.readinessPlanDigest()); + if (currentPlan == null + || !Boolean.TRUE.equals(currentPlan.get("validator_inventory_complete", Boolean.class)) + || !promotion.readinessPlanDigest().equals(currentPlan.get("plan_digest", String.class)) + || !result.operationDigest().equals(currentPlan.get("operation_digest", String.class)) + || !result + .generationRequestDigest() + .equals(currentPlan.get("generation_request_digest", String.class)) + || !result + .receiptDigest() + .equals(currentPlan.get("generation_receipt_digest", String.class)) + || result.desiredStateVersion() != currentPlan.get("desired_state_version", Long.class) + || !result + .targetGeneration() + .equals(String.valueOf(currentPlan.get("target_generation", Long.class))) + || !result.targetKid().equals(currentPlan.get("target_kid", String.class)) + || !result + .publicKeyFingerprint() + .equals(currentPlan.get("target_public_key_fingerprint", String.class)) + || !promotion + .prepublicationIntentDigest() + .equals(currentPlan.get("publication_intent_digest", String.class)) + || !promotion + .prepublicationReceiptDigest() + .equals(currentPlan.get("publication_receipt_digest", String.class)) + || !promotion + .mountedObservationDigest() + .equals(currentPlan.get("mounted_observation_digest", String.class)) + || !expectedPlan + .applicabilityMatrixDigest() + .equals(currentPlan.get("applicability_matrix_digest", String.class)) + || expectedPlan.maximumCacheAgeSeconds() + != currentPlan.get("maximum_cache_age_seconds", Short.class) + || expectedPlan.notBeforeEpochSecond() + != currentPlan.get("not_before_epoch_seconds", Long.class) + || expectedPlan.expiresAtEpochSecond() + != currentPlan.get("expires_at_epoch_seconds", Long.class) + || currentPlan.get("checked_epoch", Long.class) == null + || currentPlan.get("checked_epoch", Long.class) < expectedPlan.notBeforeEpochSecond() + || currentPlan.get("checked_epoch", Long.class) >= expectedPlan.expiresAtEpochSecond()) { + throw new PromotionPrerequisitesIncompleteException( + "Exact Account readiness proof is missing, changed, or expired at commit"); + } + + Record currentEntries = + dsl.fetchOne( + "SELECT count(*) AS total, count(*) FILTER (WHERE state = 'VERIFIED' " + + "AND verification_receipt_sha256 IS NOT NULL " + + "AND verified_at_epoch_seconds < expires_at_epoch_seconds " + + "AND expires_at_epoch_seconds > floor(extract(epoch FROM clock_timestamp()))::bigint) " + + "AS verified FROM account_jwt_readiness_probe_entries " + + "WHERE rotation_operation_id = ? AND plan_digest = ?", + result.operationId(), + promotion.readinessPlanDigest()); + Long total = currentEntries == null ? null : currentEntries.get("total", Long.class); + Long verified = currentEntries == null ? null : currentEntries.get("verified", Long.class); + if (total == null + || verified == null + || total <= 0L + || total != proof.verifiedProbes().size() + || !total.equals(verified)) { + throw new PromotionPrerequisitesIncompleteException( + "Every exact Account validator proof must remain VERIFIED and unexpired at commit"); + } + } + + private void insertPromotion(StoredPromotion promotion) { + int inserted = + dsl.execute( + "INSERT INTO " + + PROMOTION_TABLE + + " (operation_id, environment_id, cluster_id, kubernetes_namespace, custody_mode, " + + "request_digest_version, request_digest, expected_record_version, " + + "expected_previous_generation, expected_previous_kid, target_generation, target_kid, " + + "target_algorithm, target_public_key_fingerprint, " + + "expected_private_secret_resource_version, expected_public_jwks_resource_version, " + + "expected_public_active_generation, expected_public_active_kid, operation_action, " + + "allowed_private_slots_canonical_bytes, status, generation_operation_id, " + + "expected_cluster_incarnation_uid, expected_namespace_uid, " + + "materializer_trust_binding_digest, materializer_trust_config_revision, " + + "api_binding_digest, api_config_revision, expected_private_secret_uid, " + + "expected_public_config_map_uid, prepublication_intent_digest, " + + "prepublication_receipt_digest, mounted_observation_digest, readiness_plan_digest, " + + "readiness_evidence_digest, expected_public_jwks_json, " + + "expected_active_generation_marker_json) " + + "VALUES (?, ?, ?, ?, ?, 1, ?, ?, ?, ?, ?, ?, 'RS256', ?, ?, ?, ?, ?, " + + "'PROMOTE_PENDING', ?, 'PREPARED', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + promotion.operationId(), + promotion.binding().environmentId(), + promotion.binding().clusterId(), + promotion.binding().namespace(), + promotion.binding().mode().value(), + promotion.requestDigest(), + promotion.expectedRecordVersion(), + generationValue(promotion.expectedPreviousActive()), + kidValue(promotion.expectedPreviousActive()), + parseGeneration(promotion.targetGeneration()), + promotion.targetKid(), + promotion.targetPublicKeyFingerprint(), + promotion.expectedPrivateResourceVersion(), + promotion.expectedPublicResourceVersion(), + generationValue(promotion.expectedPublishedActive()), + kidValue(promotion.expectedPublishedActive()), + PROMOTION_SLOTS_CANONICAL_BYTES, + promotion.generationOperationId(), + UUID.fromString(promotion.trustFence().expectedClusterIncarnationUid()), + UUID.fromString(promotion.trustFence().expectedNamespaceUid()), + promotion.trustFence().bindingDigest(), + promotion.trustFence().configRevision(), + promotion.apiBindingDigest(), + promotion.apiConfigRevision(), + UUID.fromString(promotion.secretUid()), + UUID.fromString(promotion.publicConfigMapUid()), + promotion.prepublicationIntentDigest(), + promotion.prepublicationReceiptDigest(), + promotion.mountedObservationDigest(), + promotion.readinessPlanDigest(), + promotion.readinessEvidenceDigest(), + promotion.expectedPublicJwksJson(), + promotion.expectedActiveMarkerJson()); + if (inserted != 1) { + throw new StorageUnavailableException("Account promotion operation insert was ambiguous"); + } + } + + private int advanceToPrepared(DesiredState state, UUID promotionOperationId) { + return dsl.execute( + "UPDATE " + + STATE_TABLE + + " SET record_version = record_version + 1, generation_operation_id = NULL, " + + "prepared_operation_id = ?, updated_at = CURRENT_TIMESTAMP WHERE environment_id = ? " + + "AND cluster_id = ? AND kubernetes_namespace = ? AND custody_mode = ? " + + "AND record_version = ? AND generation_operation_id = ? AND prepared_operation_id IS NULL " + + "AND durable_active_generation IS NOT DISTINCT FROM ? " + + "AND durable_active_kid IS NOT DISTINCT FROM ? " + + "AND published_active_generation IS NOT DISTINCT FROM ? " + + "AND published_active_kid IS NOT DISTINCT FROM ?", + promotionOperationId, + state.binding().environmentId(), + state.binding().clusterId(), + state.binding().namespace(), + state.binding().mode().value(), + state.recordVersion(), + state.generationOperationId().orElseThrow(), + generationValue(state.durableActive()), + kidValue(state.durableActive()), + generationValue(state.publishedActive()), + kidValue(state.publishedActive())); + } + + private int advanceToGenerationRequest(DesiredState state, UUID operationId) { + return dsl.execute( + "UPDATE " + + STATE_TABLE + + " SET record_version = record_version + 1, generation_operation_id = ?, " + + "updated_at = CURRENT_TIMESTAMP WHERE environment_id = ? AND cluster_id = ? " + + "AND kubernetes_namespace = ? AND custody_mode = ? " + + "AND private_secret_name = 'jwt-signing-keys' " + + "AND public_jwks_config_map_name = 'jwt-jwks' AND record_version = ? " + + "AND durable_active_generation IS NOT DISTINCT FROM ? " + + "AND durable_active_kid IS NOT DISTINCT FROM ? " + + "AND published_active_generation IS NOT DISTINCT FROM ? " + + "AND published_active_kid IS NOT DISTINCT FROM ? " + + "AND generation_operation_id IS NULL AND prepared_operation_id IS NULL", + operationId, + state.binding().environmentId(), + state.binding().clusterId(), + state.binding().namespace(), + state.binding().mode().value(), + state.recordVersion(), + generationValue(state.durableActive()), + kidValue(state.durableActive()), + generationValue(state.publishedActive()), + kidValue(state.publishedActive())); + } + + private void insertSecretObservation(SecretObservation observation) { + int inserted = + dsl.execute( + "INSERT INTO " + + OBSERVATION_TABLE + + " (operation_id, environment_id, cluster_id, kubernetes_namespace, custody_mode, " + + "operation_digest_version, operation_digest, expected_record_version, " + + "expected_cluster_incarnation_uid, expected_namespace_uid, trust_binding_digest, " + + "trust_config_revision, private_secret_name, secret_uid, observed_resource_version, " + + "observation_digest_version, observation_digest, generation_request_digest) " + + "VALUES (?, ?, ?, ?, ?, 1, ?, ?, ?, ?, ?, ?, 'jwt-signing-keys', ?, ?, 1, ?, ?)", + observation.operationId(), + observation.binding().environmentId(), + observation.binding().clusterId(), + observation.binding().namespace(), + observation.binding().mode().value(), + observation.operationDigest(), + observation.expectedRecordVersion(), + UUID.fromString(observation.trustFence().expectedClusterIncarnationUid()), + UUID.fromString(observation.trustFence().expectedNamespaceUid()), + observation.trustFence().bindingDigest(), + observation.trustFence().configRevision(), + UUID.fromString(observation.secretUid()), + observation.observedResourceVersion(), + observation.observationDigest(), + observation.generationRequestDigest()); + if (inserted != 1) { + throw new StorageUnavailableException("Account JWT Secret observation insert was ambiguous"); + } + } + + private void insertGenerationResult(GenerationResult result) { + int inserted = + dsl.execute( + "INSERT INTO " + + RESULT_TABLE + + " (operation_id, environment_id, cluster_id, kubernetes_namespace, custody_mode, " + + "operation_digest, generation_request_digest, desired_state_version, " + + "expected_cluster_incarnation_uid, expected_namespace_uid, trust_binding_digest, " + + "trust_config_revision, private_secret_name, secret_uid, " + + "expected_prior_resource_version, observed_resource_version, target_generation, " + + "target_kid, target_algorithm, public_key_fingerprint, public_jwk_json, receipt_digest) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'jwt-signing-keys', ?, ?, ?, ?, ?, 'RS256', ?, ?, ?)", + result.operationId(), + result.binding().environmentId(), + result.binding().clusterId(), + result.binding().namespace(), + result.binding().mode().value(), + result.operationDigest(), + result.generationRequestDigest(), + result.desiredStateVersion(), + UUID.fromString(result.trustFence().expectedClusterIncarnationUid()), + UUID.fromString(result.trustFence().expectedNamespaceUid()), + result.trustFence().bindingDigest(), + result.trustFence().configRevision(), + UUID.fromString(result.secretUid()), + result.expectedPriorResourceVersion(), + result.observedResourceVersion(), + parseGeneration(result.targetGeneration()), + result.targetKid(), + result.publicKeyFingerprint(), + result.publicJwkJson(), + result.receiptDigest()); + if (inserted != 1) { + throw new StorageUnavailableException("Account JWT generation result insert was ambiguous"); + } + } + + private DesiredState decodeState(Record row) { + try { + if (!PRIVATE_SECRET_NAME.equals(row.get("private_secret_name", String.class)) + || !PUBLIC_JWKS_CONFIG_MAP_NAME.equals( + row.get("public_jwks_config_map_name", String.class))) { + throw new QuarantinedStateException("Account JWT signer resource binding is malformed"); + } + return new DesiredState( + new Binding( + row.get("environment_id", String.class), + row.get("cluster_id", String.class), + row.get("kubernetes_namespace", String.class), + CustodyMode.fromValue(row.get("custody_mode", String.class))), + positive(row.get("record_version", Long.class), "Account JWT signer record version"), + activeOptional( + row.get("durable_active_generation", Long.class), + row.get("durable_active_kid", String.class), + "durable active signer"), + activeOptional( + row.get("published_active_generation", Long.class), + row.get("published_active_kid", String.class), + "published active signer"), + Optional.ofNullable(row.get("generation_operation_id", UUID.class)), + Optional.ofNullable(row.get("prepared_operation_id", UUID.class)), + enrollmentIdentity(row)); + } catch (RuntimeException ex) { + throw new QuarantinedStateException("Account JWT signer desired state is malformed", ex); + } + } + + private static Optional enrollmentIdentity(Record row) { + UUID clusterUid = row.get("enrollment_cluster_incarnation_uid", UUID.class); + UUID namespaceUid = row.get("enrollment_namespace_uid", UUID.class); + String materializerDigest = row.get("enrollment_materializer_binding_digest", String.class); + String materializerRevision = row.get("enrollment_materializer_config_revision", String.class); + String apiDigest = row.get("enrollment_api_binding_digest", String.class); + String apiRevision = row.get("enrollment_api_config_revision", String.class); + UUID configMapUid = row.get("enrollment_public_config_map_uid", UUID.class); + String resourceVersion = row.get("enrollment_public_config_map_resource_version", String.class); + String snapshotDigest = row.get("enrollment_public_config_map_snapshot_digest", String.class); + boolean allAbsent = + clusterUid == null + && namespaceUid == null + && materializerDigest == null + && materializerRevision == null + && apiDigest == null + && apiRevision == null + && configMapUid == null + && resourceVersion == null + && snapshotDigest == null; + if (allAbsent) { + return Optional.empty(); + } + if (clusterUid == null + || namespaceUid == null + || materializerDigest == null + || materializerRevision == null + || apiDigest == null + || apiRevision == null + || configMapUid == null + || resourceVersion == null + || snapshotDigest == null) { + throw new QuarantinedStateException("Account JWT signer enrollment pins are partial"); + } + return Optional.of( + new EnrollmentIdentity( + clusterUid.toString(), + namespaceUid.toString(), + materializerDigest, + materializerRevision, + apiDigest, + apiRevision, + configMapUid.toString(), + resourceVersion, + snapshotDigest)); + } + + private StoredGenerationOperation decodeGenerationOperation(Record row) { + try { + String slotBytes = + new String( + row.get("allowed_private_slots_canonical_bytes", byte[].class), + StandardCharsets.UTF_8); + if (!"[\"pending\"]".equals(slotBytes)) { + throw new QuarantinedStateException("JWT signer operation private slots are malformed"); + } + Integer digestVersion = row.get("operation_digest_version", Integer.class); + StoredGenerationOperation operation = + new StoredGenerationOperation( + row.get("operation_id", UUID.class), + new Binding( + row.get("environment_id", String.class), + row.get("cluster_id", String.class), + row.get("kubernetes_namespace", String.class), + CustodyMode.fromValue(row.get("custody_mode", String.class))), + digestVersion != null && digestVersion == 1 ? REQUEST_DIGEST_VERSION : "unsupported", + row.get("operation_digest", String.class), + positive(row.get("expected_record_version", Long.class), "expected state version"), + activeOptional( + row.get("expected_previous_generation", Long.class), + row.get("expected_previous_kid", String.class), + "expected active signer"), + activeOptional( + row.get("expected_published_generation", Long.class), + row.get("expected_published_kid", String.class), + "expected published signer"), + canonicalGeneration(row.get("target_generation", Long.class), "target generation"), + row.get("target_kid", String.class), + row.get("target_algorithm", String.class), + new TrustFence( + row.get("expected_cluster_incarnation_uid", UUID.class).toString(), + row.get("expected_namespace_uid", UUID.class).toString(), + row.get("trust_binding_digest", String.class), + row.get("trust_config_revision", String.class))); + if (!ACTION.equals(row.get("operation_action", String.class))) { + throw new QuarantinedStateException("JWT signer operation action is unsupported"); + } + if (!generationOperationDigest(operation).equals(operation.operationDigest())) { + throw new QuarantinedStateException("JWT signer operation digest is invalid"); + } + return operation; + } catch (RuntimeException ex) { + if (ex instanceof QuarantinedStateException) { + throw ex; + } + throw new QuarantinedStateException( + "Account JWT signer generation operation is malformed", ex); + } + } + + private SecretObservation decodeSecretObservation(Record row) { + try { + SecretObservation observation = + new SecretObservation( + row.get("operation_id", UUID.class), + new Binding( + row.get("environment_id", String.class), + row.get("cluster_id", String.class), + row.get("kubernetes_namespace", String.class), + CustodyMode.fromValue(row.get("custody_mode", String.class))), + row.get("operation_digest", String.class), + positive(row.get("expected_record_version", Long.class), "expected state version"), + new TrustFence( + row.get("expected_cluster_incarnation_uid", UUID.class).toString(), + row.get("expected_namespace_uid", UUID.class).toString(), + row.get("trust_binding_digest", String.class), + row.get("trust_config_revision", String.class)), + row.get("private_secret_name", String.class), + row.get("secret_uid", UUID.class).toString(), + row.get("observed_resource_version", String.class), + row.get("observation_digest", String.class), + row.get("generation_request_digest", String.class)); + if (!observationDigest( + observation.operationDigest(), + observation.trustFence(), + observation.secretUid(), + observation.observedResourceVersion()) + .equals(observation.observationDigest()) + || !generationRequestDigest(observation).equals(observation.generationRequestDigest())) { + throw new QuarantinedStateException("JWT signer Secret observation digest is invalid"); + } + return observation; + } catch (RuntimeException ex) { + if (ex instanceof QuarantinedStateException) { + throw ex; + } + throw new QuarantinedStateException("Account JWT Secret observation is malformed", ex); + } + } + + private GenerationResult decodeGenerationResult(Record row) { + try { + GenerationResult result = + new GenerationResult( + row.get("operation_id", UUID.class), + new Binding( + row.get("environment_id", String.class), + row.get("cluster_id", String.class), + row.get("kubernetes_namespace", String.class), + CustodyMode.fromValue(row.get("custody_mode", String.class))), + row.get("operation_digest", String.class), + row.get("generation_request_digest", String.class), + positive(row.get("desired_state_version", Long.class), "desired state version"), + new TrustFence( + row.get("expected_cluster_incarnation_uid", UUID.class).toString(), + row.get("expected_namespace_uid", UUID.class).toString(), + row.get("trust_binding_digest", String.class), + row.get("trust_config_revision", String.class)), + row.get("private_secret_name", String.class), + row.get("secret_uid", UUID.class).toString(), + row.get("expected_prior_resource_version", String.class), + row.get("observed_resource_version", String.class), + canonicalGeneration(row.get("target_generation", Long.class), "target generation"), + row.get("target_kid", String.class), + row.get("target_algorithm", String.class), + row.get("public_key_fingerprint", String.class), + row.get("public_jwk_json", String.class), + row.get("receipt_digest", String.class)); + PublicJwk jwk = parsePublicJwk(result.publicJwkJson()); + if (!jwk.kid().equals(result.targetKid()) + || !jwk.fingerprint().equals(result.publicKeyFingerprint()) + || !generationReceiptDigest(result).equals(result.receiptDigest())) { + throw new QuarantinedStateException("JWT signer generation receipt digest is invalid"); + } + return result; + } catch (RuntimeException ex) { + if (ex instanceof QuarantinedStateException) { + throw ex; + } + throw new QuarantinedStateException("Account JWT generation result is malformed", ex); + } + } + + private static void verifyPreparedIsUnavailable(DesiredState state) { + if (state.preparedOperationId().isPresent()) { + throw new PromotionPrerequisitesIncompleteException( + "Existing PREPARED signer state requires unavailable lifecycle evidence"); + } + } + + private static void requireBinding(DesiredState state, Binding expected) { + if (!state.binding().equals(expected)) { + throw new BindingMismatchException( + "Account JWT signer environment, cluster, namespace, or custody binding changed"); + } + } + + private static String generationOperationDigest(StoredGenerationOperation operation) { + Map preimage = new LinkedHashMap<>(); + preimage.put("digestVersion", REQUEST_DIGEST_VERSION); + preimage.put("environmentId", operation.binding().environmentId()); + preimage.put("clusterId", operation.binding().clusterId()); + preimage.put("namespace", operation.binding().namespace()); + preimage.put("custodyMode", operation.binding().mode().value()); + preimage.put("privateResource", Map.of("kind", "Secret", "name", PRIVATE_SECRET_NAME)); + preimage.put("operationId", operation.operationId().toString()); + preimage.put("expectedRecordVersion", Long.toString(operation.expectedRecordVersion())); + preimage.put("expectedPreviousActive", activeDigestValue(operation.expectedPreviousActive())); + preimage.put("expectedPublishedActive", activeDigestValue(operation.expectedPublishedActive())); + preimage.put("targetGeneration", operation.targetGeneration()); + preimage.put("targetKid", operation.targetKid()); + preimage.put("targetAlgorithm", operation.targetAlgorithm()); + preimage.put("operationAction", ACTION); + preimage.put("allowedPrivateSlots", List.of(PENDING_SLOT)); + preimage.put( + "expectedClusterIncarnationUid", operation.trustFence().expectedClusterIncarnationUid()); + preimage.put("expectedNamespaceUid", operation.trustFence().expectedNamespaceUid()); + preimage.put("trustBindingDigest", operation.trustFence().bindingDigest()); + preimage.put("trustConfigRevision", operation.trustFence().configRevision()); + return digest(preimage); + } + + private static String observationDigest( + String operationDigest, TrustFence trust, String secretUid, String resourceVersion) { + return digest( + Map.of( + "digestVersion", OBSERVATION_DIGEST_VERSION, + "operationDigest", operationDigest, + "privateResource", Map.of("kind", "Secret", "name", PRIVATE_SECRET_NAME), + "expectedClusterIncarnationUid", trust.expectedClusterIncarnationUid(), + "expectedNamespaceUid", trust.expectedNamespaceUid(), + "trustBindingDigest", trust.bindingDigest(), + "trustConfigRevision", trust.configRevision(), + "secretUid", secretUid, + "observedResourceVersion", resourceVersion)); + } + + private static String generationRequestDigest(SecretObservation observation) { + return digest( + Map.of( + "digestVersion", GENERATION_REQUEST_DIGEST_VERSION, + "operationDigest", observation.operationDigest(), + "observationDigest", observation.observationDigest(), + "secretUid", observation.secretUid(), + "expectedPriorResourceVersion", observation.observedResourceVersion(), + "target", "pending")); + } + + private static String generationReceiptDigest(GenerationResult result) { + Map preimage = new LinkedHashMap<>(); + preimage.put("digestVersion", RECEIPT_DIGEST_VERSION); + preimage.put("operationId", result.operationId().toString()); + preimage.put("operationDigest", result.operationDigest()); + preimage.put("generationRequestDigest", result.generationRequestDigest()); + preimage.put("desiredStateVersion", Long.toString(result.desiredStateVersion())); + preimage.put("environmentId", result.binding().environmentId()); + preimage.put("clusterId", result.binding().clusterId()); + preimage.put("namespace", result.binding().namespace()); + preimage.put( + "expectedClusterIncarnationUid", result.trustFence().expectedClusterIncarnationUid()); + preimage.put("expectedNamespaceUid", result.trustFence().expectedNamespaceUid()); + preimage.put("trustBindingDigest", result.trustFence().bindingDigest()); + preimage.put("trustConfigRevision", result.trustFence().configRevision()); + preimage.put("privateResource", Map.of("kind", "Secret", "name", PRIVATE_SECRET_NAME)); + preimage.put("secretUid", result.secretUid()); + preimage.put("expectedPriorResourceVersion", result.expectedPriorResourceVersion()); + preimage.put("observedResourceVersion", result.observedResourceVersion()); + preimage.put("targetGeneration", result.targetGeneration()); + preimage.put("targetKid", result.targetKid()); + preimage.put("targetAlgorithm", result.targetAlgorithm()); + preimage.put("publicKeyFingerprint", result.publicKeyFingerprint()); + preimage.put("publicJwk", result.publicJwkJson()); + return digest(preimage); + } + + private static String digest(Object value) { + try { + byte[] canonical = Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(canonical)); + } catch (IOException | NoSuchAlgorithmException ex) { + throw new IllegalStateException("Account JWT signer evidence digest is unavailable", ex); + } + } + + private static String sha256(String value) { + try { + return HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256").digest(value.getBytes(StandardCharsets.UTF_8))); + } catch (NoSuchAlgorithmException ex) { + throw new IllegalStateException("SHA-256 is unavailable for JWT promotion evidence", ex); + } + } + + private static Object activeDigestValue(Optional active) { + if (active.isEmpty()) { + return Map.of("present", false); + } + ActiveSigner value = active.orElseThrow(); + return Map.of("present", true, "generation", value.generation(), "kid", value.kid()); + } + + private static PublicJwk parsePublicJwk(String json) { + if (json == null || json.isEmpty() || json.getBytes(StandardCharsets.UTF_8).length > 8_192) { + throw new IllegalArgumentException("JWT signer public JWK is missing or too large"); + } + try { + JsonNode node = STRICT_JSON.readTree(json); + if (node == null || !node.isObject() || node.size() != PUBLIC_JWK_FIELDS.size()) { + throw new IllegalArgumentException("JWT signer public JWK has an unsupported shape"); + } + for (Map.Entry property : node.properties()) { + if (!PUBLIC_JWK_FIELDS.contains(property.getKey())) { + throw new IllegalArgumentException("JWT signer public JWK has an unsupported field"); + } + } + String canonicalJson = + new String(Rfc8785CanonicalJson.canonicalizeUtf8(json), StandardCharsets.UTF_8); + if (!canonicalJson.equals(json)) { + throw new IllegalArgumentException("JWT signer public JWK must be canonical RFC 8785 JSON"); + } + String kty = requiredText(node, "kty", 8); + String use = requiredText(node, "use", 8); + String algorithm = requiredText(node, "alg", 8); + String kid = requiredText(node, "kid", 64); + String modulus = requiredText(node, "n", 4_096); + String exponent = requiredText(node, "e", 16); + JsonNode keyOps = node.get("key_ops"); + if (!"RSA".equals(kty) + || !"sig".equals(use) + || !ALGORITHM.equals(algorithm) + || !KID.matcher(kid).matches() + || keyOps == null + || !keyOps.isArray() + || keyOps.size() != 1 + || !keyOps.get(0).isTextual() + || !"verify".equals(keyOps.get(0).textValue())) { + throw new IllegalArgumentException("JWT signer public JWK does not meet RS256 policy"); + } + byte[] modulusBytes = decodeCanonicalBase64Url(modulus, 2_048); + byte[] exponentBytes = decodeCanonicalBase64Url(exponent, 8); + try { + if (modulusBytes.length == 0 + || modulusBytes[0] == 0 + || exponentBytes.length == 0 + || exponentBytes[0] == 0) { + throw new IllegalArgumentException("JWT signer RSA public numbers are malformed"); + } + BigInteger modulusInteger = new BigInteger(1, modulusBytes); + BigInteger exponentInteger = new BigInteger(1, exponentBytes); + if (modulusInteger.bitLength() < 3_072 + || modulusInteger.bitLength() > 16_384 + || !modulusInteger.testBit(0) + || !BigInteger.valueOf(65_537).equals(exponentInteger)) { + throw new IllegalArgumentException("JWT signer RSA public key is outside policy"); + } + } finally { + java.util.Arrays.fill(modulusBytes, (byte) 0); + java.util.Arrays.fill(exponentBytes, (byte) 0); + } + String fingerprint = + digest( + Map.of( + "e", exponent, + "kty", "RSA", + "n", modulus)); + return new PublicJwk(kid, canonicalJson, fingerprint); + } catch (IllegalArgumentException ex) { + throw ex; + } catch (Exception ex) { + throw new IllegalArgumentException("JWT signer public JWK is malformed", ex); + } + } + + private static byte[] decodeCanonicalBase64Url(String encoded, int maxBytes) { + final byte[] decoded; + try { + decoded = Base64.getUrlDecoder().decode(encoded); + } catch (IllegalArgumentException ex) { + throw new IllegalArgumentException("JWT signer RSA public number is malformed", ex); + } + byte[] canonical = Base64.getUrlEncoder().withoutPadding().encode(decoded); + boolean matches = canonical.length == encoded.length(); + for (int index = 0; matches && index < canonical.length; index++) { + matches = (char) Byte.toUnsignedInt(canonical[index]) == encoded.charAt(index); + } + java.util.Arrays.fill(canonical, (byte) 0); + if (decoded.length == 0 || decoded.length > maxBytes || !matches) { + java.util.Arrays.fill(decoded, (byte) 0); + throw new IllegalArgumentException("JWT signer RSA public number is not canonical"); + } + return decoded; + } + + private static ActiveSigner active(Long generation, String kid, String field) { + if (generation == null && kid == null) { + return null; + } + if (generation == null || kid == null) { + throw new QuarantinedStateException(field + " has an incomplete generation/kid pair"); + } + return new ActiveSigner(Long.toString(positive(generation, field + " generation")), kid); + } + + private static Optional activeOptional(Long generation, String kid, String field) { + return Optional.ofNullable(active(generation, kid, field)); + } + + private static Long generationValue(Optional active) { + return active.map(value -> parseGeneration(value.generation())).orElse(null); + } + + private static String kidValue(Optional active) { + return active.map(ActiveSigner::kid).orElse(null); + } + + private static String canonicalGeneration(Long value, String field) { + return Long.toString(positive(value, field)); + } + + private static long positive(Long value, String field) { + if (value == null || value <= 0) { + throw new QuarantinedStateException(field + " must be positive"); + } + return value; + } + + private static long parseGeneration(String value) { + if (value == null || !POSITIVE_DECIMAL.matcher(value).matches()) { + throw new IllegalArgumentException("Signer generation must be canonical positive decimal"); + } + try { + return Long.parseLong(value); + } catch (NumberFormatException ex) { + throw new IllegalArgumentException("Signer generation is outside its supported range", ex); + } + } + + private static void requireOperationId(UUID operationId) { + Objects.requireNonNull(operationId, "Account JWT signer operation ID is required"); + if (operationId.version() != 4) { + throw new IllegalArgumentException("Account JWT signer operation ID must be UUIDv4"); + } + } + + private static void requireUuid(String value, String field) { + if (value == null) { + throw new IllegalArgumentException("JWT signer " + field + " is missing"); + } + try { + UUID parsed = UUID.fromString(value); + if (!parsed.toString().equals(value) || parsed.equals(new UUID(0, 0))) { + throw new IllegalArgumentException("JWT signer " + field + " is malformed"); + } + } catch (RuntimeException ex) { + throw new IllegalArgumentException("JWT signer " + field + " is malformed", ex); + } + } + + private static void requireMatch(Pattern pattern, String value, String field) { + if (value == null || !pattern.matcher(value).matches()) { + throw new IllegalArgumentException("JWT signer " + field + " is malformed"); + } + } + + private static void requireAccountTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException("Account transaction is required for JWT signer state"); + } + } + + private static void requireWritableAccountTransaction() { + requireAccountTransaction(); + if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException( + "Writable Account transaction is required for JWT signer state"); + } + } + + public enum CustodyMode { + INTERIM_ACCOUNT_ONLY_MOUNTED_FALLBACK(MODE); + + private final String value; + + CustodyMode(String value) { + this.value = value; + } + + public String value() { + return value; + } + + private static CustodyMode fromValue(String value) { + for (CustodyMode candidate : values()) { + if (candidate.value.equals(value)) { + return candidate; + } + } + throw new QuarantinedStateException("JWT signer custody mode is unsupported"); + } + } + + public enum GenerationPhase { + OBSERVE_PRIVATE_SECRET, + GENERATE_PENDING, + GENERATION_RECORDED + } + + public record Binding( + String environmentId, String clusterId, String namespace, CustodyMode mode) { + public Binding { + requireMatch(ENVIRONMENT_ID, environmentId, "environment ID"); + requireMatch(CLUSTER_ID, clusterId, "cluster ID"); + requireMatch(ENVIRONMENT_ID, namespace, "Kubernetes namespace"); + Objects.requireNonNull(mode, "JWT signer custody mode is required"); + } + } + + /** Independently protected trust identity captured by every immutable operation and receipt. */ + public record TrustFence( + String expectedClusterIncarnationUid, + String expectedNamespaceUid, + String bindingDigest, + String configRevision) { + public TrustFence { + requireUuid(expectedClusterIncarnationUid, "expected cluster incarnation UID"); + requireUuid(expectedNamespaceUid, "expected namespace UID"); + requireMatch(SHA256_HEX, bindingDigest, "materializer trust binding digest"); + requireMatch(CLUSTER_ID, configRevision, "materializer trust configuration revision"); + } + } + + /** + * Immutable independently protected trust and first ConfigMap observation used for enrollment. + */ + public record EnrollmentIdentity( + String expectedClusterIncarnationUid, + String expectedNamespaceUid, + String materializerTrustBindingDigest, + String materializerTrustConfigRevision, + String apiBindingDigest, + String apiConfigRevision, + String publicConfigMapUid, + String publicConfigMapResourceVersion, + String publicConfigMapSnapshotDigest) { + public EnrollmentIdentity { + requireUuid(expectedClusterIncarnationUid, "enrollment cluster incarnation UID"); + requireUuid(expectedNamespaceUid, "enrollment namespace UID"); + requireMatch(SHA256_HEX, materializerTrustBindingDigest, "materializer trust digest"); + requireMatch(CLUSTER_ID, materializerTrustConfigRevision, "materializer trust revision"); + requireMatch(SHA256_HEX, apiBindingDigest, "public JWKS API binding digest"); + requireMatch(CLUSTER_ID, apiConfigRevision, "public JWKS API configuration revision"); + requireUuid(publicConfigMapUid, "pre-created public ConfigMap UID"); + requireMatch( + RESOURCE_VERSION, publicConfigMapResourceVersion, "initial ConfigMap resourceVersion"); + requireMatch(SHA256_HEX, publicConfigMapSnapshotDigest, "initial ConfigMap snapshot digest"); + } + + /** Stable pin equality deliberately excludes the historical first ConfigMap RV/data digest. */ + public boolean sameStablePins(EnrollmentIdentity other) { + Objects.requireNonNull(other, "Enrollment identity is required"); + return expectedClusterIncarnationUid.equals(other.expectedClusterIncarnationUid) + && expectedNamespaceUid.equals(other.expectedNamespaceUid) + && materializerTrustBindingDigest.equals(other.materializerTrustBindingDigest) + && materializerTrustConfigRevision.equals(other.materializerTrustConfigRevision) + && apiBindingDigest.equals(other.apiBindingDigest) + && apiConfigRevision.equals(other.apiConfigRevision) + && publicConfigMapUid.equals(other.publicConfigMapUid); + } + } + + public record ActiveSigner(String generation, String kid) { + public ActiveSigner { + parseGeneration(generation); + requireMatch(KID, kid, "active signer kid"); + } + } + + public record DesiredState( + Binding binding, + long recordVersion, + Optional durableActive, + Optional publishedActive, + Optional generationOperationId, + Optional preparedOperationId, + Optional enrollmentIdentity) { + public DesiredState { + Objects.requireNonNull(binding, "JWT signer binding is required"); + if (recordVersion <= 0) { + throw new IllegalArgumentException("JWT signer record version must be positive"); + } + durableActive = Objects.requireNonNull(durableActive, "Durable active signer is required"); + publishedActive = + Objects.requireNonNull(publishedActive, "Published active signer is required"); + generationOperationId = + Objects.requireNonNull(generationOperationId, "Generation operation state is required"); + preparedOperationId = + Objects.requireNonNull(preparedOperationId, "Prepared operation state is required"); + enrollmentIdentity = + Objects.requireNonNull(enrollmentIdentity, "Enrollment identity state is required"); + if (generationOperationId.isPresent() && preparedOperationId.isPresent()) { + throw new IllegalArgumentException("Generation and PREPARED pointers cannot coexist"); + } + } + } + + public record GenerationRequest( + GenerationPhase phase, + UUID operationId, + String operationDigest, + String generationRequestDigest, + long desiredStateVersion, + Binding binding, + TrustFence trustFence, + String privateSecretName, + String targetGeneration, + String targetKid, + String targetAlgorithm, + String operationAction, + List allowedPrivateSlots, + Optional expectedActive, + Optional expectedPublishedActive, + String secretUid, + String expectedSecretResourceVersion, + String generationReceiptDigest, + String publicKeyFingerprint, + String publicJwkJson, + String observedSecretResourceVersion) { + public GenerationRequest { + Objects.requireNonNull(phase, "Generation phase is required"); + requireOperationId(operationId); + requireMatch(SHA256_HEX, operationDigest, "generation operation digest"); + if (phase != GenerationPhase.OBSERVE_PRIVATE_SECRET) { + requireMatch(SHA256_HEX, generationRequestDigest, "generation request digest"); + } else if (generationRequestDigest != null && !generationRequestDigest.isEmpty()) { + requireMatch(SHA256_HEX, generationRequestDigest, "generation request digest"); + } + if (desiredStateVersion <= 1) { + throw new QuarantinedStateException("JWT generation request state version is invalid"); + } + Objects.requireNonNull(binding, "Generation request binding is required"); + Objects.requireNonNull(trustFence, "Generation request trust fence is required"); + if (!PRIVATE_SECRET_NAME.equals(privateSecretName) + || !ALGORITHM.equals(targetAlgorithm) + || !ACTION.equals(operationAction) + || !List.of(PENDING_SLOT).equals(allowedPrivateSlots)) { + throw new QuarantinedStateException("JWT generation request fixed operation is malformed"); + } + allowedPrivateSlots = List.copyOf(allowedPrivateSlots); + parseGeneration(targetGeneration); + requireMatch(KID, targetKid, "target kid"); + expectedActive = Objects.requireNonNull(expectedActive, "Expected active signer is required"); + expectedPublishedActive = + Objects.requireNonNull(expectedPublishedActive, "Expected published signer is required"); + secretUid = secretUid == null ? "" : secretUid; + expectedSecretResourceVersion = + expectedSecretResourceVersion == null ? "" : expectedSecretResourceVersion; + generationReceiptDigest = generationReceiptDigest == null ? "" : generationReceiptDigest; + publicKeyFingerprint = publicKeyFingerprint == null ? "" : publicKeyFingerprint; + publicJwkJson = publicJwkJson == null ? "" : publicJwkJson; + observedSecretResourceVersion = + observedSecretResourceVersion == null ? "" : observedSecretResourceVersion; + if (phase != GenerationPhase.OBSERVE_PRIVATE_SECRET) { + requireUuid(secretUid, "observed fixed Secret UID"); + requireMatch( + RESOURCE_VERSION, expectedSecretResourceVersion, "observed Secret resourceVersion"); + } + if (phase == GenerationPhase.GENERATION_RECORDED) { + requireMatch(SHA256_HEX, generationReceiptDigest, "generation receipt digest"); + requireMatch(SHA256_HEX, publicKeyFingerprint, "RFC 7638 public-key fingerprint"); + parsePublicJwk(publicJwkJson); + requireMatch( + RESOURCE_VERSION, observedSecretResourceVersion, "result Secret resourceVersion"); + } else if (!generationReceiptDigest.isEmpty() + || !publicKeyFingerprint.isEmpty() + || !publicJwkJson.isEmpty() + || !observedSecretResourceVersion.isEmpty()) { + throw new QuarantinedStateException( + "Incomplete JWT generation request contains result evidence"); + } + } + } + + public record GenerationResult( + UUID operationId, + Binding binding, + String operationDigest, + String generationRequestDigest, + long desiredStateVersion, + TrustFence trustFence, + String privateSecretName, + String secretUid, + String expectedPriorResourceVersion, + String observedResourceVersion, + String targetGeneration, + String targetKid, + String targetAlgorithm, + String publicKeyFingerprint, + String publicJwkJson, + String receiptDigest) { + public GenerationResult { + requireOperationId(operationId); + Objects.requireNonNull(binding, "Generation result binding is required"); + requireMatch(SHA256_HEX, operationDigest, "generation operation digest"); + requireMatch(SHA256_HEX, generationRequestDigest, "generation request digest"); + if (desiredStateVersion <= 1) { + throw new QuarantinedStateException("JWT generation result state version is invalid"); + } + Objects.requireNonNull(trustFence, "Generation result trust fence is required"); + if (!PRIVATE_SECRET_NAME.equals(privateSecretName)) { + throw new IllegalArgumentException("JWT generation result must name the fixed Secret"); + } + requireUuid(secretUid, "generation result Secret UID"); + requireMatch( + RESOURCE_VERSION, expectedPriorResourceVersion, "expected Secret resourceVersion"); + requireMatch(RESOURCE_VERSION, observedResourceVersion, "observed Secret resourceVersion"); + if (expectedPriorResourceVersion.equals(observedResourceVersion)) { + throw new QuarantinedStateException("JWT signer Secret resourceVersion did not advance"); + } + parseGeneration(targetGeneration); + requireMatch(KID, targetKid, "target kid"); + if (!ALGORITHM.equals(targetAlgorithm)) { + throw new IllegalArgumentException("Only RS256 JWT signer results are supported"); + } + requireMatch(SHA256_HEX, publicKeyFingerprint, "RFC 7638 public-key fingerprint"); + requireMatch(SHA256_HEX, receiptDigest, "generation receipt digest"); + PublicJwk jwk = parsePublicJwk(publicJwkJson); + if (!jwk.kid().equals(targetKid) || !jwk.fingerprint().equals(publicKeyFingerprint)) { + throw new QuarantinedStateException( + "JWT generation result public key does not match receipt"); + } + } + + private static GenerationResult from( + StoredGenerationOperation operation, + long desiredStateVersion, + SecretObservation observation, + String observedResourceVersion, + PublicJwk jwk) { + GenerationResult candidate = + new GenerationResult( + operation.operationId(), + operation.binding(), + operation.operationDigest(), + observation.generationRequestDigest(), + desiredStateVersion, + operation.trustFence(), + PRIVATE_SECRET_NAME, + observation.secretUid(), + observation.observedResourceVersion(), + observedResourceVersion, + operation.targetGeneration(), + operation.targetKid(), + operation.targetAlgorithm(), + jwk.fingerprint(), + jwk.canonicalJson(), + "0".repeat(64)); + return new GenerationResult( + candidate.operationId(), + candidate.binding(), + candidate.operationDigest(), + candidate.generationRequestDigest(), + candidate.desiredStateVersion(), + candidate.trustFence(), + candidate.privateSecretName(), + candidate.secretUid(), + candidate.expectedPriorResourceVersion(), + candidate.observedResourceVersion(), + candidate.targetGeneration(), + candidate.targetKid(), + candidate.targetAlgorithm(), + candidate.publicKeyFingerprint(), + candidate.publicJwkJson(), + generationReceiptDigest(candidate)); + } + } + + private record StoredGenerationOperation( + UUID operationId, + Binding binding, + String digestVersion, + String operationDigest, + long expectedRecordVersion, + Optional expectedPreviousActive, + Optional expectedPublishedActive, + String targetGeneration, + String targetKid, + String targetAlgorithm, + TrustFence trustFence) { + private StoredGenerationOperation { + requireOperationId(operationId); + Objects.requireNonNull(binding, "Generation operation binding is required"); + requireMatch(SHA256_HEX, operationDigest, "generation operation digest"); + if (expectedRecordVersion <= 0 || expectedRecordVersion == Long.MAX_VALUE) { + throw new IllegalArgumentException("Generation operation state version is invalid"); + } + expectedPreviousActive = + Objects.requireNonNull(expectedPreviousActive, "Expected active signer is required"); + expectedPublishedActive = + Objects.requireNonNull(expectedPublishedActive, "Expected published signer is required"); + parseGeneration(targetGeneration); + requireMatch(KID, targetKid, "target kid"); + if (!ALGORITHM.equals(targetAlgorithm)) { + throw new IllegalArgumentException("Only RS256 generation operations are supported"); + } + Objects.requireNonNull(trustFence, "Generation operation trust is required"); + } + + private static StoredGenerationOperation create( + DesiredState state, + TrustFence trust, + UUID operationId, + long targetGeneration, + String targetKid) { + StoredGenerationOperation unsigned = + new StoredGenerationOperation( + operationId, + state.binding(), + REQUEST_DIGEST_VERSION, + "0".repeat(64), + state.recordVersion(), + state.durableActive(), + state.publishedActive(), + Long.toString(targetGeneration), + targetKid, + ALGORITHM, + trust); + return new StoredGenerationOperation( + unsigned.operationId(), + unsigned.binding(), + unsigned.digestVersion(), + generationOperationDigest(unsigned), + unsigned.expectedRecordVersion(), + unsigned.expectedPreviousActive(), + unsigned.expectedPublishedActive(), + unsigned.targetGeneration(), + unsigned.targetKid(), + unsigned.targetAlgorithm(), + unsigned.trustFence()); + } + } + + private record SecretObservation( + UUID operationId, + Binding binding, + String operationDigest, + long expectedRecordVersion, + TrustFence trustFence, + String privateSecretName, + String secretUid, + String observedResourceVersion, + String observationDigest, + String generationRequestDigest) { + private SecretObservation { + requireOperationId(operationId); + Objects.requireNonNull(binding, "Secret observation binding is required"); + if (expectedRecordVersion <= 0 || expectedRecordVersion == Long.MAX_VALUE) { + throw new IllegalArgumentException("Secret observation state version is invalid"); + } + requireMatch(SHA256_HEX, operationDigest, "operation digest"); + Objects.requireNonNull(trustFence, "Secret observation trust is required"); + if (!PRIVATE_SECRET_NAME.equals(privateSecretName)) { + throw new IllegalArgumentException("Secret observation must name the fixed Secret"); + } + requireUuid(secretUid, "observed Secret UID"); + requireMatch(RESOURCE_VERSION, observedResourceVersion, "observed Secret resourceVersion"); + requireMatch(SHA256_HEX, observationDigest, "Secret observation digest"); + requireMatch(SHA256_HEX, generationRequestDigest, "generation request digest"); + } + + private static SecretObservation from( + StoredGenerationOperation operation, String secretUid, String resourceVersion) { + String observationDigest = + AccountJwtSignerDesiredStateRepository.observationDigest( + operation.operationDigest(), operation.trustFence(), secretUid, resourceVersion); + String generationRequestDigest = + AccountJwtSignerDesiredStateRepository.generationRequestDigest( + operation.operationDigest(), observationDigest, secretUid, resourceVersion); + return new SecretObservation( + operation.operationId(), + operation.binding(), + operation.operationDigest(), + operation.expectedRecordVersion(), + operation.trustFence(), + PRIVATE_SECRET_NAME, + secretUid, + resourceVersion, + observationDigest, + generationRequestDigest); + } + } + + private record PublicJwk(String kid, String canonicalJson, String fingerprint) {} + + private record LockedCurrent(DesiredState state, StoredGenerationOperation operation) {} + + private record StoredPromotion( + UUID operationId, + Binding binding, + int requestDigestVersion, + String requestDigest, + long expectedRecordVersion, + Optional expectedPreviousActive, + Optional expectedPublishedActive, + String targetGeneration, + String targetKid, + String targetAlgorithm, + String targetPublicKeyFingerprint, + String expectedPrivateResourceVersion, + String expectedPublicResourceVersion, + TrustFence trustFence, + UUID generationOperationId, + String generationOperationDigest, + String generationReceiptDigest, + String apiBindingDigest, + String apiConfigRevision, + String secretUid, + String publicConfigMapUid, + String prepublicationIntentDigest, + String prepublicationReceiptDigest, + String mountedObservationDigest, + String readinessPlanDigest, + String readinessEvidenceDigest, + String expectedPublicJwksJson, + String expectedActiveMarkerJson, + String status, + boolean privatePromotionDispatched, + String privatePromotionObservedResourceVersion, + String privatePromotionReceiptDigest, + String activeJwksObservedResourceVersion, + String activeJwksPublicDataDigest, + String activeJwksReceiptDigest) { + private StoredPromotion { + requireOperationId(operationId); + Objects.requireNonNull(binding, "Promotion binding is required"); + if (requestDigestVersion != 1 + || expectedRecordVersion <= 0L + || expectedRecordVersion == Long.MAX_VALUE) { + throw new QuarantinedStateException("Promotion version fence is malformed"); + } + requireMatch(SHA256_HEX, requestDigest, "promotion request digest"); + expectedPreviousActive = Objects.requireNonNull(expectedPreviousActive); + expectedPublishedActive = Objects.requireNonNull(expectedPublishedActive); + parseGeneration(targetGeneration); + requireMatch(KID, targetKid, "promotion target kid"); + if (!ALGORITHM.equals(targetAlgorithm)) { + throw new QuarantinedStateException("Promotion target algorithm is unsupported"); + } + requireMatch(SHA256_HEX, targetPublicKeyFingerprint, "promotion target fingerprint"); + requireMatch( + RESOURCE_VERSION, expectedPrivateResourceVersion, "expected private Secret version"); + requireMatch( + RESOURCE_VERSION, expectedPublicResourceVersion, "expected public ConfigMap version"); + Objects.requireNonNull(trustFence, "Promotion trust fence is required"); + requireOperationId(generationOperationId); + requireMatch(SHA256_HEX, generationOperationDigest, "generation operation digest"); + requireMatch(SHA256_HEX, generationReceiptDigest, "generation receipt digest"); + requireMatch(SHA256_HEX, apiBindingDigest, "public API binding digest"); + requireMatch(CLUSTER_ID, apiConfigRevision, "public API config revision"); + requireUuid(secretUid, "promotion Secret UID"); + requireUuid(publicConfigMapUid, "promotion ConfigMap UID"); + requireMatch(SHA256_HEX, prepublicationIntentDigest, "prepublication intent digest"); + requireMatch(SHA256_HEX, prepublicationReceiptDigest, "prepublication receipt digest"); + requireMatch(SHA256_HEX, mountedObservationDigest, "mounted observation digest"); + requireMatch(SHA256_HEX, readinessPlanDigest, "readiness plan digest"); + requireMatch(SHA256_HEX, readinessEvidenceDigest, "readiness evidence digest"); + if (expectedPublicJwksJson == null + || expectedPublicJwksJson.isBlank() + || expectedPublicJwksJson.getBytes(StandardCharsets.UTF_8).length > 256 * 1024 + || expectedActiveMarkerJson == null + || expectedActiveMarkerJson.isBlank() + || expectedActiveMarkerJson.getBytes(StandardCharsets.UTF_8).length > 16 * 1024) { + throw new QuarantinedStateException("Promotion public payload is missing or oversized"); + } + if (!Set.of("PREPARED", "COMMITTED", "ABORTED").contains(status)) { + throw new QuarantinedStateException("Promotion status is malformed"); + } + boolean noActiveJwksReceipt = + activeJwksObservedResourceVersion == null + && activeJwksPublicDataDigest == null + && activeJwksReceiptDigest == null; + boolean completeActiveJwksReceipt = + activeJwksObservedResourceVersion != null + && activeJwksPublicDataDigest != null + && activeJwksReceiptDigest != null; + if ((privatePromotionObservedResourceVersion == null) + != (privatePromotionReceiptDigest == null) + || !(noActiveJwksReceipt || completeActiveJwksReceipt)) { + throw new QuarantinedStateException("Promotion resource receipts are partial"); + } + if ((privatePromotionReceiptDigest != null && !privatePromotionDispatched) + || ("COMMITTED".equals(status) && !privatePromotionDispatched) + || ("ABORTED".equals(status) && privatePromotionDispatched)) { + throw new QuarantinedStateException( + "Promotion dispatch state is inconsistent with its receipts or terminal status"); + } + if (privatePromotionObservedResourceVersion != null) { + requireMatch( + RESOURCE_VERSION, + privatePromotionObservedResourceVersion, + "private promotion readback version"); + requireMatch(SHA256_HEX, privatePromotionReceiptDigest, "private promotion receipt digest"); + } + if (activeJwksObservedResourceVersion != null) { + requireMatch( + RESOURCE_VERSION, activeJwksObservedResourceVersion, "active JWKS readback version"); + requireMatch(SHA256_HEX, activeJwksPublicDataDigest, "active JWKS public data digest"); + requireMatch(SHA256_HEX, activeJwksReceiptDigest, "active JWKS receipt digest"); + } + } + + private static StoredPromotion create( + PromotionPreparation preparation, + DesiredState state, + StoredGenerationOperation generation, + GenerationResult result, + TrustFence trust, + Binding binding) { + if (!preparation.generationOperationId().equals(generation.operationId()) + || !preparation.generationResult().equals(result) + || !preparation + .enrollmentIdentity() + .sameStablePins(state.enrollmentIdentity().orElseThrow()) + || !generation.binding().equals(binding) + || !result.binding().equals(binding) + || !generation.trustFence().equals(trust) + || !result.trustFence().equals(trust) + || !state.generationOperationId().equals(Optional.of(generation.operationId())) + || state.preparedOperationId().isPresent()) { + throw new PromotionPrerequisitesIncompleteException( + "Promotion preparation is not bound to the current Account generation and enrollment"); + } + UUID promotionId = UUID.randomUUID(); + StoredPromotion unsigned = + new StoredPromotion( + promotionId, + binding, + 1, + "0".repeat(64), + state.recordVersion(), + state.durableActive(), + state.publishedActive(), + result.targetGeneration(), + result.targetKid(), + result.targetAlgorithm(), + result.publicKeyFingerprint(), + result.observedResourceVersion(), + preparation.expectedPublicResourceVersion(), + trust, + generation.operationId(), + generation.operationDigest(), + result.receiptDigest(), + preparation.apiBindingDigest(), + preparation.apiConfigRevision(), + result.secretUid(), + preparation.publicConfigMapUid(), + preparation.prepublicationIntentDigest(), + preparation.prepublicationReceiptDigest(), + preparation.mountedObservationDigest(), + preparation.readinessPlanDigest(), + preparation.readinessEvidenceDigest(), + preparation.expectedPublicJwksJson(), + "{}", + "PREPARED", + false, + null, + null, + null, + null, + null); + StoredPromotion signed = + new StoredPromotion( + unsigned.operationId(), + unsigned.binding(), + unsigned.requestDigestVersion(), + promotionRequestDigest(unsigned), + unsigned.expectedRecordVersion(), + unsigned.expectedPreviousActive(), + unsigned.expectedPublishedActive(), + unsigned.targetGeneration(), + unsigned.targetKid(), + unsigned.targetAlgorithm(), + unsigned.targetPublicKeyFingerprint(), + unsigned.expectedPrivateResourceVersion(), + unsigned.expectedPublicResourceVersion(), + unsigned.trustFence(), + unsigned.generationOperationId(), + unsigned.generationOperationDigest(), + unsigned.generationReceiptDigest(), + unsigned.apiBindingDigest(), + unsigned.apiConfigRevision(), + unsigned.secretUid(), + unsigned.publicConfigMapUid(), + unsigned.prepublicationIntentDigest(), + unsigned.prepublicationReceiptDigest(), + unsigned.mountedObservationDigest(), + unsigned.readinessPlanDigest(), + unsigned.readinessEvidenceDigest(), + unsigned.expectedPublicJwksJson(), + "{}", + unsigned.status(), + unsigned.privatePromotionDispatched(), + null, + null, + null, + null, + null); + return new StoredPromotion( + signed.operationId(), + signed.binding(), + signed.requestDigestVersion(), + signed.requestDigest(), + signed.expectedRecordVersion(), + signed.expectedPreviousActive(), + signed.expectedPublishedActive(), + signed.targetGeneration(), + signed.targetKid(), + signed.targetAlgorithm(), + signed.targetPublicKeyFingerprint(), + signed.expectedPrivateResourceVersion(), + signed.expectedPublicResourceVersion(), + signed.trustFence(), + signed.generationOperationId(), + signed.generationOperationDigest(), + signed.generationReceiptDigest(), + signed.apiBindingDigest(), + signed.apiConfigRevision(), + signed.secretUid(), + signed.publicConfigMapUid(), + signed.prepublicationIntentDigest(), + signed.prepublicationReceiptDigest(), + signed.mountedObservationDigest(), + signed.readinessPlanDigest(), + signed.readinessEvidenceDigest(), + signed.expectedPublicJwksJson(), + activeMarkerJson(signed), + signed.status(), + signed.privatePromotionDispatched(), + null, + null, + null, + null, + null); + } + + private String operationDigestForGeneration() { + return generationOperationDigest; + } + + private boolean matchesPreparation( + PromotionPreparation preparation, + StoredGenerationOperation generation, + GenerationResult result, + EnrollmentIdentity enrollment) { + return generation.operationId().equals(preparation.generationOperationId()) + && result.equals(preparation.generationResult()) + && preparation.enrollmentIdentity().sameStablePins(enrollment) + && apiBindingDigest.equals(preparation.apiBindingDigest()) + && apiConfigRevision.equals(preparation.apiConfigRevision()) + && publicConfigMapUid.equals(preparation.publicConfigMapUid()) + && expectedPublicResourceVersion.equals(preparation.expectedPublicResourceVersion()) + && prepublicationIntentDigest.equals(preparation.prepublicationIntentDigest()) + && prepublicationReceiptDigest.equals(preparation.prepublicationReceiptDigest()) + && mountedObservationDigest.equals(preparation.mountedObservationDigest()) + && readinessPlanDigest.equals(preparation.readinessPlanDigest()) + && readinessEvidenceDigest.equals(preparation.readinessEvidenceDigest()) + && expectedPublicJwksJson.equals(preparation.expectedPublicJwksJson()) + && generationOperationId.equals(generation.operationId()) + && generationOperationDigest.equals(generation.operationDigest()) + && generationReceiptDigest.equals(result.receiptDigest()) + && secretUid.equals(result.secretUid()) + && expectedPrivateResourceVersion.equals(result.observedResourceVersion()) + && targetGeneration.equals(result.targetGeneration()) + && targetKid.equals(result.targetKid()) + && targetPublicKeyFingerprint.equals(result.publicKeyFingerprint()); + } + + private PromotionOperationEvidence publicEvidence() { + return new PromotionOperationEvidence( + operationId, + requestDigest, + expectedRecordVersion, + binding, + expectedPreviousActive, + expectedPreviousActive.map( + active -> publicFingerprintForKid(expectedPublicJwksJson, active.kid())), + expectedPublishedActive, + targetGeneration, + targetKid, + targetAlgorithm, + targetPublicKeyFingerprint, + trustFence, + generationOperationId, + generationOperationDigest, + generationReceiptDigest, + secretUid, + expectedPrivateResourceVersion, + apiBindingDigest, + apiConfigRevision, + publicConfigMapUid, + expectedPublicResourceVersion, + prepublicationIntentDigest, + prepublicationReceiptDigest, + mountedObservationDigest, + readinessPlanDigest, + readinessEvidenceDigest, + expectedPublicJwksJson, + expectedActiveMarkerJson, + status, + privatePromotionDispatched, + Optional.ofNullable(privatePromotionObservedResourceVersion), + Optional.ofNullable(privatePromotionReceiptDigest), + Optional.ofNullable(activeJwksObservedResourceVersion), + Optional.ofNullable(activeJwksPublicDataDigest), + Optional.ofNullable(activeJwksReceiptDigest)); + } + } + + public record PreparedGenerationEvidence( + DesiredState desiredState, + PromotionOperationEvidence promotion, + GenerationResult generationResult) { + public PreparedGenerationEvidence { + Objects.requireNonNull(desiredState); + Objects.requireNonNull(promotion); + Objects.requireNonNull(generationResult); + if (!"PREPARED".equals(promotion.status()) + || !promotion.generationOperationId().equals(generationResult.operationId())) { + throw new QuarantinedStateException("Prepared generation evidence is inconsistent"); + } + } + } + + /** Exact current owner-readback values required to freeze one PREPARED operation. */ + public record PromotionPreparation( + UUID generationOperationId, + GenerationResult generationResult, + EnrollmentIdentity enrollmentIdentity, + String apiBindingDigest, + String apiConfigRevision, + String publicConfigMapUid, + String expectedPublicResourceVersion, + String prepublicationIntentDigest, + String prepublicationReceiptDigest, + String mountedObservationDigest, + String readinessPlanDigest, + String readinessEvidenceDigest, + String expectedPublicJwksJson) { + public PromotionPreparation { + requireOperationId(generationOperationId); + Objects.requireNonNull(generationResult, "Persisted generation result is required"); + Objects.requireNonNull(enrollmentIdentity, "Pinned Account enrollment is required"); + requireMatch(SHA256_HEX, apiBindingDigest, "promotion API binding digest"); + requireMatch(CLUSTER_ID, apiConfigRevision, "promotion API config revision"); + requireUuid(publicConfigMapUid, "promotion public ConfigMap UID"); + requireMatch( + RESOURCE_VERSION, expectedPublicResourceVersion, "promotion ConfigMap resourceVersion"); + requireMatch(SHA256_HEX, prepublicationIntentDigest, "prepublication intent digest"); + requireMatch(SHA256_HEX, prepublicationReceiptDigest, "prepublication receipt digest"); + requireMatch(SHA256_HEX, mountedObservationDigest, "mounted observation digest"); + requireMatch(SHA256_HEX, readinessPlanDigest, "readiness plan digest"); + requireMatch(SHA256_HEX, readinessEvidenceDigest, "readiness evidence digest"); + if (expectedPublicJwksJson == null + || expectedPublicJwksJson.isBlank() + || expectedPublicJwksJson.getBytes(StandardCharsets.UTF_8).length > 256 * 1024) { + throw new PromotionPrerequisitesIncompleteException( + "Account promotion public projection is missing or oversized"); + } + } + } + + public record ActiveJwksPromotionObservation( + String configMapUid, + String priorResourceVersion, + String observedResourceVersion, + String jwksJson, + String activeMarkerJson) { + public ActiveJwksPromotionObservation { + requireUuid(configMapUid, "active public ConfigMap UID"); + requireMatch( + RESOURCE_VERSION, priorResourceVersion, "active ConfigMap prior resourceVersion"); + requireMatch( + RESOURCE_VERSION, observedResourceVersion, "active ConfigMap readback resourceVersion"); + if (priorResourceVersion.equals(observedResourceVersion)) { + throw new QuarantinedStateException( + "Account ACTIVE ConfigMap resourceVersion did not advance"); + } + if (jwksJson == null + || jwksJson.isBlank() + || jwksJson.getBytes(StandardCharsets.UTF_8).length > 256 * 1024 + || activeMarkerJson == null + || activeMarkerJson.isBlank() + || activeMarkerJson.getBytes(StandardCharsets.UTF_8).length > 16 * 1024) { + throw new QuarantinedStateException( + "Account ACTIVE ConfigMap projection is missing or oversized"); + } + } + } + + public record ActiveJwksPromotionReceipt( + UUID promotionOperationId, + String configMapUid, + String priorResourceVersion, + String observedResourceVersion, + String publicDataDigest, + String receiptDigest) { + public ActiveJwksPromotionReceipt { + requireOperationId(promotionOperationId); + requireUuid(configMapUid, "active public ConfigMap UID"); + requireMatch( + RESOURCE_VERSION, priorResourceVersion, "active ConfigMap prior resourceVersion"); + requireMatch( + RESOURCE_VERSION, observedResourceVersion, "active ConfigMap readback resourceVersion"); + requireMatch(SHA256_HEX, publicDataDigest, "active public ConfigMap data digest"); + requireMatch(SHA256_HEX, receiptDigest, "active public ConfigMap receipt digest"); + if (priorResourceVersion.equals(observedResourceVersion)) { + throw new QuarantinedStateException( + "Account ACTIVE ConfigMap resourceVersion did not advance"); + } + } + + private static ActiveJwksPromotionReceipt from( + StoredPromotion promotion, ActiveJwksPromotionObservation observation) { + String dataDigest = + AccountJwtJwksPublicationRepository.publicDataDigest( + observation.jwksJson(), observation.activeMarkerJson()); + return create( + promotion, + observation.configMapUid(), + observation.priorResourceVersion(), + observation.observedResourceVersion(), + dataDigest); + } + + private static ActiveJwksPromotionReceipt fromStored(StoredPromotion promotion) { + if (promotion.activeJwksObservedResourceVersion() == null + || promotion.activeJwksPublicDataDigest() == null + || promotion.activeJwksReceiptDigest() == null) { + throw new QuarantinedStateException("Committed signer has no active JWKS receipt"); + } + ActiveJwksPromotionReceipt calculated = + create( + promotion, + promotion.publicConfigMapUid(), + promotion.expectedPublicResourceVersion(), + promotion.activeJwksObservedResourceVersion(), + promotion.activeJwksPublicDataDigest()); + if (!calculated.receiptDigest().equals(promotion.activeJwksReceiptDigest())) { + throw new QuarantinedStateException("Committed active JWKS receipt digest is invalid"); + } + return calculated; + } + + private static ActiveJwksPromotionReceipt create( + StoredPromotion promotion, + String configMapUid, + String priorResourceVersion, + String observedResourceVersion, + String dataDigest) { + Map preimage = new LinkedHashMap<>(); + preimage.put("receiptVersion", "account-jwt-active-jwks-promotion-receipt/v1"); + preimage.put("promotionOperationId", promotion.operationId().toString()); + preimage.put("promotionRequestDigest", promotion.requestDigest()); + preimage.put("generationOperationId", promotion.generationOperationId().toString()); + preimage.put("generationOperationDigest", promotion.generationOperationDigest()); + preimage.put("generationReceiptDigest", promotion.generationReceiptDigest()); + preimage.put("configMapName", PUBLIC_JWKS_CONFIG_MAP_NAME); + preimage.put("configMapUid", configMapUid); + preimage.put("priorResourceVersion", priorResourceVersion); + preimage.put("observedResourceVersion", observedResourceVersion); + preimage.put("action", "MARK_ACTIVE"); + preimage.put("publicDataDigest", dataDigest); + return new ActiveJwksPromotionReceipt( + promotion.operationId(), + configMapUid, + priorResourceVersion, + observedResourceVersion, + dataDigest, + digest(preimage)); + } + } + + /** Durable non-authorizing result for Account's current committed active signer. */ + public record CommittedSignerEvidence( + PromotionOperationEvidence promotion, + GenerationResult generationResult, + DesiredState desiredState, + PrivatePromotionReceipt privateReceipt, + ActiveJwksPromotionReceipt publicReceipt) { + public CommittedSignerEvidence { + Objects.requireNonNull(promotion); + Objects.requireNonNull(generationResult); + Objects.requireNonNull(desiredState); + Objects.requireNonNull(privateReceipt); + Objects.requireNonNull(publicReceipt); + ActiveSigner target = new ActiveSigner(promotion.targetGeneration(), promotion.targetKid()); + if (!"COMMITTED".equals(promotion.status()) + || !promotion.operationId().equals(privateReceipt.promotionOperationId()) + || !promotion.operationId().equals(publicReceipt.promotionOperationId()) + || !promotion.generationOperationId().equals(generationResult.operationId()) + || desiredState.durableActive().filter(target::equals).isEmpty() + || desiredState.publishedActive().filter(target::equals).isEmpty() + || desiredState.preparedOperationId().isPresent()) { + throw new QuarantinedStateException("Committed signer evidence is inconsistent"); + } + } + } + + public record AbortedPromotion( + UUID operationId, + long desiredStateVersion, + Optional durableActive, + Optional publishedActive) { + public AbortedPromotion { + requireOperationId(operationId); + if (desiredStateVersion <= 0) + throw new IllegalArgumentException("Aborted state version is invalid"); + durableActive = Objects.requireNonNull(durableActive); + publishedActive = Objects.requireNonNull(publishedActive); + if (!durableActive.equals(publishedActive)) { + throw new QuarantinedStateException("Aborted signer operation changed active fences"); + } + } + } + + /** Public-only immutable promotion row needed by the materializer and Account reconciler. */ + public record PromotionOperationEvidence( + UUID operationId, + String requestDigest, + long expectedRecordVersion, + Binding binding, + Optional expectedPreviousActive, + Optional expectedPreviousPublicKeyFingerprint, + Optional expectedPublishedActive, + String targetGeneration, + String targetKid, + String targetAlgorithm, + String targetPublicKeyFingerprint, + TrustFence trustFence, + UUID generationOperationId, + String generationOperationDigest, + String generationReceiptDigest, + String secretUid, + String expectedPrivateResourceVersion, + String apiBindingDigest, + String apiConfigRevision, + String publicConfigMapUid, + String expectedPublicResourceVersion, + String prepublicationIntentDigest, + String prepublicationReceiptDigest, + String mountedObservationDigest, + String readinessPlanDigest, + String readinessEvidenceDigest, + String expectedPublicJwksJson, + String expectedActiveMarkerJson, + String status, + boolean privatePromotionDispatched, + Optional privatePromotionObservedResourceVersion, + Optional privatePromotionReceiptDigest, + Optional activeJwksObservedResourceVersion, + Optional activeJwksPublicDataDigest, + Optional activeJwksReceiptDigest) { + public PromotionOperationEvidence { + Objects.requireNonNull(operationId); + requireMatch(SHA256_HEX, requestDigest, "promotion request digest"); + Objects.requireNonNull(binding); + expectedPreviousActive = Objects.requireNonNull(expectedPreviousActive); + expectedPreviousPublicKeyFingerprint = + Objects.requireNonNull(expectedPreviousPublicKeyFingerprint); + expectedPublishedActive = Objects.requireNonNull(expectedPublishedActive); + if (expectedPreviousActive.isPresent() != expectedPreviousPublicKeyFingerprint.isPresent()) { + throw new QuarantinedStateException("Promotion prior public identity is incomplete"); + } + expectedPreviousPublicKeyFingerprint.ifPresent( + value -> requireMatch(SHA256_HEX, value, "prior public-key fingerprint")); + Objects.requireNonNull(trustFence); + Objects.requireNonNull(generationOperationId); + requireMatch(SHA256_HEX, generationOperationDigest, "generation operation digest"); + requireMatch(SHA256_HEX, generationReceiptDigest, "generation receipt digest"); + privatePromotionObservedResourceVersion = + Objects.requireNonNull(privatePromotionObservedResourceVersion); + privatePromotionReceiptDigest = Objects.requireNonNull(privatePromotionReceiptDigest); + activeJwksObservedResourceVersion = Objects.requireNonNull(activeJwksObservedResourceVersion); + activeJwksPublicDataDigest = Objects.requireNonNull(activeJwksPublicDataDigest); + activeJwksReceiptDigest = Objects.requireNonNull(activeJwksReceiptDigest); + } + } + + public record PublicKeyIdentity(String generation, String kid, String publicKeyFingerprint) { + public PublicKeyIdentity { + parseGeneration(generation); + requireMatch(KID, kid, "observed public key kid"); + requireMatch(SHA256_HEX, publicKeyFingerprint, "observed public key fingerprint"); + } + } + + public record PrivatePromotionObservation( + UUID promotionOperationId, + String promotionRequestDigest, + UUID generationOperationId, + String generationOperationDigest, + String secretUid, + String expectedPriorResourceVersion, + String observedResourceVersion, + PublicKeyIdentity current, + Optional previous, + List resultingSlots) { + public PrivatePromotionObservation { + requireOperationId(promotionOperationId); + requireMatch(SHA256_HEX, promotionRequestDigest, "promotion request digest"); + requireOperationId(generationOperationId); + requireMatch(SHA256_HEX, generationOperationDigest, "generation operation digest"); + requireUuid(secretUid, "observed fixed Secret UID"); + requireMatch(RESOURCE_VERSION, expectedPriorResourceVersion, "expected Secret version"); + requireMatch(RESOURCE_VERSION, observedResourceVersion, "observed Secret version"); + Objects.requireNonNull(current); + previous = Objects.requireNonNull(previous); + resultingSlots = List.copyOf(resultingSlots); + if (expectedPriorResourceVersion.equals(observedResourceVersion) + || !(resultingSlots.equals(List.of("current")) + || resultingSlots.equals(List.of("current", "previous")))) { + throw new QuarantinedStateException("Private promotion readback identity is malformed"); + } + } + } + + public record PrivatePromotionReceipt( + UUID promotionOperationId, + UUID generationOperationId, + String observedResourceVersion, + String receiptDigest) { + public PrivatePromotionReceipt { + requireOperationId(promotionOperationId); + requireOperationId(generationOperationId); + requireMatch(RESOURCE_VERSION, observedResourceVersion, "private promotion readback version"); + requireMatch(SHA256_HEX, receiptDigest, "private promotion receipt digest"); + } + + private static PrivatePromotionReceipt from( + StoredPromotion promotion, PrivatePromotionObservation observation) { + Map preimage = new LinkedHashMap<>(); + preimage.put("receiptVersion", 1); + preimage.put("promotionOperationId", promotion.operationId().toString()); + preimage.put("promotionRequestDigest", promotion.requestDigest()); + preimage.put("generationOperationId", promotion.generationOperationId().toString()); + preimage.put("generationOperationDigest", promotion.generationOperationDigest()); + preimage.put("generationReceiptDigest", promotion.generationReceiptDigest()); + preimage.put("secretResource", Map.of("kind", "Secret", "name", PRIVATE_SECRET_NAME)); + preimage.put("secretUid", observation.secretUid()); + preimage.put("expectedPriorResourceVersion", observation.expectedPriorResourceVersion()); + preimage.put("observedResourceVersion", observation.observedResourceVersion()); + preimage.put("action", "PROMOTE_PENDING"); + preimage.put("resultingSlots", observation.resultingSlots()); + preimage.put("current", publicKeyIdentityMap(observation.current())); + preimage.put( + "previous", + observation + .previous() + .map(AccountJwtSignerDesiredStateRepository::publicKeyIdentityMap) + .orElseGet(() -> Map.of("present", false))); + return new PrivatePromotionReceipt( + promotion.operationId(), + promotion.generationOperationId(), + observation.observedResourceVersion(), + digest(preimage)); + } + + private static PrivatePromotionReceipt fromStored(StoredPromotion promotion) { + if (promotion.privatePromotionObservedResourceVersion() == null + || promotion.privatePromotionReceiptDigest() == null) { + throw new QuarantinedStateException("Committed signer has no private promotion receipt"); + } + Optional previous = + promotion + .expectedPreviousActive() + .map( + active -> + new PublicKeyIdentity( + active.generation(), + active.kid(), + publicFingerprintForKid( + promotion.expectedPublicJwksJson(), active.kid()))); + PrivatePromotionReceipt calculated = + from( + promotion, + new PrivatePromotionObservation( + promotion.operationId(), + promotion.requestDigest(), + promotion.generationOperationId(), + promotion.generationOperationDigest(), + promotion.secretUid(), + promotion.expectedPrivateResourceVersion(), + promotion.privatePromotionObservedResourceVersion(), + new PublicKeyIdentity( + promotion.targetGeneration(), + promotion.targetKid(), + promotion.targetPublicKeyFingerprint()), + previous, + previous.isPresent() ? List.of("current", "previous") : List.of("current"))); + if (!calculated.receiptDigest().equals(promotion.privatePromotionReceiptDigest())) { + throw new QuarantinedStateException( + "Committed private promotion receipt digest is invalid"); + } + return calculated; + } + } + + private static Map publicKeyIdentityMap(PublicKeyIdentity identity) { + return Map.of( + "generation", identity.generation(), + "kid", identity.kid(), + "publicKeyFingerprint", identity.publicKeyFingerprint()); + } + + public record PreparedPromotion(UUID operationId, String requestDigest, String status) { + public PreparedPromotion { + requireOperationId(operationId); + requireMatch(SHA256_HEX, requestDigest, "prepared promotion digest"); + if (!"PREPARED".equals(status)) { + throw new IllegalArgumentException("Only PREPARED JWT signer operations are represented"); + } + } + } + + private static String generationRequestDigest( + String operationDigest, String observationDigest, String secretUid, String resourceVersion) { + return digest( + Map.of( + "digestVersion", GENERATION_REQUEST_DIGEST_VERSION, + "operationDigest", operationDigest, + "observationDigest", observationDigest, + "secretUid", secretUid, + "expectedPriorResourceVersion", resourceVersion, + "target", "pending")); + } + + public static class MissingDesiredStateException extends IllegalStateException { + public MissingDesiredStateException(String environmentId) { + super("Account JWT signer desired state is missing for environment " + environmentId); + } + } + + public static class MissingGenerationOperationException extends IllegalStateException { + public MissingGenerationOperationException(String message) { + super(message); + } + } + + public static class MissingGenerationObservationException extends IllegalStateException { + public MissingGenerationObservationException(String message) { + super(message); + } + } + + public static class StaleGenerationOperationException extends IllegalStateException { + public StaleGenerationOperationException(String message) { + super(message); + } + } + + public static class BindingMismatchException extends IllegalStateException { + public BindingMismatchException(String message) { + super(message); + } + } + + public static class VersionConflictException extends IllegalStateException { + public VersionConflictException(String message) { + super(message); + } + } + + public static class IdempotencyConflictException extends IllegalStateException { + public IdempotencyConflictException(String message) { + super(message); + } + } + + public static class QuarantinedStateException extends IllegalStateException { + public QuarantinedStateException(String message) { + super(message); + } + + public QuarantinedStateException(String message, Throwable cause) { + super(message, cause); + } + } + + public static class PromotionPrerequisitesIncompleteException extends IllegalStateException { + public PromotionPrerequisitesIncompleteException(String message) { + super(message); + } + } + + public static class NoPreparedPromotionException extends IllegalStateException { + public NoPreparedPromotionException() { + super("Account has no PREPARED JWT signer promotion"); + } + } + + public static class StorageUnavailableException extends IllegalStateException { + public StorageUnavailableException(String message) { + super(message); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtValidatorInventoryRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtValidatorInventoryRepository.java new file mode 100644 index 0000000000..4c3558b831 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtValidatorInventoryRepository.java @@ -0,0 +1,280 @@ +package net.firedevops.firemud.accountservice.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.security.MessageDigest; +import java.time.Instant; +import java.util.Arrays; +import java.util.HexFormat; +import java.util.Objects; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.Binding; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.TrustFence; +import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource.InventorySnapshot; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Immutable persistence for an Account-observed, non-authorizing validator inventory snapshot. The + * table stores only the source's closed canonical public/runtime observation, never API response + * objects or credentials. + */ +@Repository +public class AccountJwtValidatorInventoryRepository { + public static final int MAX_SNAPSHOT_BYTES = 4 * 1024 * 1024; + private static final String TABLE = "account_jwt_validator_inventory_snapshots"; + private static final Pattern DIGEST = Pattern.compile("[0-9a-f]{64}"); + + private final DSLContext dsl; + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "The constructor only validates its trusted injected DSLContext; it performs no I/O or resource acquisition and defines no finalizer.") + public AccountJwtValidatorInventoryRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl, "DSLContext is required"); + } + + /** Inserts once or proves that a same-digest retry reads back the exact immutable bytes. */ + @Transactional(propagation = Propagation.MANDATORY) + public StoredSnapshot persistOrReadback( + InventorySnapshot snapshot, Binding binding, TrustFence trustFence) { + requireWritableAccountTransaction(); + Objects.requireNonNull(snapshot, "Owner-observed inventory snapshot is required"); + requireBinding(snapshot, binding, trustFence); + byte[] canonicalBytes = snapshot.canonicalBytes(); + requireSnapshotBytes(canonicalBytes, snapshot.digest()); + dsl.execute( + "INSERT INTO " + + TABLE + + " (snapshot_digest, environment_id, cluster_id, cluster_incarnation_uid, " + + "kubernetes_namespace, namespace_uid, api_binding_revision, api_binding_digest, " + + "inventory_binding_revision, inventory_binding_digest, observed_at, canonical_snapshot) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) " + + "ON CONFLICT (snapshot_digest) DO NOTHING", + snapshot.digest(), + snapshot.environmentId(), + snapshot.clusterId(), + UUID.fromString(snapshot.clusterIncarnationUid()), + snapshot.namespace(), + UUID.fromString(snapshot.namespaceUid()), + snapshot.apiBindingRevision(), + snapshot.apiBindingDigest(), + snapshot.inventoryBindingRevision(), + snapshot.inventoryBindingDigest(), + snapshot.observedAt().toString(), + canonicalBytes); + Record row = + dsl.fetchOne( + "SELECT * FROM " + TABLE + " WHERE snapshot_digest = ? FOR UPDATE", snapshot.digest()); + StoredSnapshot stored = decode(row); + requireSameSnapshot(snapshot, stored); + requireBinding(stored, binding, trustFence); + return stored; + } + + /** Reads the exact previously persisted snapshot and rechecks its Account binding. */ + @Transactional(propagation = Propagation.MANDATORY) + public StoredSnapshot readRequired(String digest, Binding binding, TrustFence trustFence) { + requireAccountTransaction(); + if (digest == null || !DIGEST.matcher(digest).matches()) { + throw new InventorySnapshotUnavailableException(); + } + Record row = + dsl.fetchOne("SELECT * FROM " + TABLE + " WHERE snapshot_digest = ? FOR KEY SHARE", digest); + StoredSnapshot stored = decode(row); + requireBinding(stored, binding, trustFence); + return stored; + } + + private static StoredSnapshot decode(Record row) { + if (row == null) { + throw new InventorySnapshotUnavailableException(); + } + try { + String digest = row.get("snapshot_digest", String.class); + byte[] bytes = row.get("canonical_snapshot", byte[].class); + requireSnapshotBytes(bytes, digest); + StoredSnapshot stored = + new StoredSnapshot( + digest, + row.get("environment_id", String.class), + row.get("cluster_id", String.class), + row.get("cluster_incarnation_uid", UUID.class).toString(), + row.get("kubernetes_namespace", String.class), + row.get("namespace_uid", UUID.class).toString(), + row.get("api_binding_revision", String.class), + row.get("api_binding_digest", String.class), + row.get("inventory_binding_revision", String.class), + row.get("inventory_binding_digest", String.class), + Instant.parse(row.get("observed_at", String.class)), + bytes); + return stored; + } catch (InventorySnapshotUnavailableException failure) { + throw failure; + } catch (RuntimeException failure) { + throw new InventorySnapshotUnavailableException(); + } + } + + private static void requireSnapshotBytes(byte[] bytes, String digest) { + if (bytes == null + || bytes.length < 2 + || bytes.length > MAX_SNAPSHOT_BYTES + || digest == null + || !DIGEST.matcher(digest).matches() + || !digest(bytes).equals(digest)) { + throw new InventorySnapshotUnavailableException(); + } + } + + private static String digest(byte[] bytes) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (Exception failure) { + throw new InventorySnapshotUnavailableException(); + } + } + + private static void requireSameSnapshot(InventorySnapshot expected, StoredSnapshot actual) { + // A content digest can be observed again later. Keep the first persisted timestamp immutable; + // callers separately use the fresh observation's timestamp for the bounded freshness check. + if (!expected.digest().equals(actual.digest()) + || !expected.environmentId().equals(actual.environmentId()) + || !expected.clusterId().equals(actual.clusterId()) + || !expected.clusterIncarnationUid().equals(actual.clusterIncarnationUid()) + || !expected.namespace().equals(actual.namespace()) + || !expected.namespaceUid().equals(actual.namespaceUid()) + || !expected.apiBindingRevision().equals(actual.apiBindingRevision()) + || !expected.apiBindingDigest().equals(actual.apiBindingDigest()) + || !expected.inventoryBindingRevision().equals(actual.inventoryBindingRevision()) + || !expected.inventoryBindingDigest().equals(actual.inventoryBindingDigest()) + || !MessageDigest.isEqual(expected.canonicalBytes(), actual.canonicalBytes())) { + throw new InventorySnapshotUnavailableException(); + } + } + + private static void requireBinding( + InventorySnapshot snapshot, Binding binding, TrustFence trustFence) { + Objects.requireNonNull(binding, "Account generation binding is required"); + Objects.requireNonNull(trustFence, "Account trust fence is required"); + if (!binding.environmentId().equals(snapshot.environmentId()) + || !binding.clusterId().equals(snapshot.clusterId()) + || !binding.namespace().equals(snapshot.namespace()) + || !trustFence.expectedClusterIncarnationUid().equals(snapshot.clusterIncarnationUid()) + || !trustFence.expectedNamespaceUid().equals(snapshot.namespaceUid())) { + throw new InventorySnapshotUnavailableException(); + } + } + + private static void requireBinding( + StoredSnapshot snapshot, Binding binding, TrustFence trustFence) { + Objects.requireNonNull(binding, "Account generation binding is required"); + Objects.requireNonNull(trustFence, "Account trust fence is required"); + if (!binding.environmentId().equals(snapshot.environmentId()) + || !binding.clusterId().equals(snapshot.clusterId()) + || !binding.namespace().equals(snapshot.namespace()) + || !trustFence.expectedClusterIncarnationUid().equals(snapshot.clusterIncarnationUid()) + || !trustFence.expectedNamespaceUid().equals(snapshot.namespaceUid())) { + throw new InventorySnapshotUnavailableException(); + } + } + + private static void requireAccountTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException("An owning Account transaction is required"); + } + } + + private static void requireWritableAccountTransaction() { + requireAccountTransaction(); + if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException("A writable Account transaction is required"); + } + } + + public record StoredSnapshot( + String digest, + String environmentId, + String clusterId, + String clusterIncarnationUid, + String namespace, + String namespaceUid, + String apiBindingRevision, + String apiBindingDigest, + String inventoryBindingRevision, + String inventoryBindingDigest, + Instant observedAt, + byte[] canonicalBytes) { + public StoredSnapshot { + Objects.requireNonNull(digest); + Objects.requireNonNull(environmentId); + Objects.requireNonNull(clusterId); + Objects.requireNonNull(clusterIncarnationUid); + Objects.requireNonNull(namespace); + Objects.requireNonNull(namespaceUid); + Objects.requireNonNull(apiBindingRevision); + Objects.requireNonNull(apiBindingDigest); + Objects.requireNonNull(inventoryBindingRevision); + Objects.requireNonNull(inventoryBindingDigest); + Objects.requireNonNull(observedAt); + canonicalBytes = canonicalBytes.clone(); + requireSnapshotBytes(canonicalBytes, digest); + } + + @Override + public byte[] canonicalBytes() { + return canonicalBytes.clone(); + } + + @Override + public boolean equals(Object other) { + if (this == other) { + return true; + } + if (!(other instanceof StoredSnapshot that)) { + return false; + } + return digest.equals(that.digest) + && environmentId.equals(that.environmentId) + && clusterId.equals(that.clusterId) + && clusterIncarnationUid.equals(that.clusterIncarnationUid) + && namespace.equals(that.namespace) + && namespaceUid.equals(that.namespaceUid) + && apiBindingRevision.equals(that.apiBindingRevision) + && apiBindingDigest.equals(that.apiBindingDigest) + && inventoryBindingRevision.equals(that.inventoryBindingRevision) + && inventoryBindingDigest.equals(that.inventoryBindingDigest) + && observedAt.equals(that.observedAt) + && Arrays.equals(canonicalBytes, that.canonicalBytes); + } + + @Override + public int hashCode() { + return 31 + * Objects.hash( + digest, + environmentId, + clusterId, + clusterIncarnationUid, + namespace, + namespaceUid, + apiBindingRevision, + apiBindingDigest, + inventoryBindingRevision, + inventoryBindingDigest, + observedAt) + + Arrays.hashCode(canonicalBytes); + } + } + + public static final class InventorySnapshotUnavailableException extends RuntimeException { + public InventorySnapshotUnavailableException() { + super("Account validator inventory snapshot is unavailable or inconsistent"); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiCurrentActorVerifier.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiCurrentActorVerifier.java new file mode 100644 index 0000000000..52dc1e045e --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiCurrentActorVerifier.java @@ -0,0 +1,848 @@ +package net.firedevops.firemud.accountservice.service.session; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.Clock; +import java.time.Duration; +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.Set; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.accountservice.config.AccountJwtJwksApiBinding; +import net.firedevops.firemud.accountservice.config.AccountJwtSignerMaterializerTrustBinding; +import net.firedevops.firemud.accountservice.dto.TenantAuthorityEventV1Codec.Event; +import net.firedevops.firemud.accountservice.entity.AccountTenantMembership; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.CompositeSnapshot; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository.IssuerAccountSourceSnapshot; +import net.firedevops.firemud.accountservice.repository.AccountControlUiCommittedIssuanceRepository; +import net.firedevops.firemud.accountservice.repository.AccountControlUiCommittedIssuanceRepository.CommittedIssuance; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.Binding; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.CustodyMode; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.TrustFence; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.PairAuthority; +import net.firedevops.firemud.accountservice.repository.AccountTenantAuthorityEventRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository.RoleSnapshot; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.MembershipEvent; +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.AccountPublicJwksCache.PublicJwksSnapshot; +import net.firedevops.firemud.common.security.AccountPublicJwksCache.SourceIdentity; +import net.firedevops.firemud.common.security.ControlUiJwtProfileValidator; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.core.type.TypeReference; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.json.JsonMapper; + +/** + * Read-only Account verification of a signed control-ui actor against committed issuance, + * Coordination, protected signer/JWKS state, and current Account tenant membership sources. + * + *

The returned object is authenticated-current actor evidence only. This class does not issue or + * redeem operator references, select a privileged route, or turn a creator grant into owner + * authority. It deliberately denies global-role claims; callers must perform the approved route + * predicate separately against this current tenant-scoped evidence. + */ +public final class AccountControlUiCurrentActorVerifier { + private static final String ISSUER = "firemud-account-service"; + private static final int MAX_BUNDLE_BYTES = 131072; + private static final Pattern DIGEST = Pattern.compile("[0-9a-f]{64}"); + private static final Set SIGNER_RECEIPT_FIELDS = + Set.of( + "schema", + "environmentId", + "clusterId", + "namespace", + "clusterIncarnationUid", + "namespaceUid", + "trustBindingDigest", + "trustConfigRevision", + "apiBindingDigest", + "apiConfigRevision", + "promotionOperationId", + "promotionRequestDigest", + "generationOperationId", + "signerGeneration", + "kid", + "algorithm", + "publicKeyFingerprint", + "privateReceiptDigest", + "privateResourceVersion", + "publicReceiptDigest", + "publicResourceVersion", + "publicConfigMapUid", + "publicDataDigest"); + private static final Set PENDING_RECEIPT_FIELDS = + Set.of( + "schema", + "tokenHash", + "recordDigest", + "expiryMillis", + "aclIdentity", + "localAofCount", + "replicaAofCount"); + private static final Set BUNDLE_FIELDS = + Set.of( + "schema", + "bundleRef", + "snapshotIdentity", + "evaluationIdentity", + "issuer", + "profile", + "audience", + "scope", + "operation", + "tokenIdentity", + "authorityTuple", + "membershipVersion", + "issuanceFence", + "authoritySourceVersions", + "accountIdentitySource", + "outboxCheckpoints", + "roleEvidence"); + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + private static final TypeReference> OBJECT = new TypeReference<>() {}; + private static final ExplicitRouteProfilePolicy POLICY = + new ExplicitRouteProfilePolicy( + "account-control-ui-current-actor", + ControlUiJwtProfileValidator.PROFILE, + ControlUiJwtProfileValidator.TOKEN_TYPE, + ISSUER, + ControlUiJwtProfileValidator.AUDIENCE, + ControlUiJwtProfileValidator.REQUIRED_CLAIMS, + Set.of(), + 300, + 0, + 16384, + claims -> ControlUiJwtProfileValidator.validateClaims(claims, 1)); + + private final AccountJwtJwksTrustedSource publicJwks; + private final AccountJwtSignerDesiredStateRepository signerStates; + private final AccountJwtSignerMaterializerTrustBinding materializerTrust; + private final AccountJwtJwksApiBinding jwksApiBinding; + private final AccountControlUiRegistryReader registry; + private final AccountControlUiCommittedIssuanceRepository issuances; + private final AccountAuthoritySourceEvidenceRepository sourceEvidence; + private final AccountAuthorityGenerationRepository generations; + private final AccountTenantAuthorityEventRepository tenantEvents; + private final AccountTenantMembershipRepository memberships; + private final AccountMembershipPairAuthorityRepository membershipPairs; + private final AccountTenantMembershipRoleSnapshotRepository roleSnapshots; + private final AccountAuthorityOutboxRepository outbox; + private final TransactionTemplate accountTransaction; + private final Clock clock; + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = + "Injected Account repositories are shared owner services; they must retain their transaction and current-state identity rather than be copied.") + public AccountControlUiCurrentActorVerifier( + AccountJwtJwksTrustedSource publicJwks, + AccountJwtSignerDesiredStateRepository signerStates, + AccountJwtSignerMaterializerTrustBinding materializerTrust, + AccountJwtJwksApiBinding jwksApiBinding, + AccountControlUiRegistryReader registry, + AccountControlUiCommittedIssuanceRepository issuances, + AccountAuthoritySourceEvidenceRepository sourceEvidence, + AccountAuthorityGenerationRepository generations, + AccountTenantAuthorityEventRepository tenantEvents, + AccountTenantMembershipRepository memberships, + AccountMembershipPairAuthorityRepository membershipPairs, + AccountTenantMembershipRoleSnapshotRepository roleSnapshots, + AccountAuthorityOutboxRepository outbox, + PlatformTransactionManager transactionManager, + Clock clock) { + this.publicJwks = Objects.requireNonNull(publicJwks); + this.signerStates = Objects.requireNonNull(signerStates); + this.materializerTrust = Objects.requireNonNull(materializerTrust); + this.jwksApiBinding = Objects.requireNonNull(jwksApiBinding); + this.registry = Objects.requireNonNull(registry); + this.issuances = Objects.requireNonNull(issuances); + this.sourceEvidence = Objects.requireNonNull(sourceEvidence); + this.generations = Objects.requireNonNull(generations); + this.tenantEvents = Objects.requireNonNull(tenantEvents); + this.memberships = Objects.requireNonNull(memberships); + this.membershipPairs = Objects.requireNonNull(membershipPairs); + this.roleSnapshots = Objects.requireNonNull(roleSnapshots); + this.outbox = Objects.requireNonNull(outbox); + this.clock = Objects.requireNonNull(clock); + accountTransaction = new TransactionTemplate(Objects.requireNonNull(transactionManager)); + accountTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + accountTransaction.setReadOnly(false); + } + + /** Verifies one signed actor for its selected canonical tenant; no authorization is returned. */ + public CurrentActor verify(String compactJwt, UUID selectedTenant) { + outsideSql(); + requireTenant(selectedTenant); + byte[] compactBytes = compactBytes(compactJwt); + SourceIdentity pin = publicJwks.sourceIdentity(); + AccountPublicJwksCache cache = + new AccountPublicJwksCache(publicJwks, pin, clock, Duration.ofSeconds(30)); + VerifiedClaims signed = + new AccountAsymmetricJwtVerifier(cache, clock).verify(compactJwt, POLICY); + PublicJwksSnapshot currentJwks = publicJwks.load(); + String tokenHash = sha256(compactBytes); + byte[] activeRegistry = registry.readActive(tokenHash); + + CurrentActor result = + accountTransaction.execute( + ignored -> + verifyOwnerState( + tokenHash, selectedTenant, signed, pin, currentJwks, activeRegistry)); + if (result == null) { + throw denied(); + } + return result; + } + + private CurrentActor verifyOwnerState( + String tokenHash, + UUID selectedTenant, + VerifiedClaims signed, + SourceIdentity pin, + PublicJwksSnapshot currentJwks, + byte[] activeRegistry) { + Map claims = signed.claims(); + UUID accountId = uuid(claims.get("accountId")); + UUID tokenTenant = selectedScopedTenant(claims, selectedTenant); + if (!selectedTenant.equals(tokenTenant) || claims.containsKey("globalRoles")) { + throw denied(); + } + CommittedIssuance issuance = + issuances + .readCommitted(tokenHash) + .orElseThrow(AccountControlUiCurrentActorVerifier::denied); + Map registryRecord = + AccountControlUiRegistryReader.parseActiveRecord(activeRegistry, tokenHash); + if (!ISSUER.equals(claims.get("iss")) + || !claims.get("sub").equals(accountId.toString()) + || !issuance.tokenHash().equals(tokenHash) + || !issuance.accountId().equals(accountId) + || !issuance.tenantId().equals(selectedTenant) + || !issuance.tokenJti().equals(uuid(claims.get("jti"))) + || !issuance.requestId().equals(uuid(registryRecord.get("requestId"))) + || !issuance.operationId().equals(uuid(registryRecord.get("operationId"))) + || !Arrays.equals(activeRegistry, issuance.activeRegistry()) + || !Arrays.equals(canonicalBytes(claims), issuance.claims()) + || !signed.keyId().equals(registryRecord.get("kid")) + || !accountId.toString().equals(registryRecord.get("accountId")) + || !claims.get("jti").equals(registryRecord.get("jti")) + || !canonicalMapEquals(registryRecord.get("authorityTuple"), claims.get("authorityTuple")) + || !canonicalMapEquals( + registryRecord.get("membershipVersion"), claims.get("membershipVersion")) + || !numericEquals( + registryRecord.get("tokenGeneration"), positiveLong(claims.get("tokenGeneration"))) + || !numericEquals( + registryRecord.get("issuanceFence"), positiveLong(claims.get("issuanceFence"))) + || !numericEquals(claims.get("iat"), issuance.issuedAtEpochSecond()) + || !numericEquals(claims.get("nbf"), issuance.issuedAtEpochSecond()) + || !numericEquals(claims.get("exp"), issuance.expiresAtEpochSecond()) + || !numericEquals(registryRecord.get("iat"), issuance.issuedAtEpochSecond()) + || !numericEquals(registryRecord.get("nbf"), issuance.issuedAtEpochSecond()) + || !numericEquals(registryRecord.get("exp"), issuance.expiresAtEpochSecond()) + || !Arrays.equals(issuance.pendingRegistry(), derivePendingRegistry(activeRegistry))) { + throw denied(); + } + requireBundle(issuance, claims, registryRecord); + requirePendingReceipt(issuance); + requireSignerReceipt(issuance, signed.keyId(), pin, currentJwks); + return requireCurrentAccountAuthority(issuance, claims, selectedTenant, tokenHash); + } + + private void requireBundle( + CommittedIssuance issuance, Map claims, Map registryRecord) { + Map storedClaims = parseCanonicalObject(issuance.claims(), 16384); + Map bundle = parseCanonicalObject(issuance.bundle(), MAX_BUNDLE_BYTES); + Map bundleRef = object(bundle.get("bundleRef")); + Map scope = object(bundle.get("scope")); + Map operation = object(bundle.get("operation")); + Map tokenIdentity = object(bundle.get("tokenIdentity")); + Map roleEvidence = object(bundle.get("roleEvidence")); + if (!bundle.keySet().equals(BUNDLE_FIELDS) + || !bundleRef + .keySet() + .equals(Set.of("bundleVersion", "sourceVersion", "sourceFence", "linearization")) + || !scope.keySet().equals(Set.of("kind", "accountId", "tenantIds")) + || !operation + .keySet() + .equals( + Set.of( + "operationId", + "requestId", + "requestDigest", + "callerWorkload", + "callerContextId", + "accountId")) + || !tokenIdentity.keySet().equals(Set.of("jti", "tokenGeneration", "iat", "nbf", "exp")) + || !roleEvidence.keySet().equals(Set.of("scopedRoles", "freshnessSource")) + || !Arrays.equals(canonicalBytes(claims), canonicalBytes(storedClaims)) + || !"account-auth-evidence-bundle/v1".equals(bundle.get("schema")) + || !ISSUER.equals(bundle.get("issuer")) + || !"control-ui".equals(bundle.get("profile")) + || !"control-ui".equals(bundle.get("audience")) + || !issuance.operationId().toString().equals(operation.get("operationId")) + || !issuance.requestId().toString().equals(operation.get("requestId")) + || !issuance.requestDigest().equals(operation.get("requestDigest")) + || !issuance.accountId().toString().equals(operation.get("accountId")) + || !issuance.callerWorkload().equals(operation.get("callerWorkload")) + || !issuance.callerContextId().toString().equals(operation.get("callerContextId")) + || !issuance.accountId().toString().equals(scope.get("accountId")) + || !List.of(issuance.tenantId().toString()).equals(scope.get("tenantIds")) + || !"TENANT".equals(scope.get("kind")) + || !canonicalMapEquals(bundle.get("authorityTuple"), claims.get("authorityTuple")) + || !canonicalMapEquals(bundle.get("membershipVersion"), claims.get("membershipVersion")) + || !numericEquals(bundle.get("issuanceFence"), positiveLong(claims.get("issuanceFence"))) + || !canonicalMapEquals( + bundle.get("authoritySourceVersions"), registryRecord.get("authoritySourceVersions")) + || !canonicalMapEquals(tokenIdentity, tokenIdentity(claims)) + || !canonicalMapEquals(roleEvidence.get("scopedRoles"), claims.get("scopedRoles"))) { + throw denied(); + } + parseCanonicalObject(issuance.source(), 131072); + String sourceIdentity = sha256(issuance.source()); + if (!sourceIdentity.equals(bundle.get("snapshotIdentity")) + || !sourceIdentity.equals(roleEvidence.get("freshnessSource"))) { + throw denied(); + } + Map expectedReference = new LinkedHashMap<>(bundleRef); + expectedReference.put("canonicalSha256", sha256(issuance.bundle())); + if (!canonicalMapEquals(expectedReference, registryRecord.get("authEvidenceBundle"))) { + throw denied(); + } + Map evaluation = + Map.of( + "operation", operation, + "claims", claims, + "bundleRef", bundleRef, + "snapshotIdentity", sourceIdentity); + if (!sha256(canonicalBytes(evaluation)).equals(bundle.get("evaluationIdentity"))) { + throw denied(); + } + } + + private void requirePendingReceipt(CommittedIssuance issuance) { + Map receipt = parseCanonicalObject(issuance.pendingReceipt(), 8192); + if (!receipt.keySet().equals(PENDING_RECEIPT_FIELDS) + || !"account-control-ui-pending-readback/v1".equals(receipt.get("schema")) + || !issuance.tokenHash().equals(receipt.get("tokenHash")) + || !sha256(issuance.pendingRegistry()).equals(receipt.get("recordDigest")) + || !"account_coord_app".equals(receipt.get("aclIdentity")) + || !numericEquals(receipt.get("expiryMillis"), issuance.expiryMillis()) + || !atLeastOne(receipt.get("localAofCount")) + || !atLeastOne(receipt.get("replicaAofCount"))) { + throw denied(); + } + } + + private void requireSignerReceipt( + CommittedIssuance issuance, + String verifiedKid, + SourceIdentity pin, + PublicJwksSnapshot currentJwks) { + Map receipt = parseCanonicalObject(issuance.signerReceipt(), 65536); + Optional fingerprint = + AccountJwtJwksTrustedSource.publicKeyFingerprint(currentJwks, pin, verifiedKid); + Map registryRecord = + AccountControlUiRegistryReader.parseActiveRecord( + issuance.activeRegistry(), issuance.tokenHash()); + if (!receipt.keySet().equals(SIGNER_RECEIPT_FIELDS) + || !"account-control-ui-committed-signer/v1".equals(receipt.get("schema")) + || !pin.environmentId().equals(receipt.get("environmentId")) + || !pin.clusterId().equals(receipt.get("clusterId")) + || !pin.clusterIncarnationUid().equals(receipt.get("clusterIncarnationUid")) + || !pin.namespace().equals(receipt.get("namespace")) + || !pin.namespaceUid().equals(receipt.get("namespaceUid")) + || !pin.configMapUid().equals(receipt.get("publicConfigMapUid")) + || !pin.bindingRevision().equals(receipt.get("apiConfigRevision")) + || !verifiedKid.equals(receipt.get("kid")) + || !verifiedKid.equals(registryRecord.get("kid")) + || !"RS256".equals(receipt.get("algorithm")) + || !fingerprint.orElse("").equals(receipt.get("publicKeyFingerprint")) + || !registryRecord.get("signerGeneration").equals(receipt.get("signerGeneration")) + || !issuance.operationId().toString().equals(registryRecord.get("operationId")) + || !issuance.requestId().toString().equals(registryRecord.get("requestId")) + || !issuance.requestDigest().equals(registryRecord.get("requestDigest")) + || !sha256(issuance.signerReceipt()) + .equals(registryRecord.get("originalSignerReceiptDigest")) + || !DIGEST.matcher(text(receipt.get("trustBindingDigest"))).matches() + || !DIGEST.matcher(text(receipt.get("apiBindingDigest"))).matches() + || !DIGEST.matcher(text(receipt.get("promotionRequestDigest"))).matches() + || !DIGEST.matcher(text(receipt.get("privateReceiptDigest"))).matches() + || !DIGEST.matcher(text(receipt.get("publicReceiptDigest"))).matches() + || !DIGEST.matcher(text(receipt.get("publicDataDigest"))).matches() + || !DIGEST.matcher(text(receipt.get("publicKeyFingerprint"))).matches()) { + throw denied(); + } + requireOriginalCommittedSigner(receipt, verifiedKid); + } + + private void requireOriginalCommittedSigner(Map receipt, String verifiedKid) { + var materializer = + materializerTrust.current().orElseThrow(AccountControlUiCurrentActorVerifier::denied); + var api = jwksApiBinding.current(); + if (!materializer.environmentId().equals(api.environmentId()) + || !materializer.clusterId().equals(api.clusterId()) + || !materializer.namespace().equals(api.namespace()) + || !materializer.expectedClusterIncarnationUid().equals(api.expectedClusterIncarnationUid()) + || !materializer.expectedNamespaceUid().equals(api.expectedNamespaceUid()) + || !text(receipt.get("apiBindingDigest")).equals(api.bindingDigest()) + || !text(receipt.get("apiConfigRevision")).equals(api.configRevision()) + || !text(receipt.get("trustBindingDigest")).equals(materializer.bindingDigest()) + || !text(receipt.get("trustConfigRevision")).equals(materializer.configRevision())) { + throw denied(); + } + Binding binding = + new Binding( + materializer.environmentId(), + materializer.clusterId(), + materializer.namespace(), + CustodyMode.INTERIM_ACCOUNT_ONLY_MOUNTED_FALLBACK); + TrustFence trust = + new TrustFence( + materializer.expectedClusterIncarnationUid(), + materializer.expectedNamespaceUid(), + materializer.bindingDigest(), + materializer.configRevision()); + var original = + signerStates + .readOriginalCommittedSigner( + binding, + trust, + api.bindingDigest(), + api.configRevision(), + uuid(receipt.get("promotionOperationId")), + uuid(receipt.get("generationOperationId"))) + .orElseThrow(AccountControlUiCurrentActorVerifier::denied); + var promotion = original.promotion(); + var generation = original.generationResult(); + if (!"COMMITTED".equals(promotion.status()) + || !promotion.operationId().toString().equals(receipt.get("promotionOperationId")) + || !promotion.requestDigest().equals(receipt.get("promotionRequestDigest")) + || !generation.operationId().toString().equals(receipt.get("generationOperationId")) + || !verifiedKid.equals(generation.targetKid()) + || !generation.targetGeneration().equals(receipt.get("signerGeneration")) + || !"RS256".equals(generation.targetAlgorithm()) + || !generation.publicKeyFingerprint().equals(receipt.get("publicKeyFingerprint")) + || !original.privateReceipt().receiptDigest().equals(receipt.get("privateReceiptDigest")) + || !original + .privateReceipt() + .observedResourceVersion() + .equals(receipt.get("privateResourceVersion")) + || !original.publicReceipt().receiptDigest().equals(receipt.get("publicReceiptDigest")) + || !original + .publicReceipt() + .observedResourceVersion() + .equals(receipt.get("publicResourceVersion")) + || !original.publicReceipt().configMapUid().equals(receipt.get("publicConfigMapUid")) + || !original.publicReceipt().publicDataDigest().equals(receipt.get("publicDataDigest"))) { + throw denied(); + } + } + + private CurrentActor requireCurrentAccountAuthority( + CommittedIssuance issuance, Map claims, UUID tenantId, String tokenHash) { + UUID accountId = issuance.accountId(); + IssuerAccountSourceSnapshot source = + sourceEvidence.readCurrentIssuerAccountSources(ISSUER, accountId); + CompositeSnapshot snapshot = + generations.readCompositeSnapshot(ISSUER, accountId, List.of(tenantId), List.of(tenantId)); + if (source.issuer().generation() != snapshot.issuer().generation() + || source.issuer().sourceVersion() != snapshot.issuer().sourceVersion() + || source.account().generation() != snapshot.account().generation() + || source.account().sourceVersion() != snapshot.account().sourceVersion() + || !source.issuanceFence().equals(snapshot.issuanceFence())) { + throw denied(); + } + var tenantState = only(snapshot.tenants(), "tenant authority"); + var membershipState = only(snapshot.memberships(), "membership authority"); + Event currentTenant = tenantEvents.readCurrentByTenant(tenantId); + if (!tenantId.equals(currentTenant.tenantId()) + || currentTenant.tenantAuthorityGeneration() != tenantState.generation() + || currentTenant.tenantAuthoritySourceVersion() != tenantState.sourceVersion()) { + throw denied(); + } + + PairAuthority pair = + membershipPairs + .readPositive(accountId, tenantId) + .orElseThrow(AccountControlUiCurrentActorVerifier::denied); + AccountTenantMembership membership = + memberships + .findFreshMembership(accountId, tenantId) + .orElseThrow(AccountControlUiCurrentActorVerifier::denied); + if (!pair.membershipExists() + || pair.eventSequence() <= 0L + || pair.lastTransitionInvalidated() + || membership.getId() == null + || membership.getAccount() == null + || membership.getAccount().getId() == null + || !accountId.equals(membership.getAccount().getAccountUuid()) + || !tenantId.equals(membership.getTenantUuid()) + || !"ACTIVE".equals(membership.getLifecycleState()) + || membership.getMembershipVersion() != pair.membershipVersion() + || membership.getMembershipAuthorityGeneration() != pair.membershipAuthorityGeneration() + || pair.membershipAuthorityGeneration() != membershipState.generation()) { + throw denied(); + } + MembershipEvent currentMembershipEvent = + requireCurrentMembershipEvent(accountId, tenantId, pair, membershipState.generation()); + RoleSnapshot roles = + roleSnapshots + .findForCanonicalUpdate( + accountId, + tenantId, + pair.provenance(), + membership.getId(), + membership.getMembershipVersion()) + .orElseThrow(AccountControlUiCurrentActorVerifier::denied); + if (!roles.roles().equals(currentMembershipEvent.roles())) { + throw denied(); + } + requireClaimsCurrent( + claims, accountId, tenantId, source, snapshot, currentTenant, pair, membership, roles); + return new CurrentActor( + accountId, + tenantId, + issuance.operationId(), + tokenHash, + roles.roles(), + snapshot.issuer().generation(), + snapshot.account().generation(), + tenantState.generation(), + membershipState.generation(), + membership.getMembershipVersion(), + snapshot.issuanceFence().value()); + } + + private MembershipEvent requireCurrentMembershipEvent( + UUID accountId, UUID tenantId, PairAuthority pair, long membershipGeneration) { + String streamKey = + MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX + + "membership/" + + accountId + + "/" + + tenantId; + var stored = + outbox + .findEvent(streamKey, pair.eventSequence()) + .orElseThrow(AccountControlUiCurrentActorVerifier::denied); + MembershipEvent event = + MembershipAuthorityEventV1Codec.verify( + new String(stored.payload(), StandardCharsets.UTF_8)); + if (!stored.outboxStreamKey().equals(streamKey) + || !stored.eventId().equals(event.eventId()) + || !stored.eventDigest().equals(event.eventDigest()) + || !Long.toString(stored.outboxSequence()).equals(event.outboxSequence()) + || !pair.eventId().equals(event.eventId()) + || !pair.eventDigest().equals(event.eventDigest()) + || !accountId.toString().equals(event.accountId()) + || !tenantId.toString().equals(event.tenantId()) + || !Long.toString(pair.membershipVersion()) + .equals(event.membershipVersion().get(tenantId.toString())) + || !Long.toString(membershipGeneration).equals(event.membershipAuthorityGeneration()) + || !"ACTIVE".equals(event.membershipLifecycleState()) + || event.callerBoundAuthorityInvalidated() != pair.lastTransitionInvalidated()) { + throw denied(); + } + return event; + } + + private void requireClaimsCurrent( + Map claims, + UUID accountId, + UUID tenantId, + IssuerAccountSourceSnapshot source, + CompositeSnapshot snapshot, + Event tenantEvent, + PairAuthority pair, + AccountTenantMembership membership, + RoleSnapshot roles) { + Map tuple = object(claims.get("authorityTuple")); + Map tenantGenerations = + Map.of(tenantId.toString(), only(snapshot.tenants(), "tenant").generation()); + Map membershipGenerations = + Map.of(tenantId.toString(), pair.membershipAuthorityGeneration()); + Map membershipVersions = Map.of(tenantId.toString(), pair.membershipVersion()); + Map expectedTuple = new LinkedHashMap<>(); + expectedTuple.put("issuerAuthGeneration", snapshot.issuer().generation()); + expectedTuple.put("accountAuthorityGeneration", snapshot.account().generation()); + expectedTuple.put("tenantAuthorityGeneration", tenantGenerations); + expectedTuple.put("membershipAuthorityGeneration", membershipGenerations); + expectedTuple.put("privateRealmGrantVersions", List.of()); + source + .account() + .accountSecurityCutoff() + .ifPresent( + cutoff -> + expectedTuple.put( + "accountSecurityCutoff", + Map.of( + "accountAuthorityGeneration", + Long.parseLong(cutoff.accountAuthorityGeneration()), + "outboxStreamKey", + cutoff.outboxStreamKey(), + "outboxSequence", + Long.parseLong(cutoff.outboxSequence())))); + if (tuple.containsKey("tenantBillingCutoff")) { + expectedTuple.put( + "tenantBillingCutoff", + Map.of( + tenantId.toString(), + Map.of( + "tenantAuthorityGeneration", + tenantEvent.tenantAuthorityGeneration(), + "tenantBillingSequence", + tenantEvent.tenantBillingSequence(), + "outboxStreamKey", + tenantEvent.tenantBillingStreamKey(), + "outboxSequence", + tenantEvent.outboxSequence()))); + } + Map scoped = object(claims.get("scopedRoles")); + if (!numericEquals(tuple.get("issuerAuthGeneration"), snapshot.issuer().generation()) + || !numericEquals(tuple.get("accountAuthorityGeneration"), snapshot.account().generation()) + || !canonicalMapEquals(tuple.get("tenantAuthorityGeneration"), tenantGenerations) + || !canonicalMapEquals(tuple.get("membershipAuthorityGeneration"), membershipGenerations) + || !canonicalMapEquals(tuple, expectedTuple) + || !canonicalMapEquals(claims.get("membershipVersion"), membershipVersions) + || !numericEquals(claims.get("issuanceFence"), snapshot.issuanceFence().value()) + || !canonicalMapEquals(scoped, Map.of(tenantId.toString(), roles.roles())) + || membership.getMembershipVersion() != pair.membershipVersion() + || !accountId.equals(membership.getAccount().getAccountUuid())) { + throw denied(); + } + } + + private static byte[] derivePendingRegistry(byte[] activeBytes) { + Map active = + parseCanonicalObject(activeBytes, AccountControlUiRegistryReader.MAX_RECORD_BYTES); + if (!"active".equals(active.get("state")) + || !Integer.valueOf(2).equals(number(active.get("registryVersion")))) { + throw denied(); + } + Map pending = new LinkedHashMap<>(active); + pending.put("state", "pending"); + pending.put("registryVersion", 1); + return canonicalBytes(pending); + } + + private static Map tokenIdentity(Map claims) { + Map identity = new LinkedHashMap<>(); + identity.put("jti", claims.get("jti")); + identity.put("tokenGeneration", claims.get("tokenGeneration")); + identity.put("iat", claims.get("iat")); + identity.put("nbf", claims.get("nbf")); + identity.put("exp", claims.get("exp")); + return identity; + } + + private static UUID selectedScopedTenant(Map claims, UUID selectedTenant) { + Map roles = object(claims.get("scopedRoles")); + if (!roles.keySet().equals(Set.of(selectedTenant.toString()))) { + throw denied(); + } + return selectedTenant; + } + + private static AccountAuthorityGenerationRepository.ScopeState only( + List states, String label) { + if (states == null || states.size() != 1) { + throw denied(); + } + return states.getFirst(); + } + + private static Map parseCanonicalObject(byte[] bytes, int maximum) { + if (bytes == null || bytes.length == 0 || bytes.length > maximum) { + throw denied(); + } + try { + String json = + StandardCharsets.UTF_8.newDecoder().decode(java.nio.ByteBuffer.wrap(bytes)).toString(); + if (!Arrays.equals(bytes, Rfc8785CanonicalJson.canonicalizeUtf8(json))) { + throw denied(); + } + Map fields = JSON.readValue(bytes, OBJECT); + if (fields == null) { + throw denied(); + } + return Map.copyOf(fields); + } catch (IOException | RuntimeException malformed) { + throw denied(); + } + } + + private static Map object(Object value) { + if (!(value instanceof Map map)) { + throw denied(); + } + Map result = new LinkedHashMap<>(); + map.forEach( + (key, item) -> { + if (!(key instanceof String text)) { + throw denied(); + } + result.put(text, item); + }); + return result; + } + + private static boolean canonicalMapEquals(Object first, Object second) { + return Arrays.equals(canonicalBytes(first), canonicalBytes(second)); + } + + private static byte[] canonicalBytes(Object value) { + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } catch (IOException | RuntimeException failure) { + throw denied(); + } + } + + private static boolean numericEquals(Object actual, long expected) { + return actual instanceof Number number && number.toString().equals(Long.toString(expected)); + } + + private static Number number(Object value) { + return value instanceof Number number ? number : null; + } + + private static long positiveLong(Object value) { + if (!(value instanceof Number number)) { + throw denied(); + } + try { + long parsed = Long.parseLong(number.toString()); + if (parsed <= 0L) { + throw denied(); + } + return parsed; + } catch (NumberFormatException malformed) { + throw denied(); + } + } + + private static boolean atLeastOne(Object value) { + return value instanceof Number number + && number.toString().matches("[1-9][0-9]{0,2}") + && number.longValue() >= 1L; + } + + private static UUID uuid(Object value) { + if (!(value instanceof String text)) { + throw denied(); + } + try { + UUID parsed = UUID.fromString(text); + if (!parsed.toString().equals(text) + || parsed.getMostSignificantBits() == 0L && parsed.getLeastSignificantBits() == 0L) { + throw denied(); + } + return parsed; + } catch (IllegalArgumentException malformed) { + throw denied(); + } + } + + private static String text(Object value) { + return value instanceof String text ? text : ""; + } + + private static String sha256(byte[] bytes) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException unavailable) { + throw denied(); + } + } + + private static byte[] compactBytes(String compactJwt) { + if (compactJwt == null + || compactJwt.isBlank() + || compactJwt.length() > 16384 + || compactJwt.codePoints().anyMatch(codePoint -> codePoint > 0x7f)) { + throw denied(); + } + return compactJwt.getBytes(StandardCharsets.US_ASCII); + } + + private static void requireTenant(UUID tenant) { + if (tenant == null + || tenant.getMostSignificantBits() == 0L && tenant.getLeastSignificantBits() == 0L) { + throw denied(); + } + } + + private static void outsideSql() { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Account JWT and Coordination reads must precede SQL ownership"); + } + } + + private static IllegalStateException denied() { + return new IllegalStateException("Current Account control-ui actor evidence unavailable"); + } + + /** + * Identity and current source tuple only. It is not a route authorization or a reference grant. + */ + public record CurrentActor( + UUID accountId, + UUID tenantId, + UUID issuanceOperationId, + String tokenHash, + List currentTenantRoles, + long issuerGeneration, + long accountGeneration, + long tenantGeneration, + long membershipGeneration, + long membershipVersion, + long issuanceFence) { + public CurrentActor { + Objects.requireNonNull(accountId); + Objects.requireNonNull(tenantId); + Objects.requireNonNull(issuanceOperationId); + if (tokenHash == null || !DIGEST.matcher(tokenHash).matches()) { + throw new IllegalArgumentException("Control-ui actor token identity is invalid"); + } + currentTenantRoles = List.copyOf(currentTenantRoles); + if (issuerGeneration <= 0L + || accountGeneration <= 0L + || tenantGeneration <= 0L + || membershipGeneration <= 0L + || membershipVersion <= 0L + || issuanceFence <= 0L) { + throw new IllegalArgumentException("Control-ui current authority values must be positive"); + } + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiRegistryReader.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiRegistryReader.java new file mode 100644 index 0000000000..8246f90998 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiRegistryReader.java @@ -0,0 +1,212 @@ +package net.firedevops.firemud.accountservice.service.session; + +import io.lettuce.core.api.sync.RedisCommands; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.core.type.TypeReference; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.json.JsonMapper; + +/** + * Read-only Account Coordination view of one committed control-ui token record. + * + *

This class is deliberately not a Spring bean and contains no Redis mutation path. A caller + * must supply Account's protected pinned connection provider; each read proves the live ACL user + * and exact physical cleanup deadline on that same non-reconnecting connection. Registry presence + * is only one input to Account's committed issuance/current-authority verification. + */ +public final class AccountControlUiRegistryReader { + public static final String TOKEN_KEY_PREFIX = "session:auth:token:"; + public static final String REQUIRED_ACL_IDENTITY = "account_coord_app"; + public static final int MAX_RECORD_BYTES = 32 * 1024; + + private static final Pattern TOKEN_HASH = Pattern.compile("[0-9a-f]{64}"); + private static final Pattern DIGEST = Pattern.compile("[0-9a-f]{64}"); + private static final Pattern KID = Pattern.compile("[A-Za-z0-9_-]{1,64}"); + private static final Pattern DECIMAL = Pattern.compile("[1-9][0-9]{0,18}"); + private static final Set FIELDS = + Set.of( + "schemaVersion", + "registryVersion", + "tokenHash", + "kid", + "signerGeneration", + "issuer", + "profile", + "type", + "audience", + "accountId", + "jti", + "iat", + "nbf", + "exp", + "tokenGeneration", + "authorityTuple", + "membershipVersion", + "issuanceFence", + "operationId", + "requestId", + "requestDigest", + "state", + "authoritySourceVersions", + "authEvidenceBundle", + "originalSignerReceiptDigest"); + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + private static final TypeReference> OBJECT = new TypeReference<>() {}; + + private final AccountCoordinationPinnedConnectionProvider connections; + + public AccountControlUiRegistryReader(AccountCoordinationPinnedConnectionProvider connections) { + this.connections = + Objects.requireNonNull(connections, "private Account Coordination is required"); + } + + /** Reads and validates one active registry value without holding an Account SQL transaction. */ + public byte[] readActive(String tokenHash) { + outsideSql(); + if (tokenHash == null || !TOKEN_HASH.matcher(tokenHash).matches()) { + throw denied(); + } + try (var connection = connections.openPinnedConnection()) { + if (connection == null + || !connection.isOpen() + || connection.getOptions() == null + || connection.getOptions().isAutoReconnect()) { + throw denied(); + } + RedisCommands commands = connection.sync(); + if (!REQUIRED_ACL_IDENTITY.equals(commands.aclWhoami())) { + throw denied(); + } + byte[] key = (TOKEN_KEY_PREFIX + tokenHash).getBytes(StandardCharsets.US_ASCII); + byte[] exact = commands.get(key); + Map record = parseActiveRecord(exact, tokenHash); + long expiresAtMillis = checkedExpiryMillis(record.get("exp")); + Long physicalExpiry = commands.pexpiretime(key); + if (physicalExpiry == null || physicalExpiry.longValue() != expiresAtMillis) { + throw denied(); + } + return exact.clone(); + } catch (RuntimeException unavailable) { + throw denied(); + } + } + + static Map parseActiveRecord(byte[] exact, String tokenHash) { + if (exact == null || exact.length == 0 || exact.length > MAX_RECORD_BYTES) { + throw denied(); + } + try { + String json = + StandardCharsets.UTF_8.newDecoder().decode(java.nio.ByteBuffer.wrap(exact)).toString(); + if (!Arrays.equals(exact, Rfc8785CanonicalJson.canonicalizeUtf8(json))) { + throw denied(); + } + Map fields = JSON.readValue(exact, OBJECT); + if (fields == null + || !fields.keySet().equals(FIELDS) + || !Integer.valueOf(1).equals(number(fields.get("schemaVersion"))) + || !Integer.valueOf(2).equals(number(fields.get("registryVersion"))) + || !tokenHash.equals(text(fields.get("tokenHash"))) + || !"firemud-account-service".equals(text(fields.get("issuer"))) + || !"control-ui".equals(text(fields.get("profile"))) + || !"control-ui".equals(text(fields.get("type"))) + || !"control-ui".equals(text(fields.get("audience"))) + || !"active".equals(text(fields.get("state"))) + || !KID.matcher(text(fields.get("kid"))).matches() + || !DECIMAL.matcher(text(fields.get("signerGeneration"))).matches() + || !DIGEST.matcher(text(fields.get("requestDigest"))).matches() + || !DIGEST.matcher(text(fields.get("originalSignerReceiptDigest"))).matches() + || !(fields.get("authorityTuple") instanceof Map) + || !(fields.get("membershipVersion") instanceof Map) + || !(fields.get("authoritySourceVersions") instanceof Map) + || !(fields.get("authEvidenceBundle") instanceof Map)) { + throw denied(); + } + requireUuid(fields.get("accountId")); + requireUuid(fields.get("jti")); + requireUuid(fields.get("operationId")); + requireUuid(fields.get("requestId")); + requirePositiveNumber(fields.get("iat")); + requirePositiveNumber(fields.get("nbf")); + requirePositiveNumber(fields.get("exp")); + requirePositiveNumber(fields.get("tokenGeneration")); + requirePositiveNumber(fields.get("issuanceFence")); + return Map.copyOf(fields); + } catch (IOException | RuntimeException malformed) { + throw denied(); + } + } + + static long checkedExpiryMillis(Object encodedExpiry) { + try { + long exp = requirePositiveNumber(encodedExpiry); + // The committed control-ui profile uses the exact token expiry and zero cleanup margin. + return Math.multiplyExact(exp, 1000L); + } catch (ArithmeticException | IllegalArgumentException malformed) { + throw denied(); + } + } + + private static Number number(Object value) { + return value instanceof Number number ? number : null; + } + + private static String text(Object value) { + return value instanceof String text ? text : ""; + } + + private static long requirePositiveNumber(Object value) { + if (!(value instanceof Number number)) { + throw denied(); + } + String encoded = number.toString(); + if (!DECIMAL.matcher(encoded).matches()) { + throw denied(); + } + try { + return Long.parseLong(encoded); + } catch (NumberFormatException malformed) { + throw denied(); + } + } + + private static void requireUuid(Object value) { + if (!(value instanceof String text)) { + throw denied(); + } + try { + UUID parsed = UUID.fromString(text); + if (!parsed.toString().equals(text) + || parsed.getMostSignificantBits() == 0L && parsed.getLeastSignificantBits() == 0L) { + throw denied(); + } + } catch (IllegalArgumentException malformed) { + throw denied(); + } + } + + private static void outsideSql() { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException("Account Coordination reads cannot retain Account SQL locks"); + } + } + + private static IllegalStateException denied() { + return new IllegalStateException( + "Exact Account active control-ui registry evidence unavailable"); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountCoordinationPinnedConnectionProvider.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountCoordinationPinnedConnectionProvider.java new file mode 100644 index 0000000000..5b8a506b74 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountCoordinationPinnedConnectionProvider.java @@ -0,0 +1,14 @@ +package net.firedevops.firemud.accountservice.service.session; + +import io.lettuce.core.api.StatefulRedisConnection; + +/** Opens one private, dedicated, non-clustered Coordination connection for one Account read. */ +@FunctionalInterface +public interface AccountCoordinationPinnedConnectionProvider { + /** + * The provider must not return an ambient Spring connection, must disable automatic reconnect, + * and must retain one pinned physical Redis connection for the invocation. The caller checks the + * open/no-auto-reconnect contract and authenticates its ACL identity before reading data. + */ + StatefulRedisConnection openPinnedConnection(); +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksConfigMapClient.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksConfigMapClient.java new file mode 100644 index 0000000000..3f2077f190 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksConfigMapClient.java @@ -0,0 +1,704 @@ +package net.firedevops.firemud.accountservice.service.session; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.nio.ByteBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.function.Supplier; +import java.util.regex.Pattern; +import net.firedevops.firemud.accountservice.config.AccountJwtJwksApiBinding; +import net.firedevops.firemud.accountservice.config.AccountJwtJwksApiBinding.ApiCall; +import net.firedevops.firemud.accountservice.config.AccountJwtJwksApiBinding.ApiResponse; +import net.firedevops.firemud.accountservice.config.AccountJwtJwksApiBinding.ParsedBinding; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; + +/** + * The Account-only Kubernetes adapter for the pre-created public {@code jwt-jwks} ConfigMap. Every + * write is a fixed-name, resourceVersion-guarded merge patch followed by exact readback. This class + * is intentionally not a lifecycle, readiness, or signer-promotion authority. + */ +public final class AccountJwtJwksConfigMapClient { + public static final String CONFIG_MAP_NAME = "jwt-jwks"; + public static final String JWKS_DATA_KEY = "jwks.json"; + public static final String GENERATION_DATA_KEY = "jwt-generation.json"; + public static final int MAX_DESIRED_VALUE_BYTES = 768 * 1024; + private static final int MAX_CONFIG_MAP_DATA_KEYS = 128; + private static final int MAX_CONFIG_MAP_DATA_BYTES = 1024 * 1024; + private static final Pattern RESOURCE_VERSION = Pattern.compile("[!-~]{1,256}"); + private static final Pattern UID = + Pattern.compile("[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}"); + private static final Set ACCOUNT_DATA_KEYS = Set.of(JWKS_DATA_KEY, GENERATION_DATA_KEY); + private static final Set PRIVATE_JWK_FIELDS = + Set.of("d", "p", "q", "dp", "dq", "qi", "oth", "k"); + private static final byte[] SELF_SUBJECT_REVIEW_REQUEST = + "{\"apiVersion\":\"authentication.k8s.io/v1\",\"kind\":\"SelfSubjectReview\",\"spec\":{}}" + .getBytes(StandardCharsets.UTF_8); + private static final JsonMapper STRICT_JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + private final Supplier operationSupplier; + + /** Production constructor; API TLS and bearer handling remain inside the protected binding. */ + public AccountJwtJwksConfigMapClient(AccountJwtJwksApiBinding binding) { + AccountJwtJwksApiBinding requiredBinding = + Objects.requireNonNull(binding, "Account JWT JWKS API binding is required"); + this.operationSupplier = + () -> { + AccountJwtJwksApiBinding.ApiOperation operation = requiredBinding.beginOperation(); + return new ApiSession() { + @Override + public ParsedBinding binding() { + return operation.binding(); + } + + @Override + public ApiResponse send(ApiCall call, byte[] body) { + return operation.send(call, body); + } + + @Override + public void close() { + operation.close(); + } + }; + }; + } + + /** Deterministic bounded transport seam for focused tests. */ + AccountJwtJwksConfigMapClient(Supplier operationSupplier) { + this.operationSupplier = + Objects.requireNonNull(operationSupplier, "API operation supplier is required"); + } + + /** + * Returns only the independently protected non-secret API/destination pins. Callers can compare + * these with Account's materializer binding before creating durable publication intent. + */ + public BindingIdentity identity() { + try (ApiSession operation = beginOperation()) { + return toIdentity(operation.binding()); + } + } + + /** + * Reads only the fixed pre-created public ConfigMap after checking Account API identity and both + * namespace incarnation pins. No list, create, delete, or Secret endpoint is available. + */ + public ConfigMapSnapshot observe() { + try (ApiSession operation = beginOperation()) { + verifyEnvironment(operation); + return readConfigMap(operation); + } + } + + /** + * Applies an exact owner-authored public data map using Kubernetes resourceVersion CAS. Only + * {@code jwks.json} and {@code jwt-generation.json} are accepted; unrelated data is preserved. An + * ambiguous write is successful only after a fresh exact-content readback on the same UID. + */ + public CasObservation publish(ConfigMapSnapshot expected, Map desiredPublicData) { + Objects.requireNonNull(expected, "expected ConfigMap snapshot is required"); + Map desired = validateDesiredPublicData(desiredPublicData); + requireSnapshotIdentity(expected); + + try (ApiSession operation = beginOperation()) { + return publish(operation, expected, desired); + } + } + + /** + * Reconciles Account's exact active-marker transition from its durable prepublication RV. The + * freshly observed full snapshot preserves unrelated entries on a first write; an exact replay is + * accepted only when the live Account-owned data already matches and its RV advanced beyond the + * original prepublication fence. + */ + public CasObservation publishActiveProjection( + ConfigMapSnapshot observed, + String expectedPriorResourceVersion, + Map desiredPublicData) { + Objects.requireNonNull(observed, "fresh ConfigMap observation is required"); + Map desired = validateDesiredPublicData(desiredPublicData); + requireSnapshotIdentity(observed); + if (expectedPriorResourceVersion == null + || !RESOURCE_VERSION.matcher(expectedPriorResourceVersion).matches()) { + throw new IllegalArgumentException("Active ConfigMap prior resourceVersion is malformed"); + } + + try (ApiSession operation = beginOperation()) { + verifyEnvironment(operation); + ConfigMapSnapshot before = readConfigMap(operation); + if (!before.uid().equals(observed.uid()) + || !before.resourceVersion().equals(observed.resourceVersion()) + || !before.data().equals(observed.data())) { + throw conflict(before); + } + if (sameAccountData(before.data(), desired)) { + if (before.resourceVersion().equals(expectedPriorResourceVersion)) { + throw conflict(before); + } + return observationWithPrior( + expectedPriorResourceVersion, before, desired, Outcome.EXACT_REPLAY); + } + if (!before.resourceVersion().equals(expectedPriorResourceVersion)) { + throw conflict(before); + } + + byte[] patch = createMergePatch(before, desired); + verifyEnvironment(operation); + ApiResponse response; + try { + response = operation.send(ApiCall.PATCH_JWKS_CONFIG_MAP, patch); + } catch (AccountJwtJwksApiBinding.BindingRejectedException ex) { + throw new BindingRejectedException(); + } catch (AccountJwtJwksApiBinding.ApiTransportException ex) { + return reconcileUnknownWrite(operation, before, before, desired); + } + if (response.statusCode() == 409) { + verifyEnvironment(operation); + throw conflict(readConfigMap(operation)); + } + if (response.statusCode() == 404) { + throw new ResourceMissingException(); + } + if (response.statusCode() >= 500 || response.statusCode() == 408) { + return reconcileUnknownWrite(operation, before, before, desired); + } + if (!isSuccess(response.statusCode())) { + throw new ApiFailureException(response.statusCode()); + } + ConfigMapSnapshot readback; + try { + verifyEnvironment(operation); + readback = readConfigMap(operation); + } catch (RuntimeException ex) { + throw new UncertainOutcomeException(); + } + requireExactPostcondition(before, before, readback, desired); + return observationWithPrior(expectedPriorResourceVersion, readback, desired, Outcome.APPLIED); + } + } + + private CasObservation publish( + ApiSession operation, ConfigMapSnapshot expected, Map desired) { + verifyEnvironment(operation); + ConfigMapSnapshot before = readConfigMap(operation); + if (!before.uid().equals(expected.uid())) { + throw conflict(before); + } + if (sameAccountData(before.data(), desired)) { + if (before.resourceVersion().equals(expected.resourceVersion())) { + throw conflict(before); + } + return observation(expected, before, desired, Outcome.EXACT_REPLAY); + } + if (!before.resourceVersion().equals(expected.resourceVersion())) { + throw conflict(before); + } + + byte[] patch = createMergePatch(expected, desired); + // Identity checks are repeated immediately before the only write call. + verifyEnvironment(operation); + ApiResponse response; + try { + response = operation.send(ApiCall.PATCH_JWKS_CONFIG_MAP, patch); + } catch (AccountJwtJwksApiBinding.BindingRejectedException ex) { + throw new BindingRejectedException(); + } catch (AccountJwtJwksApiBinding.ApiTransportException ex) { + return reconcileUnknownWrite(operation, expected, before, desired); + } + if (response.statusCode() == 409) { + verifyEnvironment(operation); + throw conflict(readConfigMap(operation)); + } + if (response.statusCode() == 404) { + throw new ResourceMissingException(); + } + if (response.statusCode() >= 500 || response.statusCode() == 408) { + return reconcileUnknownWrite(operation, expected, before, desired); + } + if (!isSuccess(response.statusCode())) { + throw new ApiFailureException(response.statusCode()); + } + + ConfigMapSnapshot readback; + try { + verifyEnvironment(operation); + readback = readConfigMap(operation); + } catch (RuntimeException ex) { + throw new UncertainOutcomeException(); + } + requireExactPostcondition(expected, before, readback, desired); + return observation(expected, readback, desired, Outcome.APPLIED); + } + + private CasObservation reconcileUnknownWrite( + ApiSession operation, + ConfigMapSnapshot expected, + ConfigMapSnapshot before, + Map desired) { + try { + verifyEnvironment(operation); + ConfigMapSnapshot observed = readConfigMap(operation); + if (observed.uid().equals(expected.uid()) && sameAccountData(observed.data(), desired)) { + requirePreservedUnrelatedData(before, observed); + if (observed.resourceVersion().equals(expected.resourceVersion())) { + throw new UncertainOutcomeException(); + } + return observation(expected, observed, desired, Outcome.EXACT_REPLAY); + } + } catch (UncertainOutcomeException ex) { + throw ex; + } catch (RuntimeException ex) { + // The write outcome remains unknown when reconciliation itself is unavailable. + } + throw new UncertainOutcomeException(); + } + + private void requireExactPostcondition( + ConfigMapSnapshot expected, + ConfigMapSnapshot before, + ConfigMapSnapshot readback, + Map desired) { + if (!readback.uid().equals(expected.uid()) + || readback.resourceVersion().equals(expected.resourceVersion()) + || !sameAccountData(readback.data(), desired)) { + throw new UncertainOutcomeException(); + } + requirePreservedUnrelatedData(before, readback); + } + + private static void requirePreservedUnrelatedData( + ConfigMapSnapshot before, ConfigMapSnapshot after) { + Map previous = unrelatedData(before.data()); + Map current = unrelatedData(after.data()); + if (!previous.equals(current)) { + throw new UncertainOutcomeException(); + } + } + + private static Map unrelatedData(Map data) { + Map unrelated = new LinkedHashMap<>(); + data.forEach( + (key, value) -> { + if (!ACCOUNT_DATA_KEYS.contains(key)) { + unrelated.put(key, value); + } + }); + return Map.copyOf(unrelated); + } + + private ConfigMapSnapshot readConfigMap(ApiSession operation) { + ApiResponse response = send(operation, ApiCall.READ_JWKS_CONFIG_MAP, null); + if (response.statusCode() == 404) { + throw new ResourceMissingException(); + } + if (!isSuccess(response.statusCode())) { + throw new ApiFailureException(response.statusCode()); + } + return parseConfigMap(response.body(), operation.binding()); + } + + private void verifyEnvironment(ApiSession operation) { + ParsedBinding binding = operation.binding(); + ApiResponse selfReview = + send(operation, ApiCall.REVIEW_AUTHENTICATED_PRINCIPAL, SELF_SUBJECT_REVIEW_REQUEST); + if ((selfReview.statusCode() != 200 && selfReview.statusCode() != 201) + || !binding.expectedApiUsername().equals(parseAuthenticatedUsername(selfReview.body()))) { + throw new BindingRejectedException(); + } + verifyNamespace( + send(operation, ApiCall.READ_KUBE_SYSTEM_NAMESPACE, null), + "kube-system", + binding.expectedClusterIncarnationUid()); + verifyNamespace( + send(operation, ApiCall.READ_TARGET_NAMESPACE, null), + binding.namespace(), + binding.expectedNamespaceUid()); + } + + private void verifyNamespace(ApiResponse response, String name, String expectedUid) { + if (!isSuccess(response.statusCode())) { + if (response.statusCode() == 404) { + throw new BindingRejectedException(); + } + throw new ApiFailureException(response.statusCode()); + } + JsonNode root = parseJson(response.body()); + JsonNode metadata = root.get("metadata"); + JsonNode status = root.get("status"); + if (!"v1".equals(text(root.get("apiVersion"))) + || !"Namespace".equals(text(root.get("kind"))) + || metadata == null + || !name.equals(text(metadata.get("name"))) + || !expectedUid.equals(canonicalUid(text(metadata.get("uid")))) + || metadata.hasNonNull("deletionTimestamp") + || status == null + || !"Active".equals(text(status.get("phase")))) { + throw new BindingRejectedException(); + } + } + + private static String parseAuthenticatedUsername(byte[] bytes) { + JsonNode root = parseJson(bytes); + JsonNode status = root.get("status"); + JsonNode userInfo = status == null ? null : status.get("userInfo"); + String username = userInfo == null ? null : text(userInfo.get("username")); + JsonNode evaluationError = status == null ? null : status.get("evaluationError"); + if (!"authentication.k8s.io/v1".equals(text(root.get("apiVersion"))) + || !"SelfSubjectReview".equals(text(root.get("kind"))) + || username == null + || (evaluationError != null + && !evaluationError.isNull() + && (!evaluationError.isTextual() || !evaluationError.asText().isEmpty()))) { + throw new BindingRejectedException(); + } + return username; + } + + private static ConfigMapSnapshot parseConfigMap(byte[] bytes, ParsedBinding binding) { + JsonNode root = parseJson(bytes); + JsonNode metadata = root.get("metadata"); + if (!"v1".equals(text(root.get("apiVersion"))) + || !"ConfigMap".equals(text(root.get("kind"))) + || metadata == null + || !CONFIG_MAP_NAME.equals(text(metadata.get("name"))) + || !binding.namespace().equals(text(metadata.get("namespace"))) + || metadata.hasNonNull("deletionTimestamp") + || Boolean.TRUE.equals(booleanValue(root.get("immutable"))) + || (root.has("binaryData") && !root.get("binaryData").isNull())) { + throw new ApiFailureException(0); + } + String uid = canonicalUid(text(metadata.get("uid"))); + String resourceVersion = text(metadata.get("resourceVersion")); + if (resourceVersion == null || !RESOURCE_VERSION.matcher(resourceVersion).matches()) { + throw new ApiFailureException(0); + } + Map data = parseData(root.get("data")); + return new ConfigMapSnapshot(uid, resourceVersion, data); + } + + private static Map parseData(JsonNode dataNode) { + if (dataNode == null || dataNode.isNull()) { + return Map.of(); + } + if (!dataNode.isObject() || dataNode.size() > MAX_CONFIG_MAP_DATA_KEYS) { + throw new ApiFailureException(0); + } + Map data = new LinkedHashMap<>(); + int totalBytes = 0; + for (Map.Entry entry : dataNode.properties()) { + JsonNode value = entry.getValue(); + if (!value.isTextual()) { + throw new ApiFailureException(0); + } + String text = value.asText(); + totalBytes += text.getBytes(StandardCharsets.UTF_8).length; + if (totalBytes > MAX_CONFIG_MAP_DATA_BYTES) { + throw new ApiFailureException(0); + } + data.put(entry.getKey(), text); + } + return Map.copyOf(data); + } + + private ApiSession beginOperation() { + try { + return Objects.requireNonNull(operationSupplier.get(), "API operation is unavailable"); + } catch (AccountJwtJwksApiBinding.BindingRejectedException ex) { + throw new BindingRejectedException(); + } catch (RuntimeException ex) { + throw new BindingRejectedException(); + } + } + + private ApiResponse send(ApiSession operation, ApiCall call, byte[] body) { + try { + return operation.send(call, body); + } catch (AccountJwtJwksApiBinding.BindingRejectedException ex) { + throw new BindingRejectedException(); + } catch (AccountJwtJwksApiBinding.ApiTransportException ex) { + throw new ApiFailureException(0); + } + } + + private static BindingIdentity toIdentity(ParsedBinding binding) { + return new BindingIdentity( + binding.bindingDigest(), + binding.configRevision(), + binding.environmentId(), + binding.clusterId(), + binding.namespace(), + binding.expectedClusterIncarnationUid(), + binding.expectedNamespaceUid(), + binding.apiServer().toString(), + binding.tlsServerName(), + binding.servingCaSha256(), + binding.expectedApiUsername()); + } + + private static Map validateDesiredPublicData(Map desired) { + if (desired == null || !desired.keySet().equals(ACCOUNT_DATA_KEYS)) { + throw new IllegalArgumentException("Account public JWKS data keys are invalid"); + } + Map copy = new LinkedHashMap<>(); + int total = 0; + for (String key : ACCOUNT_DATA_KEYS) { + String value = desired.get(key); + if (value == null || value.isBlank()) { + throw new IllegalArgumentException("Account public JWKS data is incomplete"); + } + int length = value.getBytes(StandardCharsets.UTF_8).length; + if (length > MAX_DESIRED_VALUE_BYTES) { + throw new IllegalArgumentException("Account public JWKS data exceeds its bound"); + } + total += length; + copy.put(key, value); + } + if (total > MAX_CONFIG_MAP_DATA_BYTES) { + throw new IllegalArgumentException("Account public JWKS data exceeds its bound"); + } + validatePublicJwks(copy.get(JWKS_DATA_KEY)); + return Map.copyOf(copy); + } + + private static void validatePublicJwks(String jwks) { + JsonNode root = parseJson(jwks.getBytes(StandardCharsets.UTF_8)); + JsonNode keys = root.get("keys"); + if (!root.isObject() || root.size() != 1 || keys == null || !keys.isArray() || keys.isEmpty()) { + throw new IllegalArgumentException("Account public JWKS is malformed"); + } + for (JsonNode key : keys) { + if (!key.isObject()) { + throw new IllegalArgumentException("Account public JWKS is malformed"); + } + for (String privateField : PRIVATE_JWK_FIELDS) { + if (key.has(privateField)) { + throw new IllegalArgumentException("Account public JWKS contains private material"); + } + } + } + } + + private static byte[] createMergePatch(ConfigMapSnapshot expected, Map desired) { + Map metadata = new LinkedHashMap<>(); + metadata.put("uid", expected.uid()); + metadata.put("resourceVersion", expected.resourceVersion()); + Map patch = new LinkedHashMap<>(); + patch.put("metadata", metadata); + patch.put("data", desired); + try { + return STRICT_JSON.writeValueAsBytes(patch); + } catch (Exception ex) { + throw new IllegalStateException("Account public JWKS patch could not be encoded"); + } + } + + private static boolean sameAccountData(Map current, Map desired) { + return desired.get(JWKS_DATA_KEY).equals(current.get(JWKS_DATA_KEY)) + && desired.get(GENERATION_DATA_KEY).equals(current.get(GENERATION_DATA_KEY)); + } + + private static CasObservation observation( + ConfigMapSnapshot expected, + ConfigMapSnapshot observed, + Map desired, + Outcome outcome) { + Map exactOutput = new LinkedHashMap<>(); + exactOutput.put(JWKS_DATA_KEY, desired.get(JWKS_DATA_KEY)); + exactOutput.put(GENERATION_DATA_KEY, desired.get(GENERATION_DATA_KEY)); + return new CasObservation( + observed.uid(), + expected.resourceVersion(), + observed.resourceVersion(), + exactOutput, + observed.data(), + outcome); + } + + private static CasObservation observationWithPrior( + String priorResourceVersion, + ConfigMapSnapshot observed, + Map desired, + Outcome outcome) { + Map exactOutput = new LinkedHashMap<>(); + exactOutput.put(JWKS_DATA_KEY, desired.get(JWKS_DATA_KEY)); + exactOutput.put(GENERATION_DATA_KEY, desired.get(GENERATION_DATA_KEY)); + return new CasObservation( + observed.uid(), + priorResourceVersion, + observed.resourceVersion(), + exactOutput, + observed.data(), + outcome); + } + + private static CasConflictException conflict(ConfigMapSnapshot observed) { + return new CasConflictException(observed.uid(), observed.resourceVersion()); + } + + private static void requireSnapshotIdentity(ConfigMapSnapshot snapshot) { + if (!validUid(snapshot.uid()) + || snapshot.resourceVersion() == null + || !RESOURCE_VERSION.matcher(snapshot.resourceVersion()).matches()) { + throw new IllegalArgumentException("Expected ConfigMap snapshot identity is malformed"); + } + } + + private static boolean isSuccess(int statusCode) { + return statusCode >= 200 && statusCode < 300; + } + + private static JsonNode parseJson(byte[] bytes) { + if (bytes == null || bytes.length == 0 || bytes.length > MAX_CONFIG_MAP_DATA_BYTES) { + throw new ApiFailureException(0); + } + try { + String text = + StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(bytes)) + .toString(); + JsonNode root = STRICT_JSON.readTree(text); + if (root == null || !root.isObject()) { + throw new ApiFailureException(0); + } + return root; + } catch (CharacterCodingException | RuntimeException ex) { + throw new ApiFailureException(0); + } + } + + private static String text(JsonNode node) { + return node != null && node.isTextual() && !node.asText().isEmpty() ? node.asText() : null; + } + + @SuppressFBWarnings( + value = "NP_BOOLEAN_RETURN_NULL", + justification = + "The parser intentionally preserves absent or malformed booleans as unknown; callers require explicit true.") + private static Boolean booleanValue(JsonNode node) { + return node != null && node.isBoolean() ? node.booleanValue() : null; + } + + private static String canonicalUid(String value) { + if (!validUid(value)) { + throw new ApiFailureException(0); + } + return value; + } + + private static boolean validUid(String value) { + return value != null + && UID.matcher(value).matches() + && !"00000000-0000-0000-0000-000000000000".equals(value); + } + + interface ApiSession extends AutoCloseable { + ParsedBinding binding(); + + ApiResponse send(ApiCall call, byte[] body); + + @Override + void close(); + } + + public record BindingIdentity( + String bindingDigest, + String configRevision, + String environmentId, + String clusterId, + String namespace, + String expectedClusterIncarnationUid, + String expectedNamespaceUid, + String apiServerUrl, + String tlsServerName, + String servingCaSha256, + String expectedApiUsername) {} + + public record ConfigMapSnapshot(String uid, String resourceVersion, Map data) { + public ConfigMapSnapshot { + data = data == null ? Map.of() : Map.copyOf(data); + } + } + + public record CasObservation( + String uid, + String priorResourceVersion, + String resourceVersion, + Map publishedData, + Map readbackData, + Outcome outcome) { + public CasObservation { + publishedData = Map.copyOf(publishedData); + readbackData = Map.copyOf(readbackData); + } + } + + public enum Outcome { + APPLIED, + EXACT_REPLAY + } + + public static class ResourceMissingException extends RuntimeException { + public ResourceMissingException() { + super("Pre-created Account public JWKS ConfigMap is unavailable"); + } + } + + public static class CasConflictException extends RuntimeException { + private final String observedUid; + private final String observedResourceVersion; + + public CasConflictException(String observedUid, String observedResourceVersion) { + super("Account public JWKS ConfigMap compare-and-set conflict"); + this.observedUid = observedUid; + this.observedResourceVersion = observedResourceVersion; + } + + public String observedUid() { + return observedUid; + } + + public String observedResourceVersion() { + return observedResourceVersion; + } + } + + public static class UncertainOutcomeException extends RuntimeException { + public UncertainOutcomeException() { + super("Account public JWKS ConfigMap write outcome is uncertain"); + } + } + + public static class ApiFailureException extends RuntimeException { + private final int statusCode; + + public ApiFailureException(int statusCode) { + super("Account public JWKS Kubernetes API request failed"); + this.statusCode = statusCode; + } + + public int statusCode() { + return statusCode; + } + } + + public static class BindingRejectedException extends RuntimeException { + public BindingRejectedException() { + super("Account public JWKS API binding or identity was rejected"); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksTrustedSource.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksTrustedSource.java new file mode 100644 index 0000000000..4742f95fed --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksTrustedSource.java @@ -0,0 +1,761 @@ +package net.firedevops.firemud.accountservice.service.session; + +import java.io.IOException; +import java.math.BigInteger; +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import net.firedevops.firemud.accountservice.config.AccountJwtSignerMaterializerTrustBinding; +import net.firedevops.firemud.accountservice.config.AccountJwtSignerMaterializerTrustBinding.Binding; +import net.firedevops.firemud.accountservice.repository.AccountJwtJwksPublicationRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtJwksPublicationRepository.PrepublicationIntent; +import net.firedevops.firemud.accountservice.repository.AccountJwtJwksPublicationRepository.PublicationEvidence; +import net.firedevops.firemud.accountservice.repository.AccountJwtJwksPublicationRepository.PublicationReceipt; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.ActiveSigner; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.CommittedSignerEvidence; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.DesiredState; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.EnrollmentIdentity; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.GenerationRequest; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.GenerationResult; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.PromotionOperationEvidence; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.TrustFence; +import net.firedevops.firemud.accountservice.service.session.AccountJwtJwksConfigMapClient.BindingIdentity; +import net.firedevops.firemud.accountservice.service.session.AccountJwtJwksConfigMapClient.ConfigMapSnapshot; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.security.AccountPublicJwksCache; +import net.firedevops.firemud.common.security.AccountPublicJwksCache.PublicJwksSnapshot; +import net.firedevops.firemud.common.security.AccountPublicJwksCache.SourceIdentity; +import net.firedevops.firemud.common.security.AccountPublicJwksCache.SourceUnavailableException; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; + +/** + * Account-owned authenticated read adapter for the current public JWKS publication. + * + *

The cache pin is derived from Account's root-protected Kubernetes API binding and exact + * Account-owned publication evidence. The first receipt-backed PREPUBLISHED key can be served to + * readiness probes before a signer is committed, but is never represented as active authority. + * During ordinary prepublication of a next key, the prior committed key remains the only active + * signer while the exact new public set may be served for validation overlap. PREPARED and + * unexplained resource changes deny. This adapter exposes only public JWKS bytes and grants no + * signing, registry, readiness, or admission authority. + */ +public final class AccountJwtJwksTrustedSource + implements AccountPublicJwksCache.TrustedPublicJwksSource { + private static final int MAX_JWKS_BYTES = 256 * 1024; + private static final int MAX_MARKER_BYTES = 16 * 1024; + private static final String ACCOUNT_SERVICE_USERNAME_PREFIX = "system:serviceaccount:"; + private static final String ACCOUNT_SERVICE_NAME = "account-service"; + private static final int MAX_KEYS = 64; + private static final java.util.Set JWKS_FIELDS = java.util.Set.of("keys"); + private static final java.util.Set JWK_FIELDS = + java.util.Set.of("kty", "use", "alg", "kid", "key_ops", "n", "e"); + private static final JsonMapper STRICT_JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + private final AccountJwtJwksConfigMapClient configMapClient; + private final AccountJwtSignerMaterializerTrustBinding materializerTrustBinding; + private final AccountJwtSignerDesiredStateRepository desiredStateRepository; + private final AccountJwtJwksPublicationRepository publicationRepository; + private final TransactionTemplate accountTransaction; + private final Object pinMonitor = new Object(); + + private volatile TrustedPin trustedPin; + + /** Constructs an inactive adapter over Account's real protected API and owner-recorded state. */ + public AccountJwtJwksTrustedSource( + AccountJwtJwksConfigMapClient configMapClient, + AccountJwtSignerMaterializerTrustBinding materializerTrustBinding, + AccountJwtSignerDesiredStateRepository desiredStateRepository, + AccountJwtJwksPublicationRepository publicationRepository, + PlatformTransactionManager transactionManager) { + this.configMapClient = + Objects.requireNonNull(configMapClient, "Account ConfigMap client is required"); + this.materializerTrustBinding = + Objects.requireNonNull(materializerTrustBinding, "Protected Account trust is required"); + this.desiredStateRepository = + Objects.requireNonNull(desiredStateRepository, "Account signer repository is required"); + this.publicationRepository = + Objects.requireNonNull(publicationRepository, "Account publication repository is required"); + this.accountTransaction = + new TransactionTemplate( + Objects.requireNonNull(transactionManager, "Account transaction manager is required")); + this.accountTransaction.setReadOnly(false); + } + + /** + * Establishes the immutable cache pin from a coherent, protected Account read. A cache owner + * obtains its expected source identity here; it is not accepted as caller-supplied evidence. + */ + public SourceIdentity sourceIdentity() { + TrustedPin current = trustedPin; + if (current != null) { + return current.sourceIdentity(); + } + synchronized (pinMonitor) { + current = trustedPin; + if (current == null) { + VerifiedSource verified = readVerifiedSource(); + current = verified.pin(); + trustedPin = current; + } + } + return current.sourceIdentity(); + } + + /** + * Derives one key's RFC 7638 fingerprint from a snapshot already loaded through this trusted + * source. It compares the immutable pin and grants no signer, registry, or token authority. + */ + static Optional publicKeyFingerprint( + PublicJwksSnapshot snapshot, SourceIdentity expectedSourceIdentity, String kid) { + if (snapshot == null + || expectedSourceIdentity == null + || !expectedSourceIdentity.equals(snapshot.sourceIdentity()) + || kid == null + || !kid.matches("[A-Za-z0-9_-]{1,64}")) { + throw rejected(); + } + Map fingerprints = + publicKeyFingerprints(new String(snapshot.jwksBytes(), StandardCharsets.UTF_8)); + return Optional.ofNullable(fingerprints.get(kid)); + } + + /** + * Loads one exact public JWKS snapshot after checking Account trust and receipt readback twice. + */ + @Override + public PublicJwksSnapshot load() { + TrustedPin expected = trustedPin; + if (expected == null) { + throw rejected(); + } + VerifiedSource verified = readVerifiedSource(); + if (!expected.equals(verified.pin())) { + throw rejected(); + } + return new PublicJwksSnapshot(expected.sourceIdentity(), verified.jwksBytes()); + } + + private VerifiedSource readVerifiedSource() { + Binding materializerBefore = currentMaterializerBinding(); + BindingIdentity apiBefore = currentApiIdentity(); + requireBindingsAgree(materializerBefore, apiBefore); + TrustedPin alreadyPinned = trustedPin; + if (alreadyPinned != null + && (!alreadyPinned.materializerBinding().equals(materializerBefore) + || !alreadyPinned.apiIdentity().equals(apiBefore))) { + throw rejected(); + } + + OwnerProjection ownerBefore = currentOwnerProjection(materializerBefore, apiBefore); + SourceIdentity pinnedIdentity = + sourceIdentity(materializerBefore, apiBefore, ownerBefore.projection().configMapUid()); + if (alreadyPinned != null && !alreadyPinned.sourceIdentity().equals(pinnedIdentity)) { + throw rejected(); + } + + ConfigMapSnapshot live; + try { + live = configMapClient.observe(); + } catch (AccountJwtJwksConfigMapClient.ResourceMissingException unavailable) { + requireUnchangedProtectedTrust(materializerBefore, apiBefore); + throw unavailable(); + } catch (AccountJwtJwksConfigMapClient.ApiFailureException failure) { + requireUnchangedProtectedTrust(materializerBefore, apiBefore); + if (isTemporaryApiFailure(failure.statusCode())) { + throw unavailable(); + } + throw rejected(); + } catch (AccountJwtJwksConfigMapClient.BindingRejectedException trustRejected) { + throw rejected(); + } catch (RuntimeException unexpected) { + throw rejected(); + } + + Binding materializerAfter = currentMaterializerBinding(); + BindingIdentity apiAfter = currentApiIdentity(); + if (!materializerBefore.equals(materializerAfter) || !apiBefore.equals(apiAfter)) { + throw rejected(); + } + + OwnerProjection ownerAfter = currentOwnerProjection(materializerAfter, apiAfter); + if (!ownerBefore.equals(ownerAfter)) { + // A concurrent Account lifecycle/publication change is not a coherent source snapshot. + throw unavailable(); + } + requireExactReadback(ownerAfter.projection(), live); + + byte[] jwks = + live.data() + .get(AccountJwtJwksPublicationRepository.JWKS_DATA_KEY) + .getBytes(StandardCharsets.UTF_8); + if (jwks.length == 0 || jwks.length > MAX_JWKS_BYTES) { + throw rejected(); + } + TrustedPin pin = new TrustedPin(materializerBefore, apiBefore, pinnedIdentity); + return new VerifiedSource(pin, jwks); + } + + private Binding currentMaterializerBinding() { + return materializerTrustBinding.current().orElseThrow(AccountJwtJwksTrustedSource::rejected); + } + + private BindingIdentity currentApiIdentity() { + try { + return Objects.requireNonNull(configMapClient.identity()); + } catch (RuntimeException rejectedBinding) { + throw rejected(); + } + } + + private OwnerProjection currentOwnerProjection(Binding binding, BindingIdentity api) { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw rejected(); + } + try { + OwnerProjection result = + accountTransaction.execute( + status -> { + DesiredState enrolled = + desiredStateRepository + .readEnrollmentState(binding.accountBinding()) + .orElseThrow(AccountJwtJwksTrustedSource::unavailable); + if (enrolled.durableActive().isEmpty() && enrolled.publishedActive().isEmpty()) { + return initialPrepublicationProjection(enrolled, binding, api); + } + CommittedSignerEvidence committed = + desiredStateRepository + .readCurrentCommittedSigner( + binding.accountBinding(), + trustFence(binding), + api.bindingDigest(), + api.configRevision()) + .orElseThrow(AccountJwtJwksTrustedSource::unavailable); + ActiveSigner currentActive = + new ActiveSigner( + committed.promotion().targetGeneration(), + committed.promotion().targetKid()); + PublishedProjection projection = committedProjection(committed); + if (committed.desiredState().generationOperationId().isEmpty()) { + return new OwnerProjection(committed, projection); + } + + var request = + desiredStateRepository.readCurrentGenerationRequest( + binding.accountBinding(), trustFence(binding)); + if (request.phase() + != AccountJwtSignerDesiredStateRepository.GenerationPhase.GENERATION_RECORDED) { + return new OwnerProjection(committed, projection); + } + Optional currentPublication = + publicationRepository.readCurrentPublication( + binding.accountBinding(), trustFence(binding)); + if (currentPublication.isEmpty() + || currentPublication.orElseThrow().receipt().isEmpty()) { + return new OwnerProjection(committed, projection); + } + PublicationEvidence evidence = currentPublication.orElseThrow(); + requirePublicationBinding(evidence, binding, api); + PrepublicationIntent intent = evidence.intent(); + var receipt = evidence.receipt().orElseThrow(); + if (!intent.operationId().equals(request.operationId()) + || !intent.operationDigest().equals(request.operationDigest()) + || !intent.generationRequestDigest().equals(request.generationRequestDigest()) + || !intent.generationReceiptDigest().equals(request.generationReceiptDigest()) + || !intent.targetGeneration().equals(request.targetGeneration()) + || !intent.targetKid().equals(request.targetKid()) + || !intent.publicKeyFingerprint().equals(request.publicKeyFingerprint()) + || !intent.expectedDurableActive().equals(Optional.of(currentActive)) + || !intent.expectedPublishedActive().equals(Optional.of(currentActive)) + || !intent.configMapUid().equals(committed.promotion().publicConfigMapUid()) + || !receipt.configMapUid().equals(committed.promotion().publicConfigMapUid()) + || !intent.apiBindingDigest().equals(api.bindingDigest()) + || !intent.apiConfigRevision().equals(api.configRevision())) { + throw rejected(); + } + requireRetainedPublicKeySet(committed, intent); + return new OwnerProjection( + committed, + new PublishedProjection( + intent.configMapUid(), + receipt.observedResourceVersion(), + intent.jwksJson(), + intent.generationMarkerJson(), + receipt.publicDataDigest())); + }); + if (result == null) { + throw unavailable(); + } + return result; + } catch (RuntimeException ownerStateUnavailable) { + if (ownerStateUnavailable instanceof SourceUnavailableException unavailable) { + throw unavailable; + } + if (ownerStateUnavailable instanceof IllegalStateException + && ownerStateUnavailable.getMessage() != null + && ownerStateUnavailable.getMessage().contains("Account trusted public JWKS source")) { + throw ownerStateUnavailable; + } + throw rejected(); + } + } + + /** + * The first exact Account-receipted PREPUBLISHED set is visible to validator probes before any + * signer is committed. It is never represented as an active signer and remains unavailable during + * PREPARED or after any active fence appears. + */ + private OwnerProjection initialPrepublicationProjection( + DesiredState enrolled, Binding binding, BindingIdentity api) { + if (!enrolled.binding().equals(binding.accountBinding()) + || enrolled.preparedOperationId().isPresent() + || enrolled.generationOperationId().isEmpty() + || enrolled.enrollmentIdentity().isEmpty()) { + throw rejected(); + } + EnrollmentIdentity enrollment = enrolled.enrollmentIdentity().orElseThrow(); + if (!enrollment.expectedClusterIncarnationUid().equals(binding.expectedClusterIncarnationUid()) + || !enrollment.expectedNamespaceUid().equals(binding.expectedNamespaceUid()) + || !enrollment.materializerTrustBindingDigest().equals(binding.bindingDigest()) + || !enrollment.materializerTrustConfigRevision().equals(binding.configRevision()) + || !enrollment.apiBindingDigest().equals(api.bindingDigest()) + || !enrollment.apiConfigRevision().equals(api.configRevision())) { + throw rejected(); + } + + GenerationRequest request = + desiredStateRepository.readCurrentGenerationRequest( + binding.accountBinding(), trustFence(binding)); + GenerationResult result = + desiredStateRepository.readCurrentGenerationResult( + binding.accountBinding(), trustFence(binding)); + if (request.phase() + != AccountJwtSignerDesiredStateRepository.GenerationPhase.GENERATION_RECORDED + || !request.expectedActive().isEmpty() + || !request.expectedPublishedActive().isEmpty() + || !enrolled.generationOperationId().equals(Optional.of(request.operationId())) + || !request.binding().equals(binding.accountBinding()) + || !request.trustFence().equals(trustFence(binding)) + || !result.binding().equals(binding.accountBinding()) + || !result.trustFence().equals(trustFence(binding)) + || request.desiredStateVersion() != result.desiredStateVersion() + || !request.operationId().equals(result.operationId()) + || !request.operationDigest().equals(result.operationDigest()) + || !request.generationRequestDigest().equals(result.generationRequestDigest()) + || !request.targetGeneration().equals(result.targetGeneration()) + || !request.targetKid().equals(result.targetKid()) + || !request.publicKeyFingerprint().equals(result.publicKeyFingerprint()) + || !request.publicJwkJson().equals(result.publicJwkJson()) + || !"RS256".equals(result.targetAlgorithm())) { + throw rejected(); + } + + PublicationEvidence evidence = + publicationRepository + .readCurrentPublication(binding.accountBinding(), trustFence(binding)) + .orElseThrow(AccountJwtJwksTrustedSource::unavailable); + requirePublicationBinding(evidence, binding, api); + PrepublicationIntent intent = evidence.intent(); + var receipt = evidence.receipt().orElseThrow(AccountJwtJwksTrustedSource::unavailable); + if (!intent.operationId().equals(result.operationId()) + || !intent.operationDigest().equals(result.operationDigest()) + || !intent.generationRequestDigest().equals(result.generationRequestDigest()) + || !intent.generationReceiptDigest().equals(result.receiptDigest()) + || intent.desiredStateVersion() != result.desiredStateVersion() + || !intent.expectedDurableActive().isEmpty() + || !intent.expectedPublishedActive().isEmpty() + || !intent.configMapUid().equals(enrollment.publicConfigMapUid()) + || !receipt.configMapUid().equals(enrollment.publicConfigMapUid()) + || !intent.apiBindingDigest().equals(enrollment.apiBindingDigest()) + || !intent.apiConfigRevision().equals(enrollment.apiConfigRevision()) + || !intent.targetGeneration().equals(result.targetGeneration()) + || !intent.targetKid().equals(result.targetKid()) + || !intent.publicKeyFingerprint().equals(result.publicKeyFingerprint())) { + throw rejected(); + } + Map publicKeys = publicKeyFingerprints(intent.jwksJson()); + if (publicKeys.size() != 1 + || !result.publicKeyFingerprint().equals(publicKeys.get(result.targetKid()))) { + throw rejected(); + } + requireInitialPrepublicationMarker(intent, result, binding, api); + return new OwnerProjection( + null, + new PublishedProjection( + intent.configMapUid(), + receipt.observedResourceVersion(), + intent.jwksJson(), + intent.generationMarkerJson(), + receipt.publicDataDigest())); + } + + private static void requireInitialPrepublicationMarker( + PrepublicationIntent intent, GenerationResult result, Binding binding, BindingIdentity api) { + try { + JsonNode marker = STRICT_JSON.readTree(intent.generationMarkerJson()); + JsonNode markerBinding = marker == null ? null : marker.get("binding"); + JsonNode publicConfigMap = marker == null ? null : marker.get("publicConfigMap"); + JsonNode pending = marker == null ? null : marker.get("pending"); + JsonNode durable = marker == null ? null : marker.get("expectedDurableActive"); + JsonNode published = marker == null ? null : marker.get("expectedPublishedActive"); + if (marker == null + || !marker.isObject() + || !hasExactFields( + marker, + java.util.Set.of( + "schemaVersion", + "phase", + "operationId", + "operationDigest", + "generationRequestDigest", + "generationReceiptDigest", + "binding", + "publicConfigMap", + "expectedDurableActive", + "expectedPublishedActive", + "pending")) + || !marker.get("schemaVersion").isIntegralNumber() + || marker.get("schemaVersion").intValue() != 1 + || !"PREPUBLISHED".equals(requiredText(marker, "phase")) + || !intent.operationId().toString().equals(requiredText(marker, "operationId")) + || !intent.operationDigest().equals(requiredText(marker, "operationDigest")) + || !intent + .generationRequestDigest() + .equals(requiredText(marker, "generationRequestDigest")) + || !intent + .generationReceiptDigest() + .equals(requiredText(marker, "generationReceiptDigest")) + || !hasExactFields( + markerBinding, + java.util.Set.of( + "environmentId", + "clusterId", + "namespace", + "expectedClusterIncarnationUid", + "expectedNamespaceUid", + "trustBindingDigest", + "trustConfigRevision", + "apiBindingDigest", + "apiConfigRevision")) + || !binding.environmentId().equals(requiredText(markerBinding, "environmentId")) + || !binding.clusterId().equals(requiredText(markerBinding, "clusterId")) + || !binding.namespace().equals(requiredText(markerBinding, "namespace")) + || !binding + .expectedClusterIncarnationUid() + .equals(requiredText(markerBinding, "expectedClusterIncarnationUid")) + || !binding + .expectedNamespaceUid() + .equals(requiredText(markerBinding, "expectedNamespaceUid")) + || !binding.bindingDigest().equals(requiredText(markerBinding, "trustBindingDigest")) + || !binding.configRevision().equals(requiredText(markerBinding, "trustConfigRevision")) + || !api.bindingDigest().equals(requiredText(markerBinding, "apiBindingDigest")) + || !api.configRevision().equals(requiredText(markerBinding, "apiConfigRevision")) + || !hasExactFields(publicConfigMap, java.util.Set.of("name")) + || !AccountJwtJwksConfigMapClient.CONFIG_MAP_NAME.equals( + requiredText(publicConfigMap, "name")) + || !hasExactFields( + pending, java.util.Set.of("generation", "kid", "algorithm", "publicKeyFingerprint")) + || !result.targetGeneration().equals(requiredText(pending, "generation")) + || !result.targetKid().equals(requiredText(pending, "kid")) + || !"RS256".equals(requiredText(pending, "algorithm")) + || !result.publicKeyFingerprint().equals(requiredText(pending, "publicKeyFingerprint")) + || !inactiveMarker(durable) + || !inactiveMarker(published)) { + throw rejected(); + } + } catch (RuntimeException malformed) { + throw rejected(); + } + } + + private static boolean inactiveMarker(JsonNode marker) { + return hasExactFields(marker, java.util.Set.of("present")) + && marker.get("present").isBoolean() + && !marker.get("present").booleanValue(); + } + + private static void requireBindingsAgree(Binding materializer, BindingIdentity api) { + if (!materializer.environmentId().equals(api.environmentId()) + || !materializer.clusterId().equals(api.clusterId()) + || !materializer.namespace().equals(api.namespace()) + || !materializer.expectedClusterIncarnationUid().equals(api.expectedClusterIncarnationUid()) + || !materializer.expectedNamespaceUid().equals(api.expectedNamespaceUid()) + || api.bindingDigest() == null + || api.configRevision() == null + || api.expectedApiUsername() == null + || !api.expectedApiUsername() + .equals( + ACCOUNT_SERVICE_USERNAME_PREFIX + + materializer.namespace() + + ":" + + ACCOUNT_SERVICE_NAME)) { + throw rejected(); + } + URI endpoint; + try { + endpoint = URI.create(api.apiServerUrl()); + } catch (RuntimeException malformedEndpoint) { + throw rejected(); + } + if (!"https".equalsIgnoreCase(endpoint.getScheme()) + || endpoint.getHost() == null + || endpoint.getPort() <= 0 + || endpoint.getRawUserInfo() != null + || endpoint.getRawQuery() != null + || endpoint.getRawFragment() != null + || (endpoint.getRawPath() != null + && !endpoint.getRawPath().isEmpty() + && !"/".equals(endpoint.getRawPath())) + || api.tlsServerName() == null + || !endpoint.getHost().equalsIgnoreCase(api.tlsServerName()) + || api.servingCaSha256() == null) { + throw rejected(); + } + } + + private static void requirePublicationBinding( + PublicationEvidence evidence, Binding materializer, BindingIdentity api) { + PrepublicationIntent intent = evidence.intent(); + if (!intent.binding().equals(materializer.accountBinding()) + || !intent.trustFence().equals(trustFence(materializer)) + || !AccountJwtJwksConfigMapClient.CONFIG_MAP_NAME.equals(intent.configMapName()) + || !intent.apiBindingDigest().equals(api.bindingDigest()) + || !intent.apiConfigRevision().equals(api.configRevision()) + || !AccountJwtJwksPublicationRepository.publicDataDigest( + intent.jwksJson(), intent.generationMarkerJson()) + .equals(intent.publicDataDigest())) { + throw rejected(); + } + PublicationReceipt receipt = evidence.receipt().orElse(null); + if (receipt != null + && (!receipt.operationId().equals(intent.operationId()) + || !receipt.binding().equals(materializer.accountBinding()) + || !receipt.intentDigest().equals(intent.intentDigest()) + || !receipt.configMapUid().equals(intent.configMapUid()) + || !receipt.publicDataDigest().equals(intent.publicDataDigest()) + || !receipt.expectedResourceVersion().equals(intent.expectedResourceVersion()))) { + throw rejected(); + } + } + + private static PublishedProjection committedProjection(CommittedSignerEvidence committed) { + PromotionOperationEvidence promotion = committed.promotion(); + var receipt = committed.publicReceipt(); + String dataDigest = + AccountJwtJwksPublicationRepository.publicDataDigest( + promotion.expectedPublicJwksJson(), promotion.expectedActiveMarkerJson()); + if (!promotion.publicConfigMapUid().equals(receipt.configMapUid()) + || !promotion + .activeJwksObservedResourceVersion() + .orElseThrow() + .equals(receipt.observedResourceVersion()) + || !promotion.activeJwksPublicDataDigest().orElseThrow().equals(dataDigest) + || !receipt.publicDataDigest().equals(dataDigest)) { + throw rejected(); + } + return new PublishedProjection( + receipt.configMapUid(), + receipt.observedResourceVersion(), + promotion.expectedPublicJwksJson(), + promotion.expectedActiveMarkerJson(), + dataDigest); + } + + private static void requireRetainedPublicKeySet( + CommittedSignerEvidence committed, PrepublicationIntent intent) { + Map previousKeys = + publicKeyFingerprints(committed.promotion().expectedPublicJwksJson()); + Map currentKeys = publicKeyFingerprints(intent.jwksJson()); + if (previousKeys.isEmpty() || currentKeys.size() < previousKeys.size()) { + throw rejected(); + } + if (new BigInteger(intent.targetGeneration()) + .compareTo(new BigInteger(committed.promotion().targetGeneration())) + <= 0) { + throw rejected(); + } + for (Map.Entry previous : previousKeys.entrySet()) { + if (!previous.getValue().equals(currentKeys.get(previous.getKey()))) { + throw rejected(); + } + } + if (!intent.publicKeyFingerprint().equals(currentKeys.get(intent.targetKid())) + || !committed + .promotion() + .targetPublicKeyFingerprint() + .equals(currentKeys.get(committed.promotion().targetKid()))) { + throw rejected(); + } + } + + private static Map publicKeyFingerprints(String jwksJson) { + try { + if (jwksJson == null + || jwksJson.isBlank() + || jwksJson.getBytes(StandardCharsets.UTF_8).length > MAX_JWKS_BYTES) { + throw new IllegalArgumentException(); + } + JsonNode root = STRICT_JSON.readTree(jwksJson); + if (root == null || !root.isObject() || !hasExactFields(root, JWKS_FIELDS)) { + throw new IllegalArgumentException(); + } + JsonNode keys = root.get("keys"); + if (keys == null || !keys.isArray() || keys.isEmpty() || keys.size() > MAX_KEYS) { + throw new IllegalArgumentException(); + } + Map fingerprints = new LinkedHashMap<>(); + for (JsonNode key : keys) { + if (key == null || !key.isObject() || !hasExactFields(key, JWK_FIELDS)) { + throw new IllegalArgumentException(); + } + String kty = requiredText(key, "kty"); + String use = requiredText(key, "use"); + String alg = requiredText(key, "alg"); + String kid = requiredText(key, "kid"); + String modulus = requiredText(key, "n"); + String exponent = requiredText(key, "e"); + JsonNode keyOps = key.get("key_ops"); + if (!"RSA".equals(kty) + || !"sig".equals(use) + || !"RS256".equals(alg) + || !kid.matches("[A-Za-z0-9_-]{1,64}") + || keyOps == null + || !keyOps.isArray() + || keyOps.size() != 1 + || !keyOps.get(0).isTextual() + || !"verify".equals(keyOps.get(0).textValue())) { + throw new IllegalArgumentException(); + } + String preimage = + new String( + Rfc8785CanonicalJson.canonicalizeUtf8( + STRICT_JSON.writeValueAsString( + Map.of("e", exponent, "kty", kty, "n", modulus))), + StandardCharsets.UTF_8); + String fingerprint = + HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256") + .digest(preimage.getBytes(StandardCharsets.UTF_8))); + if (fingerprints.putIfAbsent(kid, fingerprint) != null) { + throw new IllegalArgumentException(); + } + } + return Map.copyOf(fingerprints); + } catch (IOException | NoSuchAlgorithmException | RuntimeException malformed) { + throw rejected(); + } + } + + private static String requiredText(JsonNode object, String field) { + JsonNode value = object.get(field); + if (value == null || !value.isTextual() || value.textValue().isEmpty()) { + throw new IllegalArgumentException(); + } + return value.textValue(); + } + + private static boolean hasExactFields(JsonNode object, java.util.Set expected) { + if (object == null || !object.isObject() || object.size() != expected.size()) { + return false; + } + for (Map.Entry property : object.properties()) { + if (!expected.contains(property.getKey())) { + return false; + } + } + return true; + } + + private static void requireExactReadback(PublishedProjection projection, ConfigMapSnapshot live) { + String jwks = live.data().get(AccountJwtJwksPublicationRepository.JWKS_DATA_KEY); + String marker = live.data().get(AccountJwtJwksPublicationRepository.GENERATION_MARKER_DATA_KEY); + if (!projection.configMapUid().equals(live.uid()) + || !projection.resourceVersion().equals(live.resourceVersion()) + || !projection.jwksJson().equals(jwks) + || !projection.markerJson().equals(marker) + || marker == null + || marker.getBytes(StandardCharsets.UTF_8).length > MAX_MARKER_BYTES + || !AccountJwtJwksPublicationRepository.publicDataDigest(jwks, marker) + .equals(projection.publicDataDigest())) { + throw rejected(); + } + } + + private static SourceIdentity sourceIdentity( + Binding materializer, BindingIdentity api, String configMapUid) { + try { + return new SourceIdentity( + materializer.environmentId(), + materializer.clusterId(), + materializer.expectedClusterIncarnationUid(), + materializer.namespace(), + materializer.expectedNamespaceUid(), + configMapUid, + api.configRevision(), + api.apiServerUrl(), + api.servingCaSha256()); + } catch (RuntimeException invalidIdentity) { + throw rejected(); + } + } + + private void requireUnchangedProtectedTrust(Binding expected, BindingIdentity expectedApi) { + Binding currentMaterializer = currentMaterializerBinding(); + BindingIdentity currentApi = currentApiIdentity(); + if (!expected.equals(currentMaterializer) || !expectedApi.equals(currentApi)) { + throw rejected(); + } + } + + private static boolean isTemporaryApiFailure(int statusCode) { + return statusCode == 0 || statusCode == 408 || statusCode == 429 || statusCode >= 500; + } + + private static TrustFence trustFence(Binding binding) { + return new TrustFence( + binding.expectedClusterIncarnationUid(), + binding.expectedNamespaceUid(), + binding.bindingDigest(), + binding.configRevision()); + } + + private static SourceUnavailableException unavailable() { + return new SourceUnavailableException(); + } + + private static IllegalStateException rejected() { + return new IllegalStateException("Account trusted public JWKS source was rejected"); + } + + private record TrustedPin( + Binding materializerBinding, BindingIdentity apiIdentity, SourceIdentity sourceIdentity) {} + + private record OwnerProjection( + CommittedSignerEvidence committedSigner, PublishedProjection projection) {} + + private record PublishedProjection( + String configMapUid, + String resourceVersion, + String jwksJson, + String markerJson, + String publicDataDigest) {} + + private record VerifiedSource(TrustedPin pin, byte[] jwksBytes) {} +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessProbeOwnerSelector.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessProbeOwnerSelector.java new file mode 100644 index 0000000000..3344965501 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessProbeOwnerSelector.java @@ -0,0 +1,165 @@ +package net.firedevops.firemud.accountservice.service.session; + +import java.net.URI; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.ActiveSigner; +import net.firedevops.firemud.accountservice.service.session.AccountJwtReadinessReceiverInvocationPort.ProbeExpectation; +import net.firedevops.firemud.accountservice.service.session.AccountMountedJwtSignerBundle.ProbeKind; + +/** Closed, bounded selector for an authenticated read of one current V2 readiness entry. */ +public record AccountJwtReadinessProbeOwnerSelector( + UUID rotationOperationId, + String operationDigest, + String planDigest, + int planVersion, + int registryVersion, + String validatorId, + String tokenProfile, + String audience, + ProbeKind probeKind, + ProbeExpectation expectedOutcome, + UUID jti, + long entryVersion, + String targetGeneration, + String targetKid, + Optional expectedActive, + long issuedAtEpochSecond, + long expiresAtEpochSecond, + long planExpiresAtEpochSecond, + String compactTokenSha256, + LocalIdentity localIdentity) { + private static final Pattern DIGEST = Pattern.compile("[0-9a-f]{64}"); + private static final Pattern ID = Pattern.compile("[a-z0-9][a-z0-9-]{0,62}"); + private static final Pattern PROFILE = Pattern.compile("[a-z][a-z0-9-]{0,62}"); + private static final Pattern KID = Pattern.compile("[A-Za-z0-9_-]{1,64}"); + private static final Pattern GENERATION = Pattern.compile("[1-9][0-9]{0,18}"); + private static final Pattern REVISION = Pattern.compile("[A-Za-z0-9][A-Za-z0-9._:-]{0,127}"); + + public AccountJwtReadinessProbeOwnerSelector { + Objects.requireNonNull(rotationOperationId, "operation ID is required"); + if (rotationOperationId.version() != 4 || rotationOperationId.variant() != 2) { + throw new IllegalArgumentException("Canonical readiness operation UUIDv4 is required"); + } + requireDigest(operationDigest, "operation digest"); + requireDigest(planDigest, "plan digest"); + if (planVersion != AccountJwtReadinessProbeRepository.INVENTORY_PLAN_VERSION + || registryVersion != 1 + || entryVersion <= 0L) { + throw new IllegalArgumentException("Current V2 readiness coordinates are required"); + } + requireId(validatorId, "validator ID"); + requireProfile(tokenProfile); + requireProfile(audience); + Objects.requireNonNull(probeKind, "probe kind is required"); + Objects.requireNonNull(expectedOutcome, "expected outcome is required"); + Objects.requireNonNull(jti, "probe JTI is required"); + if (jti.version() != 4 || jti.variant() != 2) { + throw new IllegalArgumentException("Canonical readiness JTI is required"); + } + requireGeneration(targetGeneration); + requireKid(targetKid); + expectedActive = Objects.requireNonNull(expectedActive, "active fence state is required"); + if (issuedAtEpochSecond <= 0L + || expiresAtEpochSecond <= issuedAtEpochSecond + || planExpiresAtEpochSecond <= 0L + || expiresAtEpochSecond > planExpiresAtEpochSecond) { + throw new IllegalArgumentException("Readiness probe time bounds are malformed"); + } + requireDigest(compactTokenSha256, "compact token digest"); + Objects.requireNonNull(localIdentity, "protected local identity is required"); + } + + public record LocalIdentity( + String validatorId, + String deploymentUid, + String podUid, + String podIp, + String directPodEndpoint, + String canonicalServiceUri, + String image, + String verifierConfigSha256, + String applicabilityMatrixDigest, + String sourceInventoryRevision, + String sourceInventoryDigest, + String serverLeafSpkiSha256) { + public LocalIdentity { + requireId(validatorId, "validator ID"); + requireCanonicalUuid(deploymentUid, "deployment UID"); + requireCanonicalUuid(podUid, "Pod UID"); + if (!net.firedevops.firemud.accountservice.config.AccountJwtValidatorInventoryBinding + .canonicalPodIp(podIp) + .equals(podIp)) { + throw new IllegalArgumentException("Pod IP is not canonical"); + } + requireText(directPodEndpoint, 256, "direct Pod endpoint"); + requireText(canonicalServiceUri, 256, "canonical service URI"); + if (image == null || !image.matches("[^\\s@]+@sha256:[0-9a-f]{64}")) { + throw new IllegalArgumentException("Validator image must be digest-pinned"); + } + requireDigest(verifierConfigSha256, "verifier configuration digest"); + requireDigest(applicabilityMatrixDigest, "applicability matrix digest"); + if (sourceInventoryRevision == null || !REVISION.matcher(sourceInventoryRevision).matches()) { + throw new IllegalArgumentException("Receiver source inventory revision is malformed"); + } + requireDigest(sourceInventoryDigest, "receiver source inventory digest"); + requireDigest(serverLeafSpkiSha256, "receiver TLS SPKI digest"); + URI endpoint = URI.create(directPodEndpoint); + if (!endpoint.toString().equals(directPodEndpoint) + || !canonicalServiceUri.matches( + "spiffe://firemud/ns/[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?/sa/[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?")) { + throw new IllegalArgumentException("Receiver endpoint or service identity is malformed"); + } + } + } + + private static void requireCanonicalUuid(String value, String label) { + if (value == null + || !value.matches("[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}") + || !UUID.fromString(value).toString().equals(value)) { + throw new IllegalArgumentException(label + " is not canonical"); + } + } + + private static void requireDigest(String value, String label) { + if (value == null || !DIGEST.matcher(value).matches()) { + throw new IllegalArgumentException(label + " is malformed"); + } + } + + private static void requireId(String value, String label) { + if (value == null || !ID.matcher(value).matches()) { + throw new IllegalArgumentException(label + " is malformed"); + } + } + + private static void requireProfile(String value) { + if (value == null || !PROFILE.matcher(value).matches()) { + throw new IllegalArgumentException("Readiness profile or audience is malformed"); + } + } + + private static void requireKid(String value) { + if (value == null || !KID.matcher(value).matches()) { + throw new IllegalArgumentException("Readiness target key ID is malformed"); + } + } + + private static void requireGeneration(String value) { + if (value == null || !GENERATION.matcher(value).matches()) { + throw new IllegalArgumentException("Readiness target generation is malformed"); + } + } + + private static void requireText(String value, int maximum, String label) { + if (value == null + || value.isBlank() + || value.length() > maximum + || value.chars().anyMatch(Character::isISOControl)) { + throw new IllegalArgumentException(label + " is malformed"); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessReceiverInvocationPort.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessReceiverInvocationPort.java new file mode 100644 index 0000000000..88acaea9a6 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessReceiverInvocationPort.java @@ -0,0 +1,593 @@ +package net.firedevops.firemud.accountservice.service.session; + +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.accountservice.config.AccountJwtValidatorInventoryBinding; +import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository; +import net.firedevops.firemud.accountservice.service.session.AccountMountedJwtSignerBundle.ProbeKind; + +/** + * Account-owned internal invocation boundary for one exact validator Pod and one exact probe. + * + *

The production implementation must route to the observed Pod endpoint, verify the TLS peer + * against its protected Pod-specific pin while retaining the canonical service SAN, and return an + * {@link AuthenticatedAcceptance} only after validating the receiver's production-verifier result + * and local Pod identity. No RPC request or harness DTO is an implementation of this port. + */ +public abstract class AccountJwtReadinessReceiverInvocationPort { + private static final Pattern UUID_V4 = + Pattern.compile("[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}"); + private static final Pattern UUID_CANONICAL = + Pattern.compile("[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}"); + private static final Pattern DIGEST = Pattern.compile("[0-9a-f]{64}"); + private static final Pattern ID = Pattern.compile("[a-z0-9][a-z0-9-]{0,62}"); + private static final Pattern SERVICE_URI = + Pattern.compile( + "spiffe://firemud/ns/[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?/sa/[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?"); + + /** Invokes one Pod; implementations must fail closed if any target binding is unavailable. */ + public abstract AuthenticatedAcceptance invoke(Invocation invocation); + + /** Availability guard called before one-shot signing or delivery is durably claimed. */ + public abstract void requireAvailable(); + + /** No remote receiver or Pod-bound transport identity is currently composed. */ + public static AccountJwtReadinessReceiverInvocationPort defaultDenied() { + return new AccountJwtReadinessReceiverInvocationPort() { + @Override + public AuthenticatedAcceptance invoke(Invocation invocation) { + throw new ReceiverUnavailableException(); + } + + @Override + public void requireAvailable() { + throw new ReceiverUnavailableException(); + } + }; + } + + /** Owner-package factory for a response already authenticated by the real Pod-bound client. */ + static AuthenticatedAcceptance authenticatedAcceptance( + String podUid, + String actualPodEndpoint, + String image, + String verifierConfigSha256, + String actualServiceUri, + String actualPeerSpkiSha256, + UUID jti, + String compactTokenSha256, + String verifiedKid, + ProbeExpectation result, + long observedAtEpochSecond) { + return new AuthenticatedAcceptance( + podUid, + actualPodEndpoint, + image, + verifierConfigSha256, + actualServiceUri, + actualPeerSpkiSha256, + jti, + compactTokenSha256, + verifiedKid, + result, + observedAtEpochSecond); + } + + /** Exact, non-secret Pod target derived by Account from one protected inventory snapshot. */ + public record PodTarget( + String inventorySnapshotDigest, + String environmentId, + String clusterId, + String clusterIncarnationUid, + String namespace, + String namespaceUid, + String apiBindingRevision, + String apiBindingDigest, + String inventoryBindingRevision, + String inventoryBindingDigest, + String validatorId, + String deploymentUid, + String podUid, + String podIp, + String image, + String verifierConfigSha256, + String applicabilityMatrixDigest, + ProbeExpectation expectation, + Optional exactPodEndpoint, + Optional canonicalServiceUri, + Optional podLeafSpkiSha256) { + public PodTarget { + requireDigest(inventorySnapshotDigest, "inventory snapshot digest"); + requireIdentity(environmentId, "environment ID"); + requireCluster(clusterId); + requireCanonicalUuid(clusterIncarnationUid, "cluster incarnation UID"); + requireIdentity(namespace, "Kubernetes namespace"); + requireCanonicalUuid(namespaceUid, "namespace UID"); + requireRevision(apiBindingRevision, "Kubernetes API binding revision"); + requireDigest(apiBindingDigest, "Kubernetes API binding digest"); + requireRevision(inventoryBindingRevision, "inventory binding revision"); + requireDigest(inventoryBindingDigest, "inventory binding digest"); + requireId(validatorId, "validator ID"); + requireCanonicalUuid(deploymentUid, "validator Deployment UID"); + requireCanonicalUuid(podUid, "validator Pod UID"); + if (!AccountJwtValidatorInventoryBinding.canonicalPodIp(podIp).equals(podIp)) { + throw new IllegalArgumentException("Protected validator Pod IP is not canonical"); + } + if (image == null || !image.matches("[^\\s@]+@sha256:[0-9a-f]{64}")) { + throw new IllegalArgumentException("Validator image must be pinned by digest"); + } + requireDigest(verifierConfigSha256, "verifier configuration digest"); + requireDigest(applicabilityMatrixDigest, "applicability matrix digest"); + Objects.requireNonNull(expectation, "probe expectation is required"); + exactPodEndpoint = Objects.requireNonNull(exactPodEndpoint); + canonicalServiceUri = Objects.requireNonNull(canonicalServiceUri); + podLeafSpkiSha256 = Objects.requireNonNull(podLeafSpkiSha256); + exactPodEndpoint.ifPresent(endpoint -> requirePodEndpoint(endpoint, podIp)); + canonicalServiceUri.ifPresent(AccountJwtReadinessReceiverInvocationPort::requireServiceUri); + podLeafSpkiSha256.ifPresent(value -> requireDigest(value, "Pod TLS leaf SPKI digest")); + } + + /** Missing addressing or a Pod-specific peer pin makes this target non-invocable. */ + public void requireRoutablePodIdentity() { + if (exactPodEndpoint.isEmpty() + || canonicalServiceUri.isEmpty() + || podLeafSpkiSha256.isEmpty()) { + throw new ReceiverUnavailableException(); + } + } + } + + /** One exact logical registry probe, including transient signed bytes but no signer authority. */ + public static final class Invocation { + private final UUID rotationOperationId; + private final String operationDigest; + private final String planDigest; + private final int planVersion; + private final long planExpiresAtEpochSecond; + private final String validatorId; + private final String tokenProfile; + private final String audience; + private final ProbeKind probeKind; + private final ProbeExpectation expectation; + private final int registryVersion; + private final long sourceEntryVersion; + private final UUID jti; + private final String compactJwt; + private final String compactTokenSha256; + private final String targetGeneration; + private final String targetKid; + private final Optional expectedActiveGeneration; + private final Optional expectedActiveKid; + private final long issuedAtEpochSecond; + private final long expiresAtEpochSecond; + private final PodTarget target; + + Invocation( + UUID rotationOperationId, + String operationDigest, + String planDigest, + int planVersion, + long planExpiresAtEpochSecond, + String validatorId, + String tokenProfile, + String audience, + ProbeKind probeKind, + ProbeExpectation expectation, + int registryVersion, + long sourceEntryVersion, + UUID jti, + String compactJwt, + String compactTokenSha256, + String targetGeneration, + String targetKid, + Optional expectedActiveGeneration, + Optional expectedActiveKid, + long issuedAtEpochSecond, + long expiresAtEpochSecond, + PodTarget target) { + this.rotationOperationId = Objects.requireNonNull(rotationOperationId); + requireUuid(rotationOperationId.toString(), "rotation operation ID"); + requireDigest(operationDigest, "generation operation digest"); + requireDigest(planDigest, "readiness plan digest"); + if (planVersion != AccountJwtReadinessProbeRepository.INVENTORY_PLAN_VERSION + || planExpiresAtEpochSecond <= 0L) { + throw new IllegalArgumentException("Exact V2 readiness plan coordinates are required"); + } + requireId(validatorId, "validator ID"); + if (tokenProfile == null || !tokenProfile.matches("[a-z][a-z0-9-]{0,127}")) { + throw new IllegalArgumentException("Token profile is malformed"); + } + if (audience == null || !audience.matches("[A-Za-z0-9][A-Za-z0-9._:-]{0,127}")) { + throw new IllegalArgumentException("Token audience is malformed"); + } + this.operationDigest = operationDigest; + this.planDigest = planDigest; + this.planVersion = planVersion; + this.planExpiresAtEpochSecond = planExpiresAtEpochSecond; + this.validatorId = validatorId; + this.tokenProfile = tokenProfile; + this.audience = audience; + this.probeKind = Objects.requireNonNull(probeKind); + this.expectation = Objects.requireNonNull(expectation); + if (registryVersion != 1 || sourceEntryVersion <= 0L) { + throw new IllegalArgumentException("Readiness entry version is malformed"); + } + this.registryVersion = registryVersion; + this.sourceEntryVersion = sourceEntryVersion; + this.jti = Objects.requireNonNull(jti); + requireUuid(jti.toString(), "probe JTI"); + if (compactJwt == null + || compactJwt.isBlank() + || compactJwt.length() > 16 * 1024 + || !compactJwt.matches("[A-Za-z0-9_=-]+\\.[A-Za-z0-9_=-]+\\.[A-Za-z0-9_=-]+")) { + throw new IllegalArgumentException("Compact readiness token is malformed"); + } + requireDigest(compactTokenSha256, "compact readiness token digest"); + if (!compactTokenSha256.equals(sha256(compactJwt))) { + throw new IllegalArgumentException("Compact readiness token digest does not match bytes"); + } + this.compactJwt = compactJwt; + this.compactTokenSha256 = compactTokenSha256; + if (targetGeneration == null || !targetGeneration.matches("[1-9][0-9]{0,18}")) { + throw new IllegalArgumentException("Target generation is malformed"); + } + if (targetKid == null || !targetKid.matches("[A-Za-z0-9_-]{1,64}")) { + throw new IllegalArgumentException("Target key ID is malformed"); + } + this.targetGeneration = targetGeneration; + this.targetKid = targetKid; + this.expectedActiveGeneration = Objects.requireNonNull(expectedActiveGeneration); + this.expectedActiveKid = Objects.requireNonNull(expectedActiveKid); + if (expectedActiveGeneration.isPresent() != expectedActiveKid.isPresent()) { + throw new IllegalArgumentException("Expected active signer fence is partial"); + } + this.expectedActiveGeneration.ifPresent( + value -> { + if (!value.matches("[1-9][0-9]{0,18}")) { + throw new IllegalArgumentException("Expected active generation is malformed"); + } + }); + this.expectedActiveKid.ifPresent( + value -> { + if (!value.matches("[A-Za-z0-9_-]{1,64}")) { + throw new IllegalArgumentException("Expected active key ID is malformed"); + } + }); + if (issuedAtEpochSecond <= 0L + || expiresAtEpochSecond <= issuedAtEpochSecond + || expiresAtEpochSecond > planExpiresAtEpochSecond) { + throw new IllegalArgumentException("Readiness token lifetime is malformed"); + } + this.issuedAtEpochSecond = issuedAtEpochSecond; + this.expiresAtEpochSecond = expiresAtEpochSecond; + this.target = Objects.requireNonNull(target); + if (!validatorId.equals(target.validatorId())) { + throw new IllegalArgumentException("Readiness probe and Pod validator differ"); + } + } + + public UUID rotationOperationId() { + return rotationOperationId; + } + + public String operationDigest() { + return operationDigest; + } + + public String planDigest() { + return planDigest; + } + + public int planVersion() { + return planVersion; + } + + public long planExpiresAtEpochSecond() { + return planExpiresAtEpochSecond; + } + + public String validatorId() { + return validatorId; + } + + public String tokenProfile() { + return tokenProfile; + } + + public String audience() { + return audience; + } + + public ProbeKind probeKind() { + return probeKind; + } + + public ProbeExpectation expectation() { + return expectation; + } + + public int registryVersion() { + return registryVersion; + } + + public long sourceEntryVersion() { + return sourceEntryVersion; + } + + public UUID jti() { + return jti; + } + + public String compactJwt() { + return compactJwt; + } + + public String compactTokenSha256() { + return compactTokenSha256; + } + + public String targetGeneration() { + return targetGeneration; + } + + public String targetKid() { + return targetKid; + } + + public Optional expectedActiveGeneration() { + return expectedActiveGeneration; + } + + public Optional expectedActiveKid() { + return expectedActiveKid; + } + + public long issuedAtEpochSecond() { + return issuedAtEpochSecond; + } + + public long expiresAtEpochSecond() { + return expiresAtEpochSecond; + } + + public PodTarget target() { + return target; + } + + @Override + public String toString() { + return "AccountJwtReadinessReceiverInvocation[rotationOperationId=" + + rotationOperationId + + ", validatorId=" + + validatorId + + ", podUid=" + + target.podUid() + + ", jti=" + + jti + + ", tokenRedacted=true]"; + } + } + + public enum ProbeExpectation { + ACCEPT, + INAPPLICABLE_REJECT + } + + /** + * Internal result established by the Account-owned receiver client after mTLS and response + * identity checks. Its package-private constructor is not available to an RPC adapter/harness. + */ + public static final class AuthenticatedAcceptance { + private final String podUid; + private final String actualPodEndpoint; + private final String image; + private final String verifierConfigSha256; + private final String actualServiceUri; + private final String actualPeerSpkiSha256; + private final UUID jti; + private final String compactTokenSha256; + private final String verifiedKid; + private final ProbeExpectation result; + private final long observedAtEpochSecond; + + private AuthenticatedAcceptance( + String podUid, + String actualPodEndpoint, + String image, + String verifierConfigSha256, + String actualServiceUri, + String actualPeerSpkiSha256, + UUID jti, + String compactTokenSha256, + String verifiedKid, + ProbeExpectation result, + long observedAtEpochSecond) { + requireCanonicalUuid(podUid, "receiver-reported local Pod UID"); + requirePodEndpointShape(actualPodEndpoint); + if (image == null || !image.matches("[^\\s@]+@sha256:[0-9a-f]{64}")) { + throw new IllegalArgumentException("Receiver image is not pinned by digest"); + } + requireDigest(verifierConfigSha256, "receiver verifier configuration digest"); + requireServiceUri(actualServiceUri); + requireDigest(actualPeerSpkiSha256, "authenticated peer SPKI digest"); + Objects.requireNonNull(jti); + requireUuid(jti.toString(), "receiver probe JTI"); + requireDigest(compactTokenSha256, "receiver compact token digest"); + if (verifiedKid == null || !verifiedKid.matches("[A-Za-z0-9_-]{1,64}")) { + throw new IllegalArgumentException("Receiver verified key ID is malformed"); + } + this.result = Objects.requireNonNull(result); + if (observedAtEpochSecond <= 0L) { + throw new IllegalArgumentException("Receiver observation time is malformed"); + } + this.podUid = podUid; + this.actualPodEndpoint = actualPodEndpoint; + this.image = image; + this.verifierConfigSha256 = verifierConfigSha256; + this.actualServiceUri = actualServiceUri; + this.actualPeerSpkiSha256 = actualPeerSpkiSha256; + this.jti = jti; + this.compactTokenSha256 = compactTokenSha256; + this.verifiedKid = verifiedKid; + this.observedAtEpochSecond = observedAtEpochSecond; + } + + public String podUid() { + return podUid; + } + + public String actualPodEndpoint() { + return actualPodEndpoint; + } + + public String image() { + return image; + } + + public String verifierConfigSha256() { + return verifierConfigSha256; + } + + public String actualServiceUri() { + return actualServiceUri; + } + + public String actualPeerSpkiSha256() { + return actualPeerSpkiSha256; + } + + public UUID jti() { + return jti; + } + + public String compactTokenSha256() { + return compactTokenSha256; + } + + public String verifiedKid() { + return verifiedKid; + } + + public ProbeExpectation result() { + return result; + } + + public long observedAtEpochSecond() { + return observedAtEpochSecond; + } + + @Override + public String toString() { + return "AccountJwtReadinessAuthenticatedAcceptance[podUid=" + + podUid + + ", jti=" + + jti + + ", tokenRedacted=true]"; + } + } + + public static final class ReceiverUnavailableException extends IllegalStateException { + public ReceiverUnavailableException() { + super("Account JWT readiness receiver transport is unavailable"); + } + } + + private static void requirePodEndpoint(URI endpoint, String podIp) { + String endpointHost = podIp.indexOf(':') >= 0 ? "[" + podIp + "]" : podIp; + if (!"grpcs".equals(endpoint.getScheme()) + || endpoint.getHost() == null + || endpoint.getPort() < 1 + || endpoint.getPort() > 65535 + || endpoint.getRawUserInfo() != null + || endpoint.getRawQuery() != null + || endpoint.getRawFragment() != null + || (endpoint.getRawPath() != null && !endpoint.getRawPath().isEmpty()) + || !endpoint.toString().equals("grpcs://" + endpointHost + ":" + endpoint.getPort())) { + throw new IllegalArgumentException("Exact Pod endpoint is malformed"); + } + } + + private static void requirePodEndpointShape(String value) { + try { + URI endpoint = URI.create(value); + if (!"grpcs".equals(endpoint.getScheme()) + || endpoint.getHost() == null + || endpoint.getPort() < 1 + || endpoint.getPort() > 65535 + || endpoint.getRawUserInfo() != null + || endpoint.getRawQuery() != null + || endpoint.getRawFragment() != null + || (endpoint.getRawPath() != null && !endpoint.getRawPath().isEmpty())) { + throw new IllegalArgumentException("Observed Pod endpoint is malformed"); + } + } catch (RuntimeException failure) { + throw new IllegalArgumentException("Observed Pod endpoint is malformed", failure); + } + } + + private static void requireServiceUri(String value) { + if (value == null || !SERVICE_URI.matcher(value).matches()) { + throw new IllegalArgumentException("Canonical validator service SAN is malformed"); + } + } + + private static void requireDigest(String value, String name) { + if (value == null || !DIGEST.matcher(value).matches()) { + throw new IllegalArgumentException(name + " is malformed"); + } + } + + private static void requireUuid(String value, String name) { + if (value == null || !UUID_V4.matcher(value).matches()) { + throw new IllegalArgumentException(name + " is malformed"); + } + } + + private static void requireCanonicalUuid(String value, String name) { + if (value == null || !UUID_CANONICAL.matcher(value).matches()) { + throw new IllegalArgumentException(name + " is malformed"); + } + } + + private static void requireId(String value, String name) { + if (value == null || !ID.matcher(value).matches()) { + throw new IllegalArgumentException(name + " is malformed"); + } + } + + private static void requireIdentity(String value, String name) { + if (value == null || !value.matches("[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?")) { + throw new IllegalArgumentException(name + " is malformed"); + } + } + + private static void requireCluster(String value) { + if (value == null || !value.matches("[A-Za-z0-9][A-Za-z0-9._:-]{0,127}")) { + throw new IllegalArgumentException("cluster ID is malformed"); + } + } + + private static void requireRevision(String value, String name) { + if (value == null || !value.matches("[A-Za-z0-9][A-Za-z0-9._:-]{0,127}")) { + throw new IllegalArgumentException(name + " is malformed"); + } + } + + private static String sha256(String value) { + try { + return HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256") + .digest(value.getBytes(StandardCharsets.US_ASCII))); + } catch (NoSuchAlgorithmException failure) { + throw new IllegalStateException("SHA-256 is unavailable", failure); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtValidatorInventorySource.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtValidatorInventorySource.java new file mode 100644 index 0000000000..a2a5d47715 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtValidatorInventorySource.java @@ -0,0 +1,1290 @@ +package net.firedevops.firemud.accountservice.service.session; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.net.URI; +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.time.Clock; +import java.time.Instant; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.accountservice.config.AccountJwtJwksApiBinding; +import net.firedevops.firemud.accountservice.config.AccountJwtJwksApiBinding.ApiOperation; +import net.firedevops.firemud.accountservice.config.AccountJwtJwksApiBinding.ApiResponse; +import net.firedevops.firemud.accountservice.config.AccountJwtJwksApiBinding.ParsedBinding; +import net.firedevops.firemud.accountservice.config.AccountJwtValidatorInventoryBinding; +import net.firedevops.firemud.accountservice.config.AccountJwtValidatorInventoryBinding.ProfileExpectation; +import net.firedevops.firemud.accountservice.config.AccountJwtValidatorInventoryBinding.ProtectedInventory; +import net.firedevops.firemud.accountservice.config.AccountJwtValidatorInventoryBinding.ReceiverPodPin; +import net.firedevops.firemud.accountservice.config.AccountJwtValidatorInventoryBinding.ValidatorExpectation; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; + +/** + * Default-inactive reader for one protected expected validator inventory and its live Kubernetes + * Deployment/Pod observations. The snapshot is non-authorizing evidence only; it does not prove + * per-Pod token acceptance, readiness completeness, promotion eligibility, or convergence. + */ +public final class AccountJwtValidatorInventorySource { + private static final int MAX_PAGES = 16; + private static final int MAX_PODS_PER_VALIDATOR = 128; + private static final int MAX_CANONICAL_SNAPSHOT_BYTES = 4 * 1024 * 1024; + private static final String INVENTORY_DOMAIN = "firemud-account-validator-inventory/v2"; + private static final String SELF_REVIEW_REQUEST = + "{\"apiVersion\":\"authentication.k8s.io/v1\",\"kind\":\"SelfSubjectReview\",\"spec\":{}}"; + private static final String RUNTIME_CONFIG_ENV = "FIREMUD_JWT_VERIFIER_CONFIG"; + private static final Pattern UID = + Pattern.compile("[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}"); + private static final Pattern RESOURCE_VERSION = Pattern.compile("[!-~]{1,256}"); + private static final Pattern IMAGE_DIGEST = Pattern.compile("sha256:[0-9a-f]{64}"); + private static final Pattern OPERATION_DIGEST = Pattern.compile("[0-9a-f]{64}"); + private static final Pattern POD_TEMPLATE_HASH = Pattern.compile("[a-z0-9]{5,20}"); + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + private final AccountJwtJwksApiBinding apiBinding; + private final AccountJwtValidatorInventoryBinding inventoryBinding; + private final Clock clock; + + /** No Spring stereotype or automatic activation is provided. */ + public AccountJwtValidatorInventorySource( + AccountJwtJwksApiBinding apiBinding, + AccountJwtValidatorInventoryBinding inventoryBinding, + Clock clock) { + this.apiBinding = + Objects.requireNonNull(apiBinding, "protected Kubernetes API binding is required"); + this.inventoryBinding = + Objects.requireNonNull( + inventoryBinding, "protected validator inventory binding is required"); + this.clock = Objects.requireNonNull(clock, "clock is required"); + } + + /** + * Produces a fresh immutable observation. Any unavailable, changed, partial, ambiguous, legacy, + * or unpinned state is returned as one redacted failure; no Kubernetes response body is retained. + */ + public InventorySnapshot observe() { + return observeInternal(null); + } + + /** + * Produces an observation bound to an Account-selected durable generation operation. Only an + * initial operation with no durable or published active signer may enumerate non-ready Running + * Pods as candidates; those candidates still require the existing authenticated per-Pod probes + * before they can satisfy a promotion proof. + */ + public InventorySnapshot observe(ObservationContext observationContext) { + return observeInternal(Objects.requireNonNull(observationContext)); + } + + private InventorySnapshot observeInternal(ObservationContext observationContext) { + ProtectedInventory expected = + inventoryBinding.current().orElseThrow(InventoryUnavailableException::new); + boolean requireOrdinaryReady = + observationContext == null || observationContext.purpose().requiresOrdinaryReady(); + try (ApiOperation operation = apiBinding.beginOperation()) { + ParsedBinding api = operation.binding(); + if (!expected.matchesApiBinding(api)) { + throw new InventoryUnavailableException(); + } + verifyApiIdentity(operation, expected); + List observations = new ArrayList<>(); + for (ValidatorExpectation validator : expected.validators()) { + DeploymentObservation beforeDeployment = + readDeployment(operation, expected, validator, requireOrdinaryReady); + List beforePods = + readPods(operation, expected, validator, beforeDeployment, requireOrdinaryReady); + List beforeReplicaSets = + readReplicaSets( + operation, expected, validator, beforeDeployment, beforePods, requireOrdinaryReady); + DeploymentObservation afterDeployment = + readDeployment(operation, expected, validator, requireOrdinaryReady); + List afterPods = + readPods(operation, expected, validator, afterDeployment, requireOrdinaryReady); + List afterReplicaSets = + readReplicaSets( + operation, expected, validator, afterDeployment, afterPods, requireOrdinaryReady); + if (!beforeDeployment.equals(afterDeployment) + || !beforePods.equals(afterPods) + || !beforeReplicaSets.equals(afterReplicaSets)) { + throw new InventoryUnavailableException(); + } + observations.add( + new ValidatorObservation( + validator.validatorId(), + beforeDeployment.name(), + beforeDeployment.uid(), + beforeDeployment.generation(), + beforeDeployment.resourceVersion(), + beforeDeployment.replicas(), + beforeDeployment.image(), + beforeDeployment.verifierConfigSha256(), + validator.maxCacheAgeSeconds(), + validator.profiles(), + beforePods, + beforeReplicaSets)); + } + verifyApiIdentity(operation, expected); + ProtectedInventory afterExpected = + inventoryBinding.current().orElseThrow(InventoryUnavailableException::new); + if (!expected.bindingDigest().equals(afterExpected.bindingDigest()) + || !expected.configRevision().equals(afterExpected.configRevision())) { + throw new InventoryUnavailableException(); + } + Instant observedAt = clock.instant(); + if (observedAt == null || observedAt.isBefore(Instant.EPOCH)) { + throw new InventoryUnavailableException(); + } + return createSnapshot(expected, observations, observedAt, observationContext); + } catch (InventoryUnavailableException failure) { + throw failure; + } catch (RuntimeException failure) { + // Do not expose tokens, API bodies, file paths, parser details, or exception causes. + throw new InventoryUnavailableException(); + } + } + + private static void verifyApiIdentity(ApiOperation operation, ProtectedInventory expected) { + ParsedBinding binding = operation.binding(); + if (!expected.matchesApiBinding(binding)) { + throw new InventoryUnavailableException(); + } + ApiResponse selfReview = + operation.send( + AccountJwtJwksApiBinding.ApiCall.REVIEW_AUTHENTICATED_PRINCIPAL, + SELF_REVIEW_REQUEST.getBytes(StandardCharsets.UTF_8)); + if (selfReview.statusCode() != 200 && selfReview.statusCode() != 201) { + throw new InventoryUnavailableException(); + } + JsonNode review = parseJson(selfReview.body()); + JsonNode status = review.get("status"); + JsonNode userInfo = status == null ? null : status.get("userInfo"); + JsonNode username = userInfo == null ? null : userInfo.get("username"); + JsonNode evaluationError = status == null ? null : status.get("evaluationError"); + if (!"authentication.k8s.io/v1".equals(text(review.get("apiVersion"))) + || !"SelfSubjectReview".equals(text(review.get("kind"))) + || !binding.expectedApiUsername().equals(text(username)) + || (evaluationError != null + && !evaluationError.isNull() + && (!evaluationError.isTextual() || !evaluationError.asText().isEmpty()))) { + throw new InventoryUnavailableException(); + } + verifyNamespace( + operation.send(AccountJwtJwksApiBinding.ApiCall.READ_KUBE_SYSTEM_NAMESPACE, null), + "kube-system", + expected.expectedClusterIncarnationUid()); + verifyNamespace( + operation.send(AccountJwtJwksApiBinding.ApiCall.READ_TARGET_NAMESPACE, null), + expected.namespace(), + expected.expectedNamespaceUid()); + } + + private static void verifyNamespace(ApiResponse response, String name, String expectedUid) { + if (response.statusCode() != 200) { + throw new InventoryUnavailableException(); + } + JsonNode root = parseJson(response.body()); + JsonNode metadata = root.get("metadata"); + JsonNode status = root.get("status"); + if (!"v1".equals(text(root.get("apiVersion"))) + || !"Namespace".equals(text(root.get("kind"))) + || metadata == null + || !name.equals(text(metadata.get("name"))) + || !expectedUid.equals(canonicalUid(text(metadata.get("uid")))) + || metadata.hasNonNull("deletionTimestamp") + || status == null + || !"Active".equals(text(status.get("phase")))) { + throw new InventoryUnavailableException(); + } + } + + private static DeploymentObservation readDeployment( + ApiOperation operation, + ProtectedInventory inventory, + ValidatorExpectation expected, + boolean requireOrdinaryReady) { + ApiResponse response = operation.readValidatorDeployment(inventory, expected); + if (response.statusCode() != 200) { + throw new InventoryUnavailableException(); + } + JsonNode root = parseJson(response.body()); + JsonNode metadata = root.get("metadata"); + JsonNode spec = root.get("spec"); + JsonNode status = root.get("status"); + JsonNode selector = spec == null ? null : spec.get("selector"); + JsonNode template = spec == null ? null : spec.get("template"); + JsonNode templateMetadata = template == null ? null : template.get("metadata"); + JsonNode templateSpec = template == null ? null : template.get("spec"); + if (!"apps/v1".equals(text(root.get("apiVersion"))) + || !"Deployment".equals(text(root.get("kind"))) + || metadata == null + || !expected.deploymentName().equals(text(metadata.get("name"))) + || !inventory.namespace().equals(text(metadata.get("namespace"))) + || !expected.deploymentUid().equals(canonicalUid(text(metadata.get("uid")))) + || metadata.hasNonNull("deletionTimestamp") + || spec == null + || status == null + || selector == null + || !selectorMatches(selector.get("matchLabels"), expected.selector()) + || (selector.has("matchExpressions") + && selector.get("matchExpressions") != null + && !selector.get("matchExpressions").isNull() + && (!selector.get("matchExpressions").isArray() + || !selector.get("matchExpressions").isEmpty())) + || templateMetadata == null + || !labelsMatch(templateMetadata.get("labels"), expected.selector()) + || templateSpec == null) { + throw new InventoryUnavailableException(); + } + String resourceVersion = resourceVersion(text(metadata.get("resourceVersion"))); + long generation = positiveLong(metadata.get("generation")); + int replicas = exactInt(spec.get("replicas"), 1, 128); + int readyReplicas = observedReplicaCount(status, "readyReplicas", !requireOrdinaryReady); + int updatedReplicas = exactInt(status.get("updatedReplicas"), 0, 128); + int availableReplicas = + observedReplicaCount(status, "availableReplicas", !requireOrdinaryReady); + int unavailableReplicas = + status.has("unavailableReplicas") && !status.get("unavailableReplicas").isNull() + ? exactInt(status.get("unavailableReplicas"), 0, 128) + : 0; + if (replicas != expected.replicas() + || positiveLong(status.get("observedGeneration")) != generation + || readyReplicas > replicas + || updatedReplicas != replicas + || availableReplicas > readyReplicas + || unavailableReplicas > replicas + || (requireOrdinaryReady + && (readyReplicas != replicas + || availableReplicas != replicas + || unavailableReplicas != 0))) { + throw new InventoryUnavailableException(); + } + ContainerConfig container = + findVerifiedContainer( + templateSpec.get("containers"), expected, templateSpec.get("volumes")); + return new DeploymentObservation( + expected.deploymentName(), + expected.deploymentUid(), + resourceVersion, + generation, + replicas, + readyReplicas, + availableReplicas, + container.image(), + container.runtimeConfigSha256()); + } + + private static int observedReplicaCount( + JsonNode status, String fieldName, boolean allowOmittedZero) { + if (!status.has(fieldName)) { + if (allowOmittedZero) { + // Kubernetes omits zero-valued optional status replica counts. This is safe only for the + // owner-bound initial candidate observation; strict readiness still requires both fields. + return 0; + } + throw new InventoryUnavailableException(); + } + return exactInt(status.get(fieldName), 0, 128); + } + + private static List readPods( + ApiOperation operation, + ProtectedInventory inventory, + ValidatorExpectation expected, + DeploymentObservation deployment, + boolean requireOrdinaryReady) { + String continuation = null; + String listResourceVersion = null; + int pageCount = 0; + List pods = new ArrayList<>(); + Set podUids = new LinkedHashSet<>(); + Set podNames = new LinkedHashSet<>(); + do { + if (++pageCount > MAX_PAGES) { + throw new InventoryUnavailableException(); + } + ApiResponse response = operation.listValidatorPods(inventory, expected, continuation); + if (response.statusCode() != 200) { + throw new InventoryUnavailableException(); + } + JsonNode root = parseJson(response.body()); + JsonNode metadata = root.get("metadata"); + JsonNode items = root.get("items"); + if (!"v1".equals(text(root.get("apiVersion"))) + || !"PodList".equals(text(root.get("kind"))) + || metadata == null + || items == null + || !items.isArray()) { + throw new InventoryUnavailableException(); + } + String pageVersion = resourceVersion(text(metadata.get("resourceVersion"))); + if (listResourceVersion == null) { + listResourceVersion = pageVersion; + } else if (!listResourceVersion.equals(pageVersion)) { + throw new InventoryUnavailableException(); + } + for (JsonNode item : items) { + if (pods.size() >= MAX_PODS_PER_VALIDATOR) { + throw new InventoryUnavailableException(); + } + PodObservation pod = + parsePod(item, inventory.namespace(), expected, deployment, requireOrdinaryReady); + if (!podUids.add(pod.uid()) || !podNames.add(pod.name())) { + throw new InventoryUnavailableException(); + } + pods.add(pod); + } + JsonNode continueNode = metadata.get("continue"); + if (continueNode == null || continueNode.isNull() || !continueNode.isTextual()) { + continuation = null; + } else { + continuation = continueNode.asText(); + if (continuation.isEmpty()) { + continuation = null; + } else if (continuation.length() > 2048) { + throw new InventoryUnavailableException(); + } + } + } while (continuation != null); + if (pods.size() != expected.replicas()) { + throw new InventoryUnavailableException(); + } + pods.sort(Comparator.comparing(PodObservation::uid)); + List observedPodUids = pods.stream().map(PodObservation::uid).toList(); + List protectedPodUids = + expected.receiverPods().stream().map(ReceiverPodPin::podUid).sorted().toList(); + if (!observedPodUids.equals(protectedPodUids)) { + throw new InventoryUnavailableException(); + } + return List.copyOf(pods); + } + + private static PodObservation parsePod( + JsonNode pod, + String namespace, + ValidatorExpectation expected, + DeploymentObservation deployment, + boolean requireOrdinaryReady) { + if (pod == null || pod.isNull()) { + throw new InventoryUnavailableException(); + } + JsonNode metadata = pod.get("metadata"); + JsonNode spec = pod.get("spec"); + JsonNode status = pod.get("status"); + if (!"v1".equals(text(pod.get("apiVersion"))) + || !"Pod".equals(text(pod.get("kind"))) + || metadata == null + || spec == null + || status == null + || !namespace.equals(text(metadata.get("namespace"))) + || metadata.hasNonNull("deletionTimestamp") + || !labelsMatch(metadata.get("labels"), expected.selector()) + || !"Running".equals(text(status.get("phase")))) { + throw new InventoryUnavailableException(); + } + String name = dnsLabel(text(metadata.get("name"))); + String uid = canonicalUid(text(metadata.get("uid"))); + String podIp = canonicalPodIp(text(status.get("podIP"))); + ReceiverPodPin receiverPin = + expected.receiverPods().stream() + .filter(pin -> pin.podUid().equals(uid)) + .findFirst() + .orElseThrow(InventoryUnavailableException::new); + if (!receiverPin.podIp().equals(podIp)) { + throw new InventoryUnavailableException(); + } + String resourceVersion = resourceVersion(text(metadata.get("resourceVersion"))); + String templateHash = podTemplateHash(metadata.get("labels")); + JsonNode owners = metadata.get("ownerReferences"); + if (owners == null || !owners.isArray() || owners.size() != 1) { + throw new InventoryUnavailableException(); + } + JsonNode owner = owners.get(0); + if (!"apps/v1".equals(text(owner.get("apiVersion"))) + || !"ReplicaSet".equals(text(owner.get("kind"))) + || !Boolean.TRUE.equals(booleanValue(owner.get("controller")))) { + throw new InventoryUnavailableException(); + } + String ownerName = dnsLabel(text(owner.get("name"))); + String ownerUid = canonicalUid(text(owner.get("uid"))); + ContainerConfig container = + findVerifiedContainer(spec.get("containers"), expected, spec.get("volumes")); + if (!deployment.image().equals(container.image()) + || !deployment.verifierConfigSha256().equals(container.runtimeConfigSha256())) { + throw new InventoryUnavailableException(); + } + verifyReadyCondition(status.get("conditions"), requireOrdinaryReady); + verifyContainerReady( + status.get("containerStatuses"), expected, deployment.image(), requireOrdinaryReady); + return new PodObservation( + name, + uid, + resourceVersion, + ownerName, + ownerUid, + templateHash, + deployment.image(), + deployment.verifierConfigSha256(), + podIp, + podEndpoint(podIp, expected.receiverPort()), + expected.receiverServiceUri(), + receiverPin.leafSpkiSha256()); + } + + private static List readReplicaSets( + ApiOperation operation, + ProtectedInventory inventory, + ValidatorExpectation expected, + DeploymentObservation deployment, + List pods, + boolean requireOrdinaryReady) { + Map observedOwners = new LinkedHashMap<>(); + Map templateHashes = new LinkedHashMap<>(); + for (PodObservation pod : pods) { + String prior = observedOwners.putIfAbsent(pod.ownerName(), pod.ownerUid()); + String priorHash = templateHashes.putIfAbsent(pod.ownerName(), pod.podTemplateHash()); + if ((prior != null && !prior.equals(pod.ownerUid())) + || (priorHash != null && !priorHash.equals(pod.podTemplateHash()))) { + throw new InventoryUnavailableException(); + } + } + List observations = new ArrayList<>(observedOwners.size()); + for (Map.Entry owner : observedOwners.entrySet()) { + ApiResponse response = operation.readValidatorReplicaSet(inventory, expected, owner.getKey()); + if (response.statusCode() != 200) { + throw new InventoryUnavailableException(); + } + observations.add( + parseReplicaSet( + response.body(), + inventory.namespace(), + expected, + deployment, + owner.getKey(), + owner.getValue(), + templateHashes.get(owner.getKey()), + requireOrdinaryReady)); + } + observations.sort(Comparator.comparing(ReplicaSetObservation::uid)); + return List.copyOf(observations); + } + + private static ReplicaSetObservation parseReplicaSet( + byte[] responseBody, + String namespace, + ValidatorExpectation expected, + DeploymentObservation deployment, + String expectedName, + String expectedUid, + String expectedTemplateHash, + boolean requireOrdinaryReady) { + JsonNode root = parseJson(responseBody); + JsonNode metadata = root.get("metadata"); + JsonNode spec = root.get("spec"); + JsonNode status = root.get("status"); + JsonNode owners = metadata == null ? null : metadata.get("ownerReferences"); + JsonNode selector = spec == null ? null : spec.get("selector"); + JsonNode template = spec == null ? null : spec.get("template"); + JsonNode templateMetadata = template == null ? null : template.get("metadata"); + JsonNode templateSpec = template == null ? null : template.get("spec"); + if (!"apps/v1".equals(text(root.get("apiVersion"))) + || !"ReplicaSet".equals(text(root.get("kind"))) + || metadata == null + || !expectedName.equals(text(metadata.get("name"))) + || !namespace.equals(text(metadata.get("namespace"))) + || !expectedUid.equals(canonicalUid(text(metadata.get("uid")))) + || metadata.hasNonNull("deletionTimestamp") + || owners == null + || !owners.isArray() + || owners.size() != 1 + || spec == null + || status == null + || selector == null + || !replicaSetSelectorMatches( + selector.get("matchLabels"), expected.selector(), expectedTemplateHash) + || (selector.has("matchExpressions") + && selector.get("matchExpressions") != null + && !selector.get("matchExpressions").isNull() + && (!selector.get("matchExpressions").isArray() + || !selector.get("matchExpressions").isEmpty())) + || templateMetadata == null + || !labelsMatch(templateMetadata.get("labels"), expected.selector()) + || !expectedTemplateHash.equals( + text(templateMetadata.get("labels").get("pod-template-hash"))) + || templateSpec == null) { + throw new InventoryUnavailableException(); + } + JsonNode owner = owners.get(0); + if (!"apps/v1".equals(text(owner.get("apiVersion"))) + || !"Deployment".equals(text(owner.get("kind"))) + || !deployment.name().equals(text(owner.get("name"))) + || !deployment.uid().equals(canonicalUid(text(owner.get("uid")))) + || !Boolean.TRUE.equals(booleanValue(owner.get("controller")))) { + throw new InventoryUnavailableException(); + } + String resourceVersion = resourceVersion(text(metadata.get("resourceVersion"))); + long generation = positiveLong(metadata.get("generation")); + int replicas = exactInt(spec.get("replicas"), 1, 128); + int readyReplicas = observedReplicaCount(status, "readyReplicas", !requireOrdinaryReady); + if (positiveLong(status.get("observedGeneration")) != generation + || readyReplicas > replicas + || replicas != expected.replicas() + || (requireOrdinaryReady && readyReplicas != replicas)) { + throw new InventoryUnavailableException(); + } + ContainerConfig container = + findVerifiedContainer( + templateSpec.get("containers"), expected, templateSpec.get("volumes")); + if (!deployment.image().equals(container.image()) + || !deployment.verifierConfigSha256().equals(container.runtimeConfigSha256())) { + throw new InventoryUnavailableException(); + } + return new ReplicaSetObservation( + expectedName, + expectedUid, + resourceVersion, + generation, + replicas, + deployment.name(), + deployment.uid(), + expectedTemplateHash, + container.image(), + container.runtimeConfigSha256()); + } + + private static boolean replicaSetSelectorMatches( + JsonNode actual, Map expected, String expectedTemplateHash) { + if (actual == null + || !actual.isObject() + || expectedTemplateHash == null + || actual.size() != expected.size() + 1 + || !expectedTemplateHash.equals(text(actual.get("pod-template-hash")))) { + return false; + } + for (Map.Entry entry : expected.entrySet()) { + if (!entry.getValue().equals(text(actual.get(entry.getKey())))) { + return false; + } + } + return true; + } + + private static String podTemplateHash(JsonNode labels) { + if (labels == null || !labels.isObject()) { + throw new InventoryUnavailableException(); + } + String value = text(labels.get("pod-template-hash")); + if (value == null || !POD_TEMPLATE_HASH.matcher(value).matches()) { + throw new InventoryUnavailableException(); + } + return value; + } + + private static ContainerConfig findVerifiedContainer( + JsonNode containers, ValidatorExpectation expected, JsonNode volumes) { + if (containers == null + || !containers.isArray() + || containers.isEmpty() + || containers.size() > 32) { + throw new InventoryUnavailableException(); + } + JsonNode selected = null; + for (JsonNode container : containers) { + String name = text(container.get("name")); + rejectSigningMaterialEnvironment(container.get("env")); + rejectSigningSecretMounts(container.get("volumeMounts")); + if (expected.containerName().equals(name)) { + if (selected != null) { + throw new InventoryUnavailableException(); + } + selected = container; + } + } + rejectSigningSecretVolumes(volumes); + if (selected == null || !expected.image().equals(text(selected.get("image")))) { + throw new InventoryUnavailableException(); + } + JsonNode env = selected.get("env"); + JsonNode configNode = null; + Set environmentNames = new LinkedHashSet<>(); + if (env != null && !env.isNull()) { + if (!env.isArray() || env.size() > 256) { + throw new InventoryUnavailableException(); + } + for (JsonNode variable : env) { + String envName = text(variable.get("name")); + if (envName == null || !environmentNames.add(envName)) { + throw new InventoryUnavailableException(); + } + if (RUNTIME_CONFIG_ENV.equals(envName)) { + if (variable.has("valueFrom") + || !expected.canonicalRuntimeConfig().equals(text(variable.get("value")))) { + throw new InventoryUnavailableException(); + } + configNode = variable; + } + if ("SPRING_APPLICATION_JSON".equals(envName) + || "JAVA_TOOL_OPTIONS".equals(envName) + || "JDK_JAVA_OPTIONS".equals(envName)) { + throw new InventoryUnavailableException(); + } + } + } + if (configNode == null) { + throw new InventoryUnavailableException(); + } + return new ContainerConfig( + expected.image(), + sha256(expected.canonicalRuntimeConfig().getBytes(StandardCharsets.UTF_8))); + } + + private static void rejectSigningMaterialEnvironment(JsonNode env) { + if (env == null || env.isNull()) { + return; + } + if (!env.isArray()) { + throw new InventoryUnavailableException(); + } + for (JsonNode variable : env) { + String name = text(variable.get("name")); + if (name != null + && (name.equals("FIREMUD_AUTH_JWT_SECRET") + || name.equals("FIREMUD_AUTH_JWT_SECRET_PATH") + || name.contains("JWT_HMAC") + || name.contains("JWT_SIGNING_KEY"))) { + throw new InventoryUnavailableException(); + } + JsonNode valueFrom = variable.get("valueFrom"); + JsonNode secretKeyRef = valueFrom == null ? null : valueFrom.get("secretKeyRef"); + if (secretKeyRef != null && !secretKeyRef.isNull()) { + String secretName = text(secretKeyRef.get("name")); + if ("jwt-signing-keys".equals(secretName)) { + throw new InventoryUnavailableException(); + } + } + } + } + + private static void rejectSigningSecretMounts(JsonNode mounts) { + if (mounts == null || mounts.isNull()) { + return; + } + if (!mounts.isArray()) { + throw new InventoryUnavailableException(); + } + for (JsonNode mount : mounts) { + String name = text(mount.get("name")); + String path = text(mount.get("mountPath")); + if ("jwt-signing-keys".equals(name) + || (path != null && path.startsWith("/var/run/secrets/firemud/jwt"))) { + throw new InventoryUnavailableException(); + } + } + } + + private static void rejectSigningSecretVolumes(JsonNode volumes) { + if (volumes == null || volumes.isNull()) { + return; + } + if (!volumes.isArray()) { + throw new InventoryUnavailableException(); + } + for (JsonNode volume : volumes) { + String name = text(volume.get("name")); + JsonNode secret = volume.get("secret"); + if ("jwt-signing-keys".equals(name) + || (secret != null + && !secret.isNull() + && "jwt-signing-keys".equals(text(secret.get("secretName"))))) { + throw new InventoryUnavailableException(); + } + } + } + + private static void verifyReadyCondition(JsonNode conditions, boolean requireOrdinaryReady) { + if (conditions == null || !conditions.isArray() || conditions.size() > 64) { + throw new InventoryUnavailableException(); + } + boolean ready = false; + for (JsonNode condition : conditions) { + if ("Ready".equals(text(condition.get("type")))) { + String status = text(condition.get("status")); + if (ready || (!"True".equals(status) && !"False".equals(status))) { + throw new InventoryUnavailableException(); + } + if (requireOrdinaryReady && !"True".equals(status)) { + throw new InventoryUnavailableException(); + } + ready = true; + } + } + if (!ready) { + throw new InventoryUnavailableException(); + } + } + + private static void verifyContainerReady( + JsonNode statuses, + ValidatorExpectation expected, + String expectedImage, + boolean requireOrdinaryReady) { + if (statuses == null || !statuses.isArray() || statuses.isEmpty() || statuses.size() > 32) { + throw new InventoryUnavailableException(); + } + JsonNode found = null; + for (JsonNode status : statuses) { + if (expected.containerName().equals(text(status.get("name")))) { + if (found != null) { + throw new InventoryUnavailableException(); + } + found = status; + } + } + String imageId = found == null ? null : text(found.get("imageID")); + String digest = imageDigest(imageId); + String expectedDigest = expected.image().substring(expected.image().lastIndexOf('@') + 1); + Boolean ready = found == null ? null : booleanValue(found.get("ready")); + if (found == null + || ready == null + || (requireOrdinaryReady && !ready) + || !expectedDigest.equals(digest)) { + throw new InventoryUnavailableException(); + } + } + + private static InventorySnapshot createSnapshot( + ProtectedInventory expected, + List validators, + Instant observedAt, + ObservationContext observationContext) { + List sorted = + validators.stream() + .sorted(Comparator.comparing(ValidatorObservation::validatorId)) + .toList(); + Map preimage = new LinkedHashMap<>(); + preimage.put("domain", INVENTORY_DOMAIN); + // Acquisition time is independently bounded freshness metadata, not inventory content. The + // v2 digest must remain stable across an unchanged later reread while retaining this time in + // the immutable snapshot row and in the in-memory observation. + preimage.put("environmentId", expected.environmentId()); + preimage.put("clusterId", expected.clusterId()); + preimage.put("clusterIncarnationUid", expected.expectedClusterIncarnationUid()); + preimage.put("namespace", expected.namespace()); + preimage.put("namespaceUid", expected.expectedNamespaceUid()); + preimage.put("apiBindingRevision", expected.apiBindingRevision()); + preimage.put("apiBindingDigest", expected.apiBindingDigest()); + preimage.put("inventoryBindingRevision", expected.configRevision()); + preimage.put("inventoryBindingDigest", expected.bindingDigest()); + if (observationContext != null) { + preimage.put("observationContext", observationContext.canonicalMap()); + } + preimage.put( + "validators", + sorted.stream().map(AccountJwtValidatorInventorySource::validatorMap).toList()); + byte[] canonicalSnapshot = canonicalBytes(preimage); + if (canonicalSnapshot.length > MAX_CANONICAL_SNAPSHOT_BYTES) { + throw new InventoryUnavailableException(); + } + String digest = sha256(canonicalSnapshot); + return new InventorySnapshot( + observedAt, + expected.environmentId(), + expected.clusterId(), + expected.expectedClusterIncarnationUid(), + expected.namespace(), + expected.expectedNamespaceUid(), + expected.apiBindingRevision(), + expected.apiBindingDigest(), + expected.configRevision(), + expected.bindingDigest(), + sorted, + Optional.ofNullable(observationContext), + canonicalSnapshot, + digest); + } + + private static Map validatorMap(ValidatorObservation validator) { + Map result = new LinkedHashMap<>(); + result.put("validatorId", validator.validatorId()); + result.put("deploymentName", validator.deploymentName()); + result.put("deploymentUid", validator.deploymentUid()); + result.put("deploymentGeneration", Long.toString(validator.deploymentGeneration())); + result.put("deploymentResourceVersion", validator.deploymentResourceVersion()); + result.put("replicas", Integer.toString(validator.replicas())); + result.put("image", validator.image()); + result.put("verifierConfigSha256", validator.verifierConfigSha256()); + result.put("maxCacheAgeSeconds", Integer.toString(validator.maxCacheAgeSeconds())); + result.put( + "profiles", + validator.profiles().stream() + .map( + profile -> + Map.of("tokenProfile", profile.tokenProfile(), "audience", profile.audience())) + .toList()); + result.put( + "pods", validator.pods().stream().map(AccountJwtValidatorInventorySource::podMap).toList()); + result.put("receiverServiceUri", validator.pods().getFirst().receiverServiceUri()); + result.put("receiverPort", validator.pods().getFirst().endpoint().getPort()); + result.put( + "replicaSets", + validator.replicaSets().stream() + .map(AccountJwtValidatorInventorySource::replicaSetMap) + .toList()); + return result; + } + + private static Map replicaSetMap(ReplicaSetObservation replicaSet) { + return Map.of( + "name", replicaSet.name(), + "uid", replicaSet.uid(), + "resourceVersion", replicaSet.resourceVersion(), + "generation", Long.toString(replicaSet.generation()), + "replicas", Integer.toString(replicaSet.replicas()), + "ownerDeploymentName", replicaSet.ownerDeploymentName(), + "ownerDeploymentUid", replicaSet.ownerDeploymentUid(), + "podTemplateHash", replicaSet.podTemplateHash(), + "image", replicaSet.image(), + "verifierConfigSha256", replicaSet.verifierConfigSha256()); + } + + private static Map podMap(PodObservation pod) { + return Map.ofEntries( + Map.entry("name", pod.name()), + Map.entry("uid", pod.uid()), + Map.entry("resourceVersion", pod.resourceVersion()), + Map.entry("ownerReplicaSetName", pod.ownerName()), + Map.entry("ownerReplicaSetUid", pod.ownerUid()), + Map.entry("podTemplateHash", pod.podTemplateHash()), + Map.entry("image", pod.image()), + Map.entry("verifierConfigSha256", pod.verifierConfigSha256()), + Map.entry("podIp", pod.podIp()), + Map.entry("exactPodEndpoint", pod.endpoint().toString()), + Map.entry("canonicalServiceUri", pod.receiverServiceUri()), + Map.entry("leafSpkiSha256", pod.leafSpkiSha256())); + } + + private static URI podEndpoint(String podIp, int port) { + String host = podIp.indexOf(':') >= 0 ? "[" + podIp + "]" : podIp; + return URI.create("grpcs://" + host + ":" + port); + } + + private static String canonicalPodIp(String value) { + try { + return AccountJwtValidatorInventoryBinding.canonicalPodIp(value); + } catch (RuntimeException failure) { + throw new InventoryUnavailableException(); + } + } + + private static boolean selectorMatches(JsonNode actual, Map expected) { + if (actual == null || !actual.isObject() || actual.size() != expected.size()) { + return false; + } + return labelsMatch(actual, expected); + } + + private static boolean labelsMatch(JsonNode labels, Map expected) { + if (labels == null || !labels.isObject()) { + return false; + } + for (Map.Entry entry : expected.entrySet()) { + if (!entry.getValue().equals(text(labels.get(entry.getKey())))) { + return false; + } + } + return true; + } + + private static JsonNode parseJson(byte[] bytes) { + if (bytes == null || bytes.length == 0 || bytes.length > 1024 * 1024) { + throw new InventoryUnavailableException(); + } + try { + JsonNode parsed = JSON.readTree(decodeUtf8(bytes)); + if (parsed == null || !parsed.isObject()) { + throw new InventoryUnavailableException(); + } + return parsed; + } catch (InventoryUnavailableException failure) { + throw failure; + } catch (Exception failure) { + throw new InventoryUnavailableException(); + } + } + + private static byte[] canonicalBytes(Object value) { + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } catch (Exception failure) { + throw new InventoryUnavailableException(); + } + } + + private static String imageDigest(String imageId) { + if (imageId == null) { + throw new InventoryUnavailableException(); + } + int marker = imageId.lastIndexOf("sha256:"); + if (marker < 0) { + throw new InventoryUnavailableException(); + } + String digest = imageId.substring(marker); + if (!IMAGE_DIGEST.matcher(digest).matches()) { + throw new InventoryUnavailableException(); + } + return digest; + } + + private static String canonicalUid(String value) { + if (value == null || !UID.matcher(value).matches() || value.startsWith("00000000-")) { + throw new InventoryUnavailableException(); + } + return value; + } + + private static String resourceVersion(String value) { + if (value == null || !RESOURCE_VERSION.matcher(value).matches()) { + throw new InventoryUnavailableException(); + } + return value; + } + + private static String dnsLabel(String value) { + if (value == null || !value.matches("[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?")) { + throw new InventoryUnavailableException(); + } + return value; + } + + private static long positiveLong(JsonNode node) { + long value = exactLong(node, 1L, Long.MAX_VALUE); + return value; + } + + private static int exactInt(JsonNode node, int minimum, int maximum) { + if (node == null || !node.isIntegralNumber() || !node.canConvertToLong()) { + throw new InventoryUnavailableException(); + } + long value = node.longValue(); + if (value < minimum || value > maximum) { + throw new InventoryUnavailableException(); + } + return (int) value; + } + + private static long exactLong(JsonNode node, long minimum, long maximum) { + if (node == null || !node.isIntegralNumber() || !node.canConvertToLong()) { + throw new InventoryUnavailableException(); + } + long value = node.longValue(); + if (value < minimum || value > maximum) { + throw new InventoryUnavailableException(); + } + return value; + } + + @SuppressFBWarnings( + value = "NP_BOOLEAN_RETURN_NULL", + justification = + "The parser intentionally preserves absent or malformed booleans as unknown; callers require explicit true.") + private static Boolean booleanValue(JsonNode node) { + return node != null && node.isBoolean() ? node.booleanValue() : null; + } + + private static String text(JsonNode node) { + return node != null && node.isTextual() && !node.asText().isEmpty() ? node.asText() : null; + } + + private static String decodeUtf8(byte[] bytes) { + try { + return StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(bytes)) + .toString(); + } catch (CharacterCodingException failure) { + throw new InventoryUnavailableException(); + } + } + + private static String sha256(byte[] bytes) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (Exception failure) { + throw new InventoryUnavailableException(); + } + } + + private record ContainerConfig(String image, String runtimeConfigSha256) {} + + private record DeploymentObservation( + String name, + String uid, + String resourceVersion, + long generation, + int replicas, + int readyReplicas, + int availableReplicas, + String image, + String verifierConfigSha256) {} + + public record ReplicaSetObservation( + String name, + String uid, + String resourceVersion, + long generation, + int replicas, + String ownerDeploymentName, + String ownerDeploymentUid, + String podTemplateHash, + String image, + String verifierConfigSha256) {} + + /** No Pod or Kubernetes API body is retained, only closed non-secret identity fields. */ + public record PodObservation( + String name, + String uid, + String resourceVersion, + String ownerName, + String ownerUid, + String podTemplateHash, + String image, + String verifierConfigSha256, + String podIp, + URI endpoint, + String receiverServiceUri, + String leafSpkiSha256) {} + + public record ValidatorObservation( + String validatorId, + String deploymentName, + String deploymentUid, + long deploymentGeneration, + String deploymentResourceVersion, + int replicas, + String image, + String verifierConfigSha256, + int maxCacheAgeSeconds, + List profiles, + List pods, + List replicaSets) { + public ValidatorObservation { + profiles = List.copyOf(profiles); + pods = List.copyOf(pods); + replicaSets = List.copyOf(replicaSets); + } + } + + /** + * Account-owner-derived context for one validator inventory acquisition. Bootstrap candidate + * observation is available only for the exact current operation whose active signer fence is + * absent; the repository re-derives and checks this context before consuming the snapshot. + */ + public record ObservationContext( + ObservationPurpose purpose, UUID operationId, String operationDigest) { + public ObservationContext { + Objects.requireNonNull(purpose, "Inventory observation purpose is required"); + Objects.requireNonNull(operationId, "Inventory observation operation is required"); + if (operationId.version() != 4 + || operationId.variant() != 2 + || operationDigest == null + || !OPERATION_DIGEST.matcher(operationDigest).matches()) { + throw new InventoryUnavailableException(); + } + } + + public boolean isInitialNoActiveSigner() { + return purpose == ObservationPurpose.INITIAL_NO_ACTIVE_SIGNER_CANDIDATES; + } + + private Map canonicalMap() { + return Map.of( + "purpose", purpose.name(), + "operationId", operationId.toString(), + "operationDigest", operationDigest); + } + } + + public enum ObservationPurpose { + STRICT_READY, + INITIAL_NO_ACTIVE_SIGNER_CANDIDATES; + + private boolean requiresOrdinaryReady() { + return this == STRICT_READY; + } + } + + public static final class InventorySnapshot { + private final Instant observedAt; + private final String environmentId; + private final String clusterId; + private final String clusterIncarnationUid; + private final String namespace; + private final String namespaceUid; + private final String apiBindingRevision; + private final String apiBindingDigest; + private final String inventoryBindingRevision; + private final String inventoryBindingDigest; + private final List validators; + private final Optional observationContext; + private final byte[] canonicalBytes; + private final String digest; + + private InventorySnapshot( + Instant observedAt, + String environmentId, + String clusterId, + String clusterIncarnationUid, + String namespace, + String namespaceUid, + String apiBindingRevision, + String apiBindingDigest, + String inventoryBindingRevision, + String inventoryBindingDigest, + List validators, + Optional observationContext, + byte[] canonicalBytes, + String digest) { + this.observedAt = Objects.requireNonNull(observedAt); + this.environmentId = Objects.requireNonNull(environmentId); + this.clusterId = Objects.requireNonNull(clusterId); + this.clusterIncarnationUid = Objects.requireNonNull(clusterIncarnationUid); + this.namespace = Objects.requireNonNull(namespace); + this.namespaceUid = Objects.requireNonNull(namespaceUid); + this.apiBindingRevision = Objects.requireNonNull(apiBindingRevision); + this.apiBindingDigest = Objects.requireNonNull(apiBindingDigest); + this.inventoryBindingRevision = Objects.requireNonNull(inventoryBindingRevision); + this.inventoryBindingDigest = Objects.requireNonNull(inventoryBindingDigest); + this.validators = List.copyOf(validators); + this.observationContext = Objects.requireNonNull(observationContext); + this.canonicalBytes = Objects.requireNonNull(canonicalBytes).clone(); + this.digest = Objects.requireNonNull(digest); + if (this.canonicalBytes.length == 0 + || this.canonicalBytes.length > MAX_CANONICAL_SNAPSHOT_BYTES + || !sha256(this.canonicalBytes).equals(digest)) { + throw new InventoryUnavailableException(); + } + } + + public Instant observedAt() { + return observedAt; + } + + public String environmentId() { + return environmentId; + } + + public String clusterId() { + return clusterId; + } + + public String clusterIncarnationUid() { + return clusterIncarnationUid; + } + + public String namespace() { + return namespace; + } + + public String namespaceUid() { + return namespaceUid; + } + + public String apiBindingRevision() { + return apiBindingRevision; + } + + public String apiBindingDigest() { + return apiBindingDigest; + } + + public String inventoryBindingRevision() { + return inventoryBindingRevision; + } + + public String inventoryBindingDigest() { + return inventoryBindingDigest; + } + + public List validators() { + return validators; + } + + public Optional observationContext() { + return observationContext; + } + + public byte[] canonicalBytes() { + return canonicalBytes.clone(); + } + + public String digest() { + return digest; + } + + @Override + public boolean equals(Object other) { + if (!(other instanceof InventorySnapshot that)) return false; + return observedAt.equals(that.observedAt) + && environmentId.equals(that.environmentId) + && clusterId.equals(that.clusterId) + && clusterIncarnationUid.equals(that.clusterIncarnationUid) + && namespace.equals(that.namespace) + && namespaceUid.equals(that.namespaceUid) + && apiBindingRevision.equals(that.apiBindingRevision) + && apiBindingDigest.equals(that.apiBindingDigest) + && inventoryBindingRevision.equals(that.inventoryBindingRevision) + && inventoryBindingDigest.equals(that.inventoryBindingDigest) + && validators.equals(that.validators) + && observationContext.equals(that.observationContext) + && java.util.Arrays.equals(canonicalBytes, that.canonicalBytes) + && digest.equals(that.digest); + } + + @Override + public int hashCode() { + return 31 + * Objects.hash( + observedAt, + environmentId, + clusterId, + clusterIncarnationUid, + namespace, + namespaceUid, + apiBindingRevision, + apiBindingDigest, + inventoryBindingRevision, + inventoryBindingDigest, + validators, + observationContext, + digest) + + java.util.Arrays.hashCode(canonicalBytes); + } + } + + public static final class InventoryUnavailableException extends RuntimeException { + public InventoryUnavailableException() { + super("Account validator inventory is unavailable or inconsistent"); + } + } +} 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 new file mode 100644 index 0000000000..2e1929da82 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountMountedJwtSignerBundle.java @@ -0,0 +1,1269 @@ +package net.firedevops.firemud.accountservice.service.session; + +import java.io.IOException; +import java.math.BigInteger; +import java.nio.ByteBuffer; +import java.nio.channels.SeekableByteChannel; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.LinkOption; +import java.nio.file.Path; +import java.nio.file.StandardOpenOption; +import java.security.GeneralSecurityException; +import java.security.KeyFactory; +import java.security.MessageDigest; +import java.security.PrivateKey; +import java.security.SecureRandom; +import java.security.Signature; +import java.security.interfaces.RSAPrivateCrtKey; +import java.security.interfaces.RSAPublicKey; +import java.security.spec.PKCS8EncodedKeySpec; +import java.security.spec.RSAPublicKeySpec; +import java.util.Arrays; +import java.util.Base64; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationPendingIdentity; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.security.ControlUiJwtProfileValidator; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationRegistryRecord.AccountAuthoritySnapshot; +import net.firedevops.firemud.common.security.PlayerBootstrapJwtProfileValidator; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; + +/** + * Bounded Account-local parser and correspondence proof for the interim mounted JWT signer. + * + *

This class exposes no general private-key operation or caller-facing token response. Its + * package-private signing operations are closed readiness probes and the exact Account-owned + * initial Game Session delegation candidate; compact bytes are delivered only to an owner callback + * and wiped after it returns. Local correspondence alone proves no lifecycle or authorization. + */ +public final class AccountMountedJwtSignerBundle { + public static final int MAX_PRIVATE_BUNDLE_BYTES = 64 * 1024; + public static final int MAX_PUBLIC_JWKS_BYTES = 256 * 1024; + private static final int MAX_READINESS_COMPACT_JWT_BYTES = 16 * 1024; + private static final int MAX_DELEGATION_COMPACT_JWT_BYTES = + GameSessionAccountDelegationProfile.MAX_COMPACT_JWT_BYTES; + private static final int MAX_RSA_BITS = 16_384; + private static final int MIN_RSA_BITS = 3_072; + private static final int MAX_JWKS_KEYS = 64; + private static final int MAX_PRIVATE_KEY_DER_BYTES = 16 * 1024; + private static final int CHALLENGE_NONCE_BYTES = 32; + private static final SecureRandom CHALLENGE_RANDOM = new SecureRandom(); + private static final String ALGORITHM = "RS256"; + static final String READINESS_CANARY_PROFILE = "account-jwt-readiness-canary"; + static final String READINESS_CANARY_TYPE = "account_jwt_readiness_canary"; + static final String READINESS_CANARY_AUDIENCE = "firemud-account-jwt-readiness"; + static final String READINESS_VALIDATOR_ID = "account-service"; + static final String REPRESENTATIVE_PROFILE = GameSessionAccountDelegationProfile.PROFILE; + static final String REPRESENTATIVE_AUDIENCE = GameSessionAccountDelegationProfile.AUDIENCE; + private static final String ISSUER = "firemud-account-service"; + private static final String RESERVED_SUBJECT = "00000000-0000-4000-8000-000000000001"; + private static final Pattern KID = Pattern.compile("[A-Za-z0-9_-]{1,64}"); + private static final Pattern GENERATION = Pattern.compile("[1-9][0-9]{0,63}"); + private static final Pattern FINGERPRINT = Pattern.compile("[0-9a-f]{64}"); + private static final Set PRIVATE_BUNDLE_FIELDS = + Set.of( + "version", + "environmentId", + "clusterId", + "namespace", + "operationId", + "generation", + "kid", + "algorithm", + "privateKeyPkcs8", + "publicKeyFingerprint"); + private static final Set JWKS_FIELDS = Set.of("keys"); + private static final Set JWK_FIELDS = + Set.of("kty", "use", "alg", "kid", "key_ops", "n", "e"); + private static final byte[] CHALLENGE_DOMAIN = + new byte[] { + 0, 'F', 'i', 'r', 'e', 'M', 'U', 'D', '/', 'A', 'c', 'c', 'o', 'u', 'n', 't', '/', 'm', 'o', + 'u', 'n', 't', 'e', 'd', '-', 's', 'i', 'g', 'n', 'e', 'r', '-', 'c', 'o', 'r', 'r', 'e', + 's', 'p', 'o', 'n', 'd', 'e', 'n', 'c', 'e', '/', 'v', '1', 0 + }; + private static final JsonMapper STRICT_JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + private AccountMountedJwtSignerBundle() {} + + /** + * Reads the explicitly configured Account-only private projection and public JWKS projection. + * Relative file paths must remain beneath their respective configured mount roots. Kubernetes + * projected-volume symlinks are accepted only when their resolved regular files stay beneath + * those roots. + */ + public static LocalObservation observeMounted( + Path privateMountRoot, + Path privateBundlePath, + Path publicMountRoot, + Path publicJwksPath, + ExpectedIdentity expectedIdentity) { + return readAndVerifyMounted( + privateMountRoot, privateBundlePath, publicMountRoot, publicJwksPath, expectedIdentity) + .observation(); + } + + /** + * Signs only one fixed non-authorizing canary or one fixed-shape representative profile, passes + * the exact compact bytes transiently to the Account-owned callback, then wipes them and returns + * only their digest plus immutable planned identity. This method is package-private so no route, + * ordinary issuer, or other service can request arbitrary JWT signing from the mounted pending + * key. + */ + static SignedProbeDigest signReadinessProbeDigest( + Path privateMountRoot, + Path privateBundlePath, + Path publicMountRoot, + Path publicJwksPath, + ExpectedIdentity expectedIdentity, + ReadinessProbeSigningSpec spec, + ProbeDeliveryConsumer deliveryConsumer) { + Objects.requireNonNull(spec, "Readiness probe signing specification is required"); + Objects.requireNonNull(deliveryConsumer, "Readiness probe delivery consumer is required"); + VerifiedMountedSigner mounted = + readAndVerifyMounted( + privateMountRoot, privateBundlePath, publicMountRoot, publicJwksPath, expectedIdentity); + if (!mounted.observation().expectedIdentity().equals(expectedIdentity) + || !spec.targetGeneration().equals(expectedIdentity.generation()) + || !spec.targetKid().equals(expectedIdentity.kid())) { + 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[] deliveryBytes = null; + try { + SignedProbeDigest result; + try { + Map headerFields = new LinkedHashMap<>(); + headerFields.put("alg", ALGORITHM); + headerFields.put("kid", expectedIdentity.kid()); + headerFields.put("typ", "JWT"); + header = canonicalJsonBytes(headerFields); + claims = canonicalJsonBytes(readinessClaims(spec)); + 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_READINESS_COMPACT_JWT_BYTES) { + throw invalid(); + } + tokenDigest = MessageDigest.getInstance("SHA-256").digest(compactBytes); + result = + new SignedProbeDigest( + expectedIdentity.operationId(), + spec.validatorId(), + spec.probeKind(), + spec.tokenProfile(), + spec.audience(), + spec.jti(), + expectedIdentity.generation(), + expectedIdentity.kid(), + expectedIdentity.publicKeyFingerprint(), + spec.issuedAtEpochSecond(), + spec.expiresAtEpochSecond(), + java.util.HexFormat.of().formatHex(tokenDigest)); + } catch (InvalidMountedSignerBundleException ex) { + throw ex; + } catch (Exception ex) { + throw invalid(); + } + deliveryBytes = compactBytes.clone(); + deliveryConsumer.persistAttemptAndDeliver(result, deliveryBytes); + if (!sha256(deliveryBytes).equals(result.compactTokenSha256())) { + throw invalid(); + } + return result; + } finally { + wipe(header); + wipe(claims); + wipe(encodedHeader); + wipe(encodedClaims); + wipe(signingInput); + wipe(signatureBytes); + wipe(encodedSignature); + wipe(compactBytes); + wipe(tokenDigest); + wipe(deliveryBytes); + } + } + + /** + * Signs only the exact Account-owned, initial Game Session delegation claim shape with the + * already committed signer identity supplied by the owner service. The compact credential is + * passed once to the Account persistence callback and wiped before this method returns. + */ + static SignedDelegationDigest signCommittedGameplayDelegationDigest( + Path privateMountRoot, + Path privateBundlePath, + Path publicMountRoot, + Path publicJwksPath, + ExpectedIdentity expectedIdentity, + DelegationSigningSpec spec, + DelegationCandidateConsumer candidateConsumer) { + Objects.requireNonNull(spec, "Gameplay delegation signing specification is required"); + Objects.requireNonNull(candidateConsumer, "Gameplay delegation owner callback is required"); + VerifiedMountedSigner mounted = + readAndVerifyMounted( + privateMountRoot, privateBundlePath, publicMountRoot, publicJwksPath, expectedIdentity); + AccountGameplayDelegationPendingIdentity identity = spec.identity(); + AccountAuthoritySnapshot authority = spec.authoritySnapshot(); + if (!mounted.observation().expectedIdentity().equals(expectedIdentity) + || !authority.accountId().equals(identity.accountId())) { + 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 = delegationClaims(identity, authority); + if (spec.bound().isPresent()) { + var bound = spec.bound().orElseThrow(); + delegation.put("tenantId", bound.tenantId()); + delegation.put("authorityTuple", bound.authorityTuple()); + delegation.put("membershipVersion", bound.membershipVersion()); + } + 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( + identity.operationId(), + identity.requestId(), + identity.tokenJti(), + expectedIdentity.operationId(), + expectedIdentity.generation(), + expectedIdentity.kid(), + expectedIdentity.publicKeyFingerprint(), + identity.issuedAtEpochSecond(), + identity.notBeforeEpochSecond(), + identity.expiresAtEpochSecond(), + java.util.HexFormat.of().formatHex(tokenDigest)); + callbackBytes = compactBytes.clone(); + try { + candidateConsumer.bindExactCandidate(digest, callbackBytes); + } catch (RuntimeException failure) { + // Callback exception chains must never retain the transient compact credential. + 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); + } + } + + private static Map delegationClaims( + AccountGameplayDelegationPendingIdentity identity, AccountAuthoritySnapshot authority) { + if (!authority.accountId().equals(identity.accountId())) { + throw invalid(); + } + Map claims = new LinkedHashMap<>(); + claims.put("iss", ISSUER); + claims.put("sub", authority.accountId().toString()); + claims.put("jti", identity.tokenJti().toString()); + claims.put("accountId", authority.accountId().toString()); + claims.put("aud", GameSessionAccountDelegationProfile.AUDIENCE); + claims.put("iat", identity.issuedAtEpochSecond()); + claims.put("nbf", identity.notBeforeEpochSecond()); + claims.put("exp", identity.expiresAtEpochSecond()); + claims.put("tokenGeneration", "1"); + claims.put( + "authorityTuple", + GameSessionAccountDelegationProfile.authorityTuple( + authority.issuerGeneration(), + authority.accountGeneration(), + authority.accountSecurityCutoff())); + claims.put("membershipVersion", Map.of()); + claims.put("issuanceFence", Long.toString(authority.issuanceFence())); + return claims; + } + + private static VerifiedMountedSigner readAndVerifyMounted( + Path privateMountRoot, + Path privateBundlePath, + Path publicMountRoot, + Path publicJwksPath, + ExpectedIdentity expectedIdentity) { + byte[] privateBytes = null; + try { + if (expectedIdentity == null) { + throw invalid(); + } + validateIdentity(expectedIdentity); + Path privateFile = resolveMountedFile(privateMountRoot, privateBundlePath); + Path publicFile = resolveMountedFile(publicMountRoot, publicJwksPath); + privateBytes = readBounded(privateFile, MAX_PRIVATE_BUNDLE_BYTES); + ParsedPrivateBundle privateBundle = parsePrivateBundle(privateBytes); + Arrays.fill(privateBytes, (byte) 0); + privateBytes = null; + requireExpectedIdentity(privateBundle.identity(), expectedIdentity); + + byte[] publicBytes = readBounded(publicFile, MAX_PUBLIC_JWKS_BYTES); + Map publicKeys; + try { + publicKeys = parsePublicJwks(publicBytes); + } finally { + Arrays.fill(publicBytes, (byte) 0); + } + RSAPublicKey publicKey = publicKeys.get(expectedIdentity.kid()); + if (publicKey == null + || !publicKey.getModulus().equals(privateBundle.publicModulus()) + || !publicKey.getPublicExponent().equals(privateBundle.publicExponent())) { + throw invalid(); + } + String fingerprint = fingerprint(publicKey.getModulus(), publicKey.getPublicExponent()); + if (!fingerprint.equals(expectedIdentity.publicKeyFingerprint()) + || !fingerprint.equals(privateBundle.identity().publicKeyFingerprint())) { + throw invalid(); + } + proveCorrespondence(privateBundle.privateKey(), publicKey); + return new VerifiedMountedSigner( + new LocalObservation(expectedIdentity, fingerprint), + privateBundle.privateKey(), + publicKey); + } catch (InvalidMountedSignerBundleException ex) { + throw ex; + } catch (Exception ex) { + // Do not retain path, parser, key, or mounted-file details in a caller-visible failure. + throw invalid(); + } finally { + if (privateBytes != null) { + Arrays.fill(privateBytes, (byte) 0); + } + } + } + + private static Map readinessClaims(ReadinessProbeSigningSpec spec) { + Map claims = new LinkedHashMap<>(); + claims.put("iss", ISSUER); + claims.put("sub", RESERVED_SUBJECT); + claims.put("jti", spec.jti().toString()); + claims.put("aud", spec.audience()); + claims.put("iat", spec.issuedAtEpochSecond()); + claims.put("nbf", spec.issuedAtEpochSecond()); + claims.put("exp", spec.expiresAtEpochSecond()); + if (spec.probeKind() == ProbeKind.CANARY) { + claims.put("tokenProfile", READINESS_CANARY_PROFILE); + claims.put("tokenType", READINESS_CANARY_TYPE); + return claims; + } + if (ControlUiJwtProfileValidator.PROFILE.equals(spec.tokenProfile()) + || PlayerBootstrapJwtProfileValidator.PROFILE.equals(spec.tokenProfile())) { + claims.put("scopedRoles", Map.of()); + } + boolean decimalCounters = + GameSessionAccountDelegationProfile.PROFILE.equals(spec.tokenProfile()); + Object initialCounter = decimalCounters ? "1" : 1L; + claims.put("accountId", RESERVED_SUBJECT); + claims.put("tokenGeneration", initialCounter); + Map authorityTuple = new LinkedHashMap<>(); + authorityTuple.put("issuerAuthGeneration", initialCounter); + authorityTuple.put("accountAuthorityGeneration", initialCounter); + authorityTuple.put("tenantAuthorityGeneration", Map.of()); + authorityTuple.put("membershipAuthorityGeneration", Map.of()); + authorityTuple.put("privateRealmGrantVersions", List.of()); + claims.put("authorityTuple", authorityTuple); + claims.put("membershipVersion", Map.of()); + claims.put("issuanceFence", initialCounter); + return claims; + } + + private static byte[] canonicalJsonBytes(Map fields) throws Exception { + String json = STRICT_JSON.writeValueAsString(fields); + return Rfc8785CanonicalJson.canonicalizeUtf8(json); + } + + private static byte[] joinCompactParts(byte[] header, byte[] claims, byte[] signature) { + int signatureLength = signature == null ? 0 : signature.length; + int separatorCount = signature == null ? 1 : 2; + byte[] compact = new byte[header.length + claims.length + signatureLength + separatorCount]; + int offset = 0; + System.arraycopy(header, 0, compact, offset, header.length); + offset += header.length; + compact[offset++] = (byte) '.'; + System.arraycopy(claims, 0, compact, offset, claims.length); + offset += claims.length; + if (signature != null) { + compact[offset++] = (byte) '.'; + System.arraycopy(signature, 0, compact, offset, signature.length); + } + return compact; + } + + private static void wipe(byte[] bytes) { + if (bytes != null) { + Arrays.fill(bytes, (byte) 0); + } + } + + private static String sha256(byte[] bytes) { + try { + return java.util.HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (GeneralSecurityException ex) { + throw invalid(); + } + } + + /** + * Builds the binary, domain-separated challenge used only by the local correspondence proof. Its + * leading NUL makes it structurally distinct from an ASCII compact JWT serialization. + */ + static byte[] correspondenceChallenge(byte[] nonce) { + if (nonce == null || nonce.length != CHALLENGE_NONCE_BYTES) { + throw invalid(); + } + byte[] challenge = Arrays.copyOf(CHALLENGE_DOMAIN, CHALLENGE_DOMAIN.length + nonce.length); + System.arraycopy(nonce, 0, challenge, CHALLENGE_DOMAIN.length, nonce.length); + return challenge; + } + + static void validateStrongRsaCrtPrivateKey(PrivateKey privateKey) { + if (!(privateKey instanceof RSAPrivateCrtKey rsaPrivateKey) + || !"RSA".equalsIgnoreCase(privateKey.getAlgorithm())) { + throw invalid(); + } + BigInteger modulus = rsaPrivateKey.getModulus(); + BigInteger publicExponent = rsaPrivateKey.getPublicExponent(); + BigInteger privateExponent = rsaPrivateKey.getPrivateExponent(); + BigInteger primeP = rsaPrivateKey.getPrimeP(); + BigInteger primeQ = rsaPrivateKey.getPrimeQ(); + BigInteger primeExponentP = rsaPrivateKey.getPrimeExponentP(); + BigInteger primeExponentQ = rsaPrivateKey.getPrimeExponentQ(); + BigInteger crtCoefficient = rsaPrivateKey.getCrtCoefficient(); + if (!positive(modulus) + || modulus.bitLength() < MIN_RSA_BITS + || modulus.bitLength() > MAX_RSA_BITS + || !BigInteger.valueOf(65_537).equals(publicExponent) + || !positive(privateExponent) + || !positive(primeP) + || !positive(primeQ) + || primeP.equals(primeQ) + || !positive(primeExponentP) + || !positive(primeExponentQ) + || !positive(crtCoefficient)) { + throw invalid(); + } + BigInteger pMinusOne = primeP.subtract(BigInteger.ONE); + BigInteger qMinusOne = primeQ.subtract(BigInteger.ONE); + BigInteger lambda = pMinusOne.divide(pMinusOne.gcd(qMinusOne)).multiply(qMinusOne); + if (!primeP.multiply(primeQ).equals(modulus) + || !privateExponent.multiply(publicExponent).mod(lambda).equals(BigInteger.ONE) + || !privateExponent.mod(pMinusOne).equals(primeExponentP) + || !privateExponent.mod(qMinusOne).equals(primeExponentQ) + || !primeQ.modInverse(primeP).equals(crtCoefficient)) { + throw invalid(); + } + } + + private static void validateIdentity(ExpectedIdentity identity) { + if (!validIdentityValue(identity.environmentId()) + || !validIdentityValue(identity.clusterId()) + || !validIdentityValue(identity.namespace()) + || !validUuidV4(identity.operationId()) + || identity.generation() == null + || !GENERATION.matcher(identity.generation()).matches() + || identity.kid() == null + || !KID.matcher(identity.kid()).matches() + || identity.publicKeyFingerprint() == null + || !FINGERPRINT.matcher(identity.publicKeyFingerprint()).matches()) { + throw invalid(); + } + } + + private static boolean validIdentityValue(String value) { + if (value == null || value.isBlank() || value.length() > 128) { + return false; + } + for (int index = 0; index < value.length(); index++) { + if (Character.isISOControl(value.charAt(index))) { + return false; + } + } + return true; + } + + private static boolean validUuidV4(String value) { + if (value == null) { + return false; + } + try { + UUID uuid = UUID.fromString(value); + return uuid.toString().equals(value) && uuid.version() == 4 && uuid.variant() == 2; + } catch (IllegalArgumentException ex) { + return false; + } + } + + private static void requireExpectedIdentity(ExpectedIdentity actual, ExpectedIdentity expected) { + if (!actual.equals(expected)) { + throw invalid(); + } + } + + private static ParsedPrivateBundle parsePrivateBundle(byte[] contents) { + if (contents == null || contents.length == 0 || contents.length > MAX_PRIVATE_BUNDLE_BYTES) { + throw invalid(); + } + try { + JsonNode root = strictJson(contents); + requireOnlyFields(root, PRIVATE_BUNDLE_FIELDS); + if (root.size() != PRIVATE_BUNDLE_FIELDS.size()) { + throw invalid(); + } + JsonNode version = root.get("version"); + if (version == null + || version.isNull() + || !version.isIntegralNumber() + || !version.canConvertToInt() + || version.intValue() != 1) { + throw invalid(); + } + ExpectedIdentity identity = + new ExpectedIdentity( + requiredText(root, "environmentId", 128), + requiredText(root, "clusterId", 128), + requiredText(root, "namespace", 128), + requiredText(root, "operationId", 36), + requiredText(root, "generation", 64), + requiredText(root, "kid", 64), + requiredText(root, "publicKeyFingerprint", 64)); + validateIdentity(identity); + if (!ALGORITHM.equals(requiredText(root, "algorithm", 8))) { + throw invalid(); + } + + String encodedPrivateKey = requiredText(root, "privateKeyPkcs8", 24 * 1024); + byte[] privateDer = decodeCanonicalBase64Url(encodedPrivateKey, MAX_PRIVATE_KEY_DER_BYTES); + try { + PrivateKey privateKey = + KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(privateDer)); + validateStrongRsaCrtPrivateKey(privateKey); + RSAPrivateCrtKey rsaPrivateKey = (RSAPrivateCrtKey) privateKey; + byte[] canonicalEncoding = privateKey.getEncoded(); + try { + if (canonicalEncoding == null || !Arrays.equals(privateDer, canonicalEncoding)) { + throw invalid(); + } + } finally { + if (canonicalEncoding != null) { + Arrays.fill(canonicalEncoding, (byte) 0); + } + } + return new ParsedPrivateBundle( + privateKey, identity, rsaPrivateKey.getModulus(), rsaPrivateKey.getPublicExponent()); + } finally { + Arrays.fill(privateDer, (byte) 0); + } + } catch (InvalidMountedSignerBundleException ex) { + throw ex; + } catch (CharacterCodingException | GeneralSecurityException | RuntimeException ex) { + throw invalid(); + } + } + + private static Map parsePublicJwks(byte[] contents) { + if (contents == null || contents.length == 0 || contents.length > MAX_PUBLIC_JWKS_BYTES) { + throw invalid(); + } + try { + JsonNode root = strictJson(contents); + requireOnlyFields(root, JWKS_FIELDS); + if (root.size() != 1) { + throw invalid(); + } + JsonNode keysNode = root.get("keys"); + if (keysNode == null + || !keysNode.isArray() + || keysNode.isEmpty() + || keysNode.size() > MAX_JWKS_KEYS) { + throw invalid(); + } + Map keys = new HashMap<>(); + Set seenKids = new HashSet<>(); + for (JsonNode jwk : keysNode) { + requireOnlyFields(jwk, JWK_FIELDS); + String keyType = requiredText(jwk, "kty", 8); + String use = requiredText(jwk, "use", 8); + String algorithm = requiredText(jwk, "alg", 8); + String kid = requiredText(jwk, "kid", 64); + String encodedModulus = requiredText(jwk, "n", 4_096); + String encodedExponent = requiredText(jwk, "e", 16); + if (!"RSA".equals(keyType) + || !"sig".equals(use) + || !ALGORITHM.equals(algorithm) + || !KID.matcher(kid).matches() + || !seenKids.add(kid)) { + throw invalid(); + } + JsonNode keyOps = jwk.get("key_ops"); + if (keyOps != null) { + if (!keyOps.isArray() + || keyOps.size() != 1 + || !keyOps.get(0).isTextual() + || !"verify".equals(keyOps.get(0).textValue())) { + throw invalid(); + } + } + byte[] modulusBytes = decodeCanonicalBase64Url(encodedModulus, 2_048); + byte[] exponentBytes = decodeCanonicalBase64Url(encodedExponent, 8); + try { + if (modulusBytes.length == 0 + || modulusBytes[0] == 0 + || exponentBytes.length == 0 + || exponentBytes[0] == 0) { + throw invalid(); + } + BigInteger modulus = new BigInteger(1, modulusBytes); + BigInteger exponent = new BigInteger(1, exponentBytes); + if (modulus.bitLength() < MIN_RSA_BITS + || modulus.bitLength() > MAX_RSA_BITS + || !modulus.testBit(0) + || !BigInteger.valueOf(65_537).equals(exponent)) { + throw invalid(); + } + RSAPublicKey publicKey = + (RSAPublicKey) + KeyFactory.getInstance("RSA") + .generatePublic(new RSAPublicKeySpec(modulus, exponent)); + keys.put(kid, publicKey); + } finally { + Arrays.fill(modulusBytes, (byte) 0); + Arrays.fill(exponentBytes, (byte) 0); + } + } + return Map.copyOf(keys); + } catch (InvalidMountedSignerBundleException ex) { + throw ex; + } catch (CharacterCodingException | GeneralSecurityException | RuntimeException ex) { + throw invalid(); + } + } + + private static JsonNode strictJson(byte[] contents) throws CharacterCodingException { + String text = + StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(contents)) + .toString(); + if (text.startsWith("\uFEFF")) { + throw invalid(); + } + JsonNode root = STRICT_JSON.readTree(text); + if (root == null || root.isNull()) { + throw invalid(); + } + return root; + } + + private static void requireOnlyFields(JsonNode node, Set allowedFields) { + if (node == null || !node.isObject()) { + throw invalid(); + } + for (Map.Entry field : node.properties()) { + if (!allowedFields.contains(field.getKey())) { + throw invalid(); + } + } + } + + private static String requiredText(JsonNode object, String name, int maxLength) { + JsonNode value = object.get(name); + if (value == null || value.isNull() || !value.isTextual()) { + throw invalid(); + } + String text = value.textValue(); + if (text == null || text.isEmpty() || text.length() > maxLength) { + throw invalid(); + } + return text; + } + + private static byte[] decodeCanonicalBase64Url(String encoded, int maxBytes) { + if (encoded == null || encoded.isEmpty()) { + throw invalid(); + } + byte[] decoded; + try { + decoded = Base64.getUrlDecoder().decode(encoded); + } catch (IllegalArgumentException ex) { + throw invalid(); + } + byte[] canonical = Base64.getUrlEncoder().withoutPadding().encode(decoded); + boolean canonicalEncoding = canonical.length == encoded.length(); + for (int index = 0; canonicalEncoding && index < canonical.length; index++) { + canonicalEncoding = (char) Byte.toUnsignedInt(canonical[index]) == encoded.charAt(index); + } + Arrays.fill(canonical, (byte) 0); + if (decoded.length == 0 || decoded.length > maxBytes || !canonicalEncoding) { + Arrays.fill(decoded, (byte) 0); + throw invalid(); + } + return decoded; + } + + private static Path resolveMountedFile(Path configuredRoot, Path configuredRelativeFile) + throws IOException { + if (configuredRoot == null + || configuredRelativeFile == null + || !configuredRoot.isAbsolute() + || configuredRelativeFile.isAbsolute() + || configuredRelativeFile.toString().isBlank()) { + throw invalid(); + } + for (Path segment : configuredRelativeFile) { + if (".".equals(segment.toString()) || "..".equals(segment.toString())) { + throw invalid(); + } + } + Path mountRoot = configuredRoot.toRealPath(); + if (!Files.isDirectory(mountRoot, LinkOption.NOFOLLOW_LINKS)) { + throw invalid(); + } + Path resolvedFile = mountRoot.resolve(configuredRelativeFile).toRealPath(); + if (!resolvedFile.startsWith(mountRoot) + || !Files.isRegularFile(resolvedFile, LinkOption.NOFOLLOW_LINKS)) { + throw invalid(); + } + return resolvedFile; + } + + private static byte[] readBounded(Path path, int maxBytes) throws IOException { + byte[] scratch = new byte[maxBytes + 1]; + try { + try (SeekableByteChannel channel = + Files.newByteChannel(path, Set.of(StandardOpenOption.READ, LinkOption.NOFOLLOW_LINKS))) { + ByteBuffer buffer = ByteBuffer.wrap(scratch); + int total = 0; + while (true) { + int count = channel.read(buffer); + if (count < 0) { + break; + } + if (count == 0) { + continue; + } + total += count; + if (total > maxBytes) { + throw invalid(); + } + } + if (channel.position() != channel.size() || total != channel.size()) { + throw invalid(); + } + return Arrays.copyOf(scratch, total); + } + } finally { + Arrays.fill(scratch, (byte) 0); + } + } + + private static void proveCorrespondence(PrivateKey privateKey, RSAPublicKey publicKey) + throws GeneralSecurityException { + byte[] nonce = new byte[CHALLENGE_NONCE_BYTES]; + byte[] challenge = null; + byte[] signatureBytes = null; + try { + CHALLENGE_RANDOM.nextBytes(nonce); + challenge = correspondenceChallenge(nonce); + Signature signer = Signature.getInstance("SHA256withRSA"); + signer.initSign(privateKey); + signer.update(challenge); + signatureBytes = signer.sign(); + + Signature verifier = Signature.getInstance("SHA256withRSA"); + verifier.initVerify(publicKey); + verifier.update(challenge); + if (!verifier.verify(signatureBytes)) { + throw invalid(); + } + } finally { + Arrays.fill(nonce, (byte) 0); + if (challenge != null) { + Arrays.fill(challenge, (byte) 0); + } + if (signatureBytes != null) { + Arrays.fill(signatureBytes, (byte) 0); + } + } + } + + private static String fingerprint(BigInteger modulus, BigInteger exponent) { + String canonicalJwk = + "{\"e\":\"" + + base64Url(unsignedBytes(exponent)) + + "\",\"kty\":\"RSA\",\"n\":\"" + + base64Url(unsignedBytes(modulus)) + + "\"}"; + try { + byte[] digest = + MessageDigest.getInstance("SHA-256") + .digest(canonicalJwk.getBytes(StandardCharsets.US_ASCII)); + return java.util.HexFormat.of().formatHex(digest); + } catch (GeneralSecurityException ex) { + throw invalid(); + } + } + + private static byte[] unsignedBytes(BigInteger value) { + byte[] encoded = value.toByteArray(); + if (encoded.length > 1 && encoded[0] == 0) { + return Arrays.copyOfRange(encoded, 1, encoded.length); + } + return encoded; + } + + private static String base64Url(byte[] bytes) { + try { + return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes); + } finally { + Arrays.fill(bytes, (byte) 0); + } + } + + private static boolean positive(BigInteger value) { + return value != null && value.signum() > 0; + } + + private static InvalidMountedSignerBundleException invalid() { + return new InvalidMountedSignerBundleException(); + } + + /** Caller-supplied durable request identity; it is not authorization or proof of provisioning. */ + public record ExpectedIdentity( + String environmentId, + String clusterId, + String namespace, + String operationId, + String generation, + String kid, + String publicKeyFingerprint) {} + + /** Closed signing input built only from the issuance repository's locked owner readback. */ + record DelegationSigningSpec( + AccountGameplayDelegationPendingIdentity identity, + AccountAuthoritySnapshot authoritySnapshot, + Optional bound) { + DelegationSigningSpec( + AccountGameplayDelegationPendingIdentity identity, + AccountAuthoritySnapshot authoritySnapshot) { + this(identity, authoritySnapshot, Optional.empty()); + } + + DelegationSigningSpec { + Objects.requireNonNull(bound); + Objects.requireNonNull(identity, "Persisted pending identity is required"); + Objects.requireNonNull(authoritySnapshot, "Persisted Account authority is required"); + if (!authoritySnapshot.accountId().equals(identity.accountId()) + || identity.issuedAtEpochSecond() <= 0L + || identity.notBeforeEpochSecond() <= 0L + || identity.notBeforeEpochSecond() > identity.issuedAtEpochSecond() + || identity.expiresAtEpochSecond() <= identity.issuedAtEpochSecond() + || identity.expiresAtEpochSecond() - identity.issuedAtEpochSecond() + > GameSessionAccountDelegationProfile.MAX_TOKEN_LIFETIME_SECONDS) { + throw invalid(); + } + } + } + + record BoundDelegationClaims( + String tenantId, Map authorityTuple, Map membershipVersion) { + BoundDelegationClaims { + net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile + .requirePublicTenantBoundAuthority(tenantId, authorityTuple, membershipVersion); + authorityTuple = Map.copyOf(authorityTuple); + membershipVersion = Map.copyOf(membershipVersion); + } + } + + @FunctionalInterface + interface DelegationCandidateConsumer { + /** The caller persists the exact candidate before any internal transient handoff. */ + void bindExactCandidate(SignedDelegationDigest digest, byte[] compactJwt); + } + + /** Non-secret operation, signer and token-hash identity; never includes compact JWT bytes. */ + static final class SignedDelegationDigest { + private final UUID issuanceOperationId; + private final UUID requestId; + private final UUID jti; + private final String signerOperationId; + private final String signerGeneration; + private final String kid; + private final String publicKeyFingerprint; + private final long issuedAtEpochSecond; + private final long notBeforeEpochSecond; + private final long expiresAtEpochSecond; + private final String compactTokenSha256; + + private SignedDelegationDigest( + UUID issuanceOperationId, + UUID requestId, + UUID jti, + String signerOperationId, + String signerGeneration, + String kid, + String publicKeyFingerprint, + long issuedAtEpochSecond, + long notBeforeEpochSecond, + long expiresAtEpochSecond, + String compactTokenSha256) { + this.issuanceOperationId = Objects.requireNonNull(issuanceOperationId); + this.requestId = Objects.requireNonNull(requestId); + this.jti = Objects.requireNonNull(jti); + this.signerOperationId = Objects.requireNonNull(signerOperationId); + this.signerGeneration = Objects.requireNonNull(signerGeneration); + this.kid = Objects.requireNonNull(kid); + this.publicKeyFingerprint = Objects.requireNonNull(publicKeyFingerprint); + this.issuedAtEpochSecond = issuedAtEpochSecond; + this.notBeforeEpochSecond = notBeforeEpochSecond; + this.expiresAtEpochSecond = expiresAtEpochSecond; + if (compactTokenSha256 == null || !FINGERPRINT.matcher(compactTokenSha256).matches()) { + throw invalid(); + } + this.compactTokenSha256 = compactTokenSha256; + } + + UUID issuanceOperationId() { + return issuanceOperationId; + } + + UUID requestId() { + return requestId; + } + + UUID jti() { + return jti; + } + + String signerOperationId() { + return signerOperationId; + } + + String signerGeneration() { + return signerGeneration; + } + + String kid() { + return kid; + } + + String publicKeyFingerprint() { + return publicKeyFingerprint; + } + + long issuedAtEpochSecond() { + return issuedAtEpochSecond; + } + + long notBeforeEpochSecond() { + return notBeforeEpochSecond; + } + + long expiresAtEpochSecond() { + return expiresAtEpochSecond; + } + + String compactTokenSha256() { + return compactTokenSha256; + } + + @Override + public String toString() { + return "SignedDelegationDigest[redacted]"; + } + } + + public enum ProbeKind { + CANARY, + REPRESENTATIVE + } + + @FunctionalInterface + interface ProbeDeliveryConsumer { + /** The caller must durably pin {@code digest} before passing the transient bytes onward. */ + void persistAttemptAndDeliver(SignedProbeDigest digest, byte[] compactJwt); + } + + /** A closed claim-shape input; its constructor permits only the two declared readiness forms. */ + record ReadinessProbeSigningSpec( + String validatorId, + ProbeKind probeKind, + String tokenProfile, + String audience, + UUID jti, + String targetGeneration, + String targetKid, + long issuedAtEpochSecond, + long expiresAtEpochSecond) { + ReadinessProbeSigningSpec { + if (validatorId == null + || !READINESS_VALIDATOR_ID.equals(validatorId) + || probeKind == null + || jti == null + || jti.version() != 4 + || jti.variant() != 2 + || targetGeneration == null + || !GENERATION.matcher(targetGeneration).matches() + || targetKid == null + || !KID.matcher(targetKid).matches() + || issuedAtEpochSecond <= 0L + || expiresAtEpochSecond <= issuedAtEpochSecond + || expiresAtEpochSecond - issuedAtEpochSecond > 300L) { + throw invalid(); + } + if (probeKind == ProbeKind.CANARY) { + if (!READINESS_CANARY_PROFILE.equals(tokenProfile) + || !READINESS_CANARY_AUDIENCE.equals(audience)) { + throw invalid(); + } + } else { + boolean exactProfileAudience = + (ControlUiJwtProfileValidator.PROFILE.equals(tokenProfile) + && ControlUiJwtProfileValidator.AUDIENCE.equals(audience)) + || (PlayerBootstrapJwtProfileValidator.PROFILE.equals(tokenProfile) + && PlayerBootstrapJwtProfileValidator.AUDIENCE.equals(audience)) + || (REPRESENTATIVE_PROFILE.equals(tokenProfile) + && REPRESENTATIVE_AUDIENCE.equals(audience)); + if (!exactProfileAudience) { + throw invalid(); + } + } + } + } + + /** Non-secret output from the one constrained signing operation; it never contains JWT bytes. */ + public static final class SignedProbeDigest { + private final String operationId; + private final String validatorId; + private final ProbeKind probeKind; + private final String tokenProfile; + private final String audience; + private final UUID jti; + private final String targetGeneration; + private final String targetKid; + private final String publicKeyFingerprint; + private final long issuedAtEpochSecond; + private final long expiresAtEpochSecond; + private final String compactTokenSha256; + + private SignedProbeDigest( + String operationId, + String validatorId, + ProbeKind probeKind, + String tokenProfile, + String audience, + UUID jti, + String targetGeneration, + String targetKid, + String publicKeyFingerprint, + long issuedAtEpochSecond, + long expiresAtEpochSecond, + String compactTokenSha256) { + this.operationId = operationId; + this.validatorId = validatorId; + this.probeKind = probeKind; + this.tokenProfile = tokenProfile; + this.audience = audience; + this.jti = jti; + this.targetGeneration = targetGeneration; + this.targetKid = targetKid; + this.publicKeyFingerprint = publicKeyFingerprint; + this.issuedAtEpochSecond = issuedAtEpochSecond; + this.expiresAtEpochSecond = expiresAtEpochSecond; + this.compactTokenSha256 = compactTokenSha256; + } + + public String operationId() { + return operationId; + } + + public String validatorId() { + return validatorId; + } + + public ProbeKind probeKind() { + return probeKind; + } + + public String tokenProfile() { + return tokenProfile; + } + + public String audience() { + return audience; + } + + public UUID jti() { + return jti; + } + + public String targetGeneration() { + return targetGeneration; + } + + public String targetKid() { + return targetKid; + } + + public String publicKeyFingerprint() { + return publicKeyFingerprint; + } + + public long issuedAtEpochSecond() { + return issuedAtEpochSecond; + } + + public long expiresAtEpochSecond() { + return expiresAtEpochSecond; + } + + public String compactTokenSha256() { + return compactTokenSha256; + } + + @Override + public String toString() { + return "AccountMountedJwtSignerBundle.SignedProbeDigest[operation=" + + operationId + + ", probeKind=" + + probeKind + + ", tokenBytes=discarded, authorization=none, verification=unproved]"; + } + } + + /** Non-secret, process-local observation with no token-signing or private-key accessor. */ + public static final class LocalObservation { + private final ExpectedIdentity expectedIdentity; + private final String publicKeyFingerprint; + + private LocalObservation(ExpectedIdentity expectedIdentity, String publicKeyFingerprint) { + this.expectedIdentity = expectedIdentity; + this.publicKeyFingerprint = publicKeyFingerprint; + } + + public ExpectedIdentity expectedIdentity() { + return expectedIdentity; + } + + public String publicKeyFingerprint() { + return publicKeyFingerprint; + } + + public boolean localPrivatePublicCorrespondenceObserved() { + return true; + } + + @Override + public String toString() { + return "AccountMountedJwtSignerBundle.LocalObservation[local correspondence observed; " + + "authorization=none, provisioning=unproved, readiness=unproved]"; + } + } + + /** Safe generic failure for malformed, unavailable, or mismatched mounted projections. */ + public static final class InvalidMountedSignerBundleException extends IllegalArgumentException { + private InvalidMountedSignerBundleException() { + super("Mounted signer correspondence is unavailable or invalid"); + } + } + + private record ParsedPrivateBundle( + PrivateKey privateKey, + ExpectedIdentity identity, + BigInteger publicModulus, + BigInteger publicExponent) {} + + private record VerifiedMountedSigner( + LocalObservation observation, PrivateKey privateKey, RSAPublicKey publicKey) {} +} diff --git a/services/account-service/src/main/resources/db/migration/V100__account_jwt_readiness_per_pod_closure.sql b/services/account-service/src/main/resources/db/migration/V100__account_jwt_readiness_per_pod_closure.sql new file mode 100644 index 0000000000..49e6204d33 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V100__account_jwt_readiness_per_pod_closure.sql @@ -0,0 +1,777 @@ +-- V2 readiness plans bind every protected live validator Pod and retain one immutable production +-- verification receipt per Pod and logical probe. Existing V1 plans and receipts remain retained +-- and partial; they are never rewritten into V2 closure evidence. + +ALTER TABLE account_jwt_readiness_probe_plans + DROP CONSTRAINT account_jwt_readiness_plan_window_check; + +ALTER TABLE account_jwt_readiness_probe_plans + ADD CONSTRAINT account_jwt_readiness_plan_window_check + CHECK (maximum_cache_age_seconds BETWEEN 1 AND 300 + AND planned_at_epoch_seconds > 0 + AND not_before_epoch_seconds >= planned_at_epoch_seconds + maximum_cache_age_seconds + AND expires_at_epoch_seconds > not_before_epoch_seconds + AND expires_at_epoch_seconds - not_before_epoch_seconds <= 300 + AND plan_version IN (1, 2) + AND (plan_version <> 2 OR inventory_snapshot_digest IS NOT NULL)); + +ALTER TABLE account_jwt_readiness_probe_entries + ADD COLUMN entry_plan_version SMALLINT NOT NULL DEFAULT 1; + +ALTER TABLE account_jwt_readiness_probe_entries + ADD COLUMN pod_receipt_count SMALLINT; + +ALTER TABLE account_jwt_readiness_probe_entries + ADD COLUMN pod_receipt_closure_sha256 VARCHAR(64); + +ALTER TABLE account_jwt_readiness_probe_entries + DROP CONSTRAINT account_jwt_readiness_probe_evidence_check; + +ALTER TABLE account_jwt_readiness_probe_entries + ADD CONSTRAINT account_jwt_readiness_probe_evidence_check + CHECK (plan_digest ~ '^[0-9a-f]{64}$' + AND registry_version = 1 + AND entry_plan_version IN (1, 2) + AND entry_version > 0 + AND planned_issued_at_epoch_seconds > 0 + AND expires_at_epoch_seconds > planned_issued_at_epoch_seconds + AND (compact_token_sha256 IS NULL OR compact_token_sha256 ~ '^[0-9a-f]{64}$') + AND (signing_attempted_at_epoch_seconds IS NULL + OR (signing_attempted_at_epoch_seconds >= planned_issued_at_epoch_seconds + AND signing_attempted_at_epoch_seconds < expires_at_epoch_seconds)) + AND ((compact_token_sha256 IS NULL AND signing_attempted_at_epoch_seconds IS NULL) + OR (compact_token_sha256 IS NOT NULL AND signing_attempted_at_epoch_seconds IS NOT NULL)) + AND (state NOT IN ('ISSUED', 'VERIFIED', 'RETIRED') OR compact_token_sha256 IS NOT NULL) + AND (verification_receipt_version IS NULL + OR (entry_plan_version = 1 AND verification_receipt_version = 1) + OR (entry_plan_version = 2 AND verification_receipt_version = 2)) + AND (verification_source_entry_version IS NULL OR verification_source_entry_version > 0) + AND (verified_at_epoch_seconds IS NULL + OR (verified_at_epoch_seconds >= planned_issued_at_epoch_seconds + AND verified_at_epoch_seconds < expires_at_epoch_seconds)) + AND (verified_kid IS NULL OR verified_kid = target_kid) + AND (validator_instance_id IS NULL + OR validator_instance_id ~ '^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$') + AND (validator_binding_digest IS NULL OR validator_binding_digest ~ '^[0-9a-f]{64}$') + AND (validator_config_revision IS NULL + OR validator_config_revision ~ '^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$') + AND (validator_peer_uri IS NULL + OR validator_peer_uri ~ '^spiffe://firemud/ns/[a-z0-9-]{1,63}/sa/[a-z0-9][a-z0-9-]{0,62}$') + AND (validator_peer_spki_sha256 IS NULL + OR validator_peer_spki_sha256 ~ '^[0-9a-f]{64}$') + AND (verification_receipt_sha256 IS NULL + OR verification_receipt_sha256 ~ '^[0-9a-f]{64}$') + AND (pod_receipt_count IS NULL OR pod_receipt_count BETWEEN 1 AND 256) + AND (pod_receipt_closure_sha256 IS NULL + OR pod_receipt_closure_sha256 ~ '^[0-9a-f]{64}$') + AND ((verification_receipt_sha256 IS NULL + AND verification_receipt_version IS NULL + AND verification_source_entry_version IS NULL + AND verified_at_epoch_seconds IS NULL + AND verified_kid IS NULL + AND validator_instance_id IS NULL + AND validator_binding_digest IS NULL + AND validator_config_revision IS NULL + AND validator_peer_uri IS NULL + AND validator_peer_spki_sha256 IS NULL + AND pod_receipt_count IS NULL + AND pod_receipt_closure_sha256 IS NULL) + OR (verification_receipt_sha256 IS NOT NULL + AND verification_receipt_version = 1 + AND entry_plan_version = 1 + AND verification_source_entry_version IS NOT NULL + AND verified_at_epoch_seconds IS NOT NULL + AND verified_kid IS NOT NULL + AND validator_instance_id IS NOT NULL + AND validator_binding_digest IS NOT NULL + AND validator_config_revision IS NOT NULL + AND validator_peer_uri IS NOT NULL + AND validator_peer_spki_sha256 IS NOT NULL + AND pod_receipt_count IS NULL + AND pod_receipt_closure_sha256 IS NULL) + OR (verification_receipt_sha256 IS NOT NULL + AND verification_receipt_version = 2 + AND entry_plan_version = 2 + AND verification_source_entry_version IS NOT NULL + AND verified_at_epoch_seconds IS NOT NULL + AND verified_kid = target_kid + AND validator_instance_id IS NOT NULL + AND validator_binding_digest IS NOT NULL + AND validator_config_revision IS NOT NULL + AND validator_peer_uri IS NOT NULL + AND validator_peer_spki_sha256 IS NOT NULL + AND pod_receipt_count IS NOT NULL + AND pod_receipt_closure_sha256 = verification_receipt_sha256)) + AND (state NOT IN ('VERIFIED', 'RETIRED') OR verification_receipt_sha256 IS NOT NULL) + AND (state NOT IN ('PLANNED', 'ISSUED') OR verification_receipt_sha256 IS NULL)); + +CREATE TABLE account_jwt_readiness_validator_pods ( + rotation_operation_id UUID NOT NULL, + plan_digest VARCHAR(64) NOT NULL, + validator_id VARCHAR(63) NOT NULL, + token_profile VARCHAR(128) NOT NULL, + audience VARCHAR(128) NOT NULL, + probe_kind VARCHAR(16) NOT NULL, + jti UUID NOT NULL, + inventory_snapshot_digest VARCHAR(64) NOT NULL, + environment_id VARCHAR(63) NOT NULL, + cluster_id VARCHAR(128) NOT NULL, + cluster_incarnation_uid UUID NOT NULL, + kubernetes_namespace VARCHAR(63) NOT NULL, + namespace_uid UUID NOT NULL, + api_binding_revision VARCHAR(128) NOT NULL, + api_binding_digest VARCHAR(64) NOT NULL, + inventory_binding_revision VARCHAR(128) NOT NULL, + inventory_binding_digest VARCHAR(64) NOT NULL, + deployment_uid UUID NOT NULL, + pod_uid UUID NOT NULL, + pod_ip VARCHAR(45) NOT NULL, + image VARCHAR(512) NOT NULL, + verifier_config_sha256 VARCHAR(64) NOT NULL, + applicability_matrix_digest VARCHAR(64) NOT NULL, + expected_outcome VARCHAR(32) NOT NULL, + exact_pod_endpoint VARCHAR(512) NOT NULL, + canonical_service_uri VARCHAR(256) NOT NULL, + expected_pod_leaf_spki_sha256 VARCHAR(64) NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (rotation_operation_id, validator_id, token_profile, audience, probe_kind, pod_uid), + CONSTRAINT account_jwt_readiness_validator_pod_entry_fk + FOREIGN KEY (rotation_operation_id, validator_id, token_profile, audience, probe_kind) + REFERENCES account_jwt_readiness_probe_entries( + rotation_operation_id, validator_id, token_profile, audience, probe_kind) + ON DELETE RESTRICT, + CONSTRAINT account_jwt_readiness_validator_pod_snapshot_fk + FOREIGN KEY (inventory_snapshot_digest, environment_id, cluster_id, kubernetes_namespace, + cluster_incarnation_uid, namespace_uid) + REFERENCES account_jwt_validator_inventory_snapshots( + snapshot_digest, environment_id, cluster_id, kubernetes_namespace, + cluster_incarnation_uid, namespace_uid) + ON DELETE RESTRICT, + CONSTRAINT account_jwt_readiness_validator_pod_shape_check + CHECK (rotation_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 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 plan_digest ~ '^[0-9a-f]{64}$' + AND inventory_snapshot_digest ~ '^[0-9a-f]{64}$' + AND validator_id ~ '^[a-z0-9][a-z0-9-]{0,62}$' + AND token_profile ~ '^[a-z0-9][a-z0-9-]{0,127}$' + AND audience ~ '^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$' + AND probe_kind IN ('CANARY', 'REPRESENTATIVE') + AND environment_id ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$' + AND cluster_id ~ '^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$' + AND cluster_incarnation_uid <> '00000000-0000-0000-0000-000000000000'::UUID + AND kubernetes_namespace ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$' + AND namespace_uid <> '00000000-0000-0000-0000-000000000000'::UUID + AND api_binding_revision ~ '^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$' + AND api_binding_digest ~ '^[0-9a-f]{64}$' + AND inventory_binding_revision ~ '^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$' + AND inventory_binding_digest ~ '^[0-9a-f]{64}$' + AND deployment_uid <> '00000000-0000-0000-0000-000000000000'::UUID + AND pod_uid <> '00000000-0000-0000-0000-000000000000'::UUID + AND (pod_ip ~ '^(?:[0-9]{1,3}[.]){3}[0-9]{1,3}$' OR pod_ip ~ '^[0-9a-f:]+$') + AND image ~ '^[^[:space:]@]+@sha256:[0-9a-f]{64}$' + AND verifier_config_sha256 ~ '^[0-9a-f]{64}$' + AND applicability_matrix_digest ~ '^[0-9a-f]{64}$' + AND expected_outcome IN ('ACCEPT', 'INAPPLICABLE_REJECT') + AND exact_pod_endpoint ~ '^grpcs://[^/?#]+:[0-9]{1,5}$' + AND canonical_service_uri ~ + '^spiffe://firemud/ns/[a-z0-9-]{1,63}/sa/[a-z0-9][a-z0-9-]{0,62}$' + AND expected_pod_leaf_spki_sha256 ~ '^[0-9a-f]{64}$') +); + +CREATE TABLE account_jwt_readiness_pod_receipts ( + rotation_operation_id UUID NOT NULL, + plan_digest VARCHAR(64) NOT NULL, + validator_id VARCHAR(63) NOT NULL, + token_profile VARCHAR(128) NOT NULL, + audience VARCHAR(128) NOT NULL, + probe_kind VARCHAR(16) NOT NULL, + pod_uid UUID NOT NULL, + receipt_version SMALLINT NOT NULL, + jti UUID NOT NULL, + source_entry_version BIGINT NOT NULL, + compact_token_sha256 VARCHAR(64) NOT NULL, + target_generation BIGINT NOT NULL, + target_kid VARCHAR(64) NOT NULL, + expected_active_generation BIGINT, + expected_active_kid VARCHAR(64), + outcome VARCHAR(32) NOT NULL, + observed_pod_uid UUID NOT NULL, + observed_image VARCHAR(512) NOT NULL, + observed_verifier_config_sha256 VARCHAR(64) NOT NULL, + verified_kid VARCHAR(64), + receiver_endpoint VARCHAR(512) NOT NULL, + receiver_service_uri VARCHAR(256) NOT NULL, + receiver_peer_spki_sha256 VARCHAR(64) NOT NULL, + observed_at_epoch_seconds BIGINT NOT NULL, + receipt_sha256 VARCHAR(64) NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (rotation_operation_id, validator_id, token_profile, audience, probe_kind, pod_uid), + CONSTRAINT account_jwt_readiness_pod_receipt_target_fk + FOREIGN KEY (rotation_operation_id, validator_id, token_profile, audience, probe_kind, pod_uid) + REFERENCES account_jwt_readiness_validator_pods( + rotation_operation_id, validator_id, token_profile, audience, probe_kind, pod_uid) + ON DELETE RESTRICT, + CONSTRAINT account_jwt_readiness_pod_receipt_shape_check + CHECK (receipt_version = 1 + AND source_entry_version > 0 + AND compact_token_sha256 ~ '^[0-9a-f]{64}$' + AND target_generation > 0 + AND target_kid ~ '^[A-Za-z0-9_-]{1,64}$' + AND ((expected_active_generation IS NULL AND expected_active_kid IS NULL) + OR (expected_active_generation > 0 + AND expected_active_kid ~ '^[A-Za-z0-9_-]{1,64}$')) + AND target_kid <> expected_active_kid + AND outcome IN ('ACCEPT', 'INAPPLICABLE_REJECT') + AND observed_pod_uid = pod_uid + AND observed_image ~ '^[^[:space:]@]+@sha256:[0-9a-f]{64}$' + AND observed_verifier_config_sha256 ~ '^[0-9a-f]{64}$' + AND (verified_kid IS NULL OR verified_kid = target_kid) + AND receiver_endpoint ~ '^grpcs://[^/?#]+:[0-9]{1,5}$' + AND receiver_service_uri ~ + '^spiffe://firemud/ns/[a-z0-9-]{1,63}/sa/[a-z0-9][a-z0-9-]{0,62}$' + AND receiver_peer_spki_sha256 ~ '^[0-9a-f]{64}$' + AND observed_at_epoch_seconds > 0 + AND receipt_sha256 ~ '^[0-9a-f]{64}$') +); + +-- [jooq ignore start] +CREATE OR REPLACE FUNCTION account_jwt_readiness_plan_inventory_guard() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +DECLARE + matrix jsonb; + account_profiles jsonb; + game_session_profiles jsonb; +BEGIN + matrix := NEW.applicability_matrix_json::jsonb; + IF NEW.plan_version = 1 THEN + IF NEW.validator_inventory_complete + OR matrix ->> 'inventoryStatus' <> 'PARTIAL_UNCONFIRMED' + OR matrix ->> 'schemaVersion' <> '1' + OR jsonb_array_length(matrix -> 'validators') <> 1 + OR matrix #>> '{validators,0,validatorId}' <> 'account-service' + OR jsonb_array_length(matrix #> '{validators,0,applicableProfiles}') <> 3 + OR NOT (matrix #> '{validators,0,applicableProfiles}' @> + '[{"tokenProfile":"control-ui","audience":"control-ui"}]'::jsonb) + OR NOT (matrix #> '{validators,0,applicableProfiles}' @> + '[{"tokenProfile":"player-bootstrap","audience":"player-bootstrap"}]'::jsonb) + OR NOT (matrix #> '{validators,0,applicableProfiles}' @> + '[{"tokenProfile":"game-session-account-delegation","audience":"account-service"}]'::jsonb) THEN + RAISE EXCEPTION 'Legacy readiness plans remain explicitly partial and Account-only' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; + END IF; + + IF NEW.plan_version <> 2 + OR NEW.inventory_snapshot_digest IS NULL + OR matrix ->> 'schemaVersion' <> '2' + OR matrix ->> 'inventorySnapshotDigest' IS DISTINCT FROM NEW.inventory_snapshot_digest + OR jsonb_array_length(matrix -> 'validators') < 1 + OR jsonb_array_length(matrix -> 'validators') > 32 + OR jsonb_array_length(matrix -> 'productionProfiles') <> 3 THEN + RAISE EXCEPTION 'Readiness V2 plan must bind its protected live snapshot and closed profile family' + USING ERRCODE = '23514'; + END IF; + IF NEW.validator_inventory_complete THEN + SELECT value -> 'applicableProfiles' INTO account_profiles + FROM jsonb_array_elements(matrix -> 'validators') AS validator(value) + WHERE value ->> 'validatorId' = 'account-service'; + SELECT value -> 'applicableProfiles' INTO game_session_profiles + FROM jsonb_array_elements(matrix -> 'validators') AS validator(value) + WHERE value ->> 'validatorId' = 'game-session-service'; + IF matrix ->> 'inventoryStatus' <> 'PROTECTED_LIVE_COMPLETE' + OR jsonb_array_length(matrix -> 'validators') <> 2 + OR account_profiles IS NULL + OR jsonb_array_length(account_profiles) <> 3 + OR NOT (account_profiles @> '[{"tokenProfile":"control-ui","audience":"control-ui"}]'::jsonb) + OR NOT (account_profiles @> '[{"tokenProfile":"player-bootstrap","audience":"player-bootstrap"}]'::jsonb) + OR NOT (account_profiles @> '[{"tokenProfile":"game-session-account-delegation","audience":"account-service"}]'::jsonb) + OR game_session_profiles IS NULL + OR jsonb_array_length(game_session_profiles) <> 1 + OR NOT (game_session_profiles @> '[{"tokenProfile":"game-session-account-delegation","audience":"account-service"}]'::jsonb) THEN + RAISE EXCEPTION 'Readiness V2 completion requires exact Account and Game Session profile inventory' + USING ERRCODE = '23514'; + END IF; + ELSIF matrix ->> 'inventoryStatus' <> 'PARTIAL_UNCONFIRMED' THEN + RAISE EXCEPTION 'Incomplete Readiness V2 inventory must remain explicitly partial' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_jwt_readiness_entry_plan_version_guard() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +DECLARE + plan_row account_jwt_readiness_probe_plans%ROWTYPE; +BEGIN + IF TG_OP = 'UPDATE' AND NEW.entry_plan_version IS DISTINCT FROM OLD.entry_plan_version THEN + RAISE EXCEPTION 'Readiness entry schema version is immutable' USING ERRCODE = '23514'; + END IF; + SELECT * INTO plan_row + FROM account_jwt_readiness_probe_plans + WHERE rotation_operation_id = NEW.rotation_operation_id + AND plan_digest = NEW.plan_digest; + IF NOT FOUND OR NEW.entry_plan_version IS DISTINCT FROM plan_row.plan_version THEN + RAISE EXCEPTION 'Readiness entry schema differs from its immutable plan' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER account_jwt_readiness_entry_plan_version_binding + BEFORE INSERT OR UPDATE ON account_jwt_readiness_probe_entries + FOR EACH ROW EXECUTE FUNCTION account_jwt_readiness_entry_plan_version_guard(); + +DROP TRIGGER account_jwt_readiness_entry_lifecycle ON account_jwt_readiness_probe_entries; +CREATE TRIGGER account_jwt_readiness_entry_lifecycle_v1 + BEFORE INSERT OR UPDATE ON account_jwt_readiness_probe_entries + FOR EACH ROW WHEN (NEW.entry_plan_version = 1) + EXECUTE FUNCTION account_jwt_readiness_entry_lifecycle_guard(); +CREATE TRIGGER account_jwt_readiness_entry_delete_guard + BEFORE DELETE ON account_jwt_readiness_probe_entries + FOR EACH ROW EXECUTE FUNCTION account_jwt_readiness_entry_lifecycle_guard(); + +CREATE FUNCTION account_jwt_readiness_expected_pod_guard() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +DECLARE + plan_row account_jwt_readiness_probe_plans%ROWTYPE; + entry_row account_jwt_readiness_probe_entries%ROWTYPE; + snapshot_json jsonb; + validator_json jsonb; + pod_json jsonb; + expected_outcome_value text; +BEGIN + IF TG_OP <> 'INSERT' THEN + RAISE EXCEPTION 'Expected readiness Pod bindings are immutable' USING ERRCODE = '23514'; + END IF; + SELECT * INTO plan_row + FROM account_jwt_readiness_probe_plans + WHERE rotation_operation_id = NEW.rotation_operation_id + AND plan_digest = NEW.plan_digest; + SELECT * INTO entry_row + FROM account_jwt_readiness_probe_entries + WHERE rotation_operation_id = NEW.rotation_operation_id + AND validator_id = NEW.validator_id + AND token_profile = NEW.token_profile + AND audience = NEW.audience + AND probe_kind = NEW.probe_kind; + SELECT convert_from(canonical_snapshot, 'UTF8')::jsonb INTO snapshot_json + FROM account_jwt_validator_inventory_snapshots + WHERE snapshot_digest = NEW.inventory_snapshot_digest; + IF NOT FOUND OR plan_row.plan_version <> 2 OR entry_row.entry_plan_version <> 2 + OR entry_row.jti IS DISTINCT FROM NEW.jti + OR plan_row.inventory_snapshot_digest IS DISTINCT FROM NEW.inventory_snapshot_digest + OR plan_row.applicability_matrix_digest IS DISTINCT FROM NEW.applicability_matrix_digest + OR (plan_row.environment_id, plan_row.cluster_id, plan_row.kubernetes_namespace, + plan_row.expected_cluster_incarnation_uid, plan_row.expected_namespace_uid) + IS DISTINCT FROM (NEW.environment_id, NEW.cluster_id, NEW.kubernetes_namespace, + NEW.cluster_incarnation_uid, NEW.namespace_uid) + OR NOT EXISTS ( + SELECT 1 + FROM jsonb_array_elements(snapshot_json -> 'validators') AS validator(value) + CROSS JOIN LATERAL jsonb_array_elements(validator.value -> 'pods') AS pod(value) + WHERE validator.value ->> 'validatorId' = NEW.validator_id + AND validator.value ->> 'deploymentUid' = NEW.deployment_uid::text + AND pod.value ->> 'uid' = NEW.pod_uid::text + AND pod.value ->> 'podIp' = NEW.pod_ip + AND pod.value ->> 'exactPodEndpoint' = NEW.exact_pod_endpoint + AND pod.value ->> 'canonicalServiceUri' = NEW.canonical_service_uri + AND pod.value ->> 'leafSpkiSha256' = NEW.expected_pod_leaf_spki_sha256 + AND pod.value ->> 'image' = NEW.image + AND pod.value ->> 'verifierConfigSha256' = NEW.verifier_config_sha256 + AND validator.value ->> 'image' = NEW.image + AND validator.value ->> 'verifierConfigSha256' = NEW.verifier_config_sha256) + OR (NEW.probe_kind = 'CANARY' AND NEW.expected_outcome <> 'ACCEPT') + OR (NEW.probe_kind = 'REPRESENTATIVE' AND ( + (NEW.expected_outcome = 'ACCEPT') IS DISTINCT FROM EXISTS ( + SELECT 1 + FROM jsonb_array_elements(snapshot_json -> 'validators') AS validator(value) + CROSS JOIN LATERAL jsonb_array_elements(validator.value -> 'profiles') AS profile(value) + WHERE validator.value ->> 'validatorId' = NEW.validator_id + AND profile.value ->> 'tokenProfile' = NEW.token_profile + AND profile.value ->> 'audience' = NEW.audience))) THEN + RAISE EXCEPTION 'Expected readiness Pod differs from its exact protected inventory and entry' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER account_jwt_readiness_expected_pod_insert_guard + BEFORE INSERT OR UPDATE OR DELETE ON account_jwt_readiness_validator_pods + FOR EACH ROW EXECUTE FUNCTION account_jwt_readiness_expected_pod_guard(); + +CREATE FUNCTION account_jwt_readiness_pod_receipt_guard() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +DECLARE + plan_row account_jwt_readiness_probe_plans%ROWTYPE; + entry_row account_jwt_readiness_probe_entries%ROWTYPE; + pod_row account_jwt_readiness_validator_pods%ROWTYPE; +BEGIN + IF TG_OP <> 'INSERT' THEN + RAISE EXCEPTION 'Readiness Pod verification receipts are immutable' USING ERRCODE = '23514'; + END IF; + SELECT * INTO plan_row + FROM account_jwt_readiness_probe_plans + WHERE rotation_operation_id = NEW.rotation_operation_id + AND plan_digest = NEW.plan_digest; + SELECT * INTO entry_row + FROM account_jwt_readiness_probe_entries + WHERE rotation_operation_id = NEW.rotation_operation_id + AND validator_id = NEW.validator_id + AND token_profile = NEW.token_profile + AND audience = NEW.audience + AND probe_kind = NEW.probe_kind + FOR UPDATE; + SELECT * INTO pod_row + FROM account_jwt_readiness_validator_pods + WHERE rotation_operation_id = NEW.rotation_operation_id + AND validator_id = NEW.validator_id + AND token_profile = NEW.token_profile + AND audience = NEW.audience + AND probe_kind = NEW.probe_kind + AND pod_uid = NEW.pod_uid + FOR KEY SHARE; + IF plan_row.plan_version <> 2 OR plan_row.validator_inventory_complete IS DISTINCT FROM TRUE + OR entry_row.entry_plan_version <> 2 OR entry_row.state <> 'ISSUED' + OR entry_row.jti IS DISTINCT FROM NEW.jti + OR entry_row.entry_version IS DISTINCT FROM NEW.source_entry_version + OR entry_row.compact_token_sha256 IS DISTINCT FROM NEW.compact_token_sha256 + OR entry_row.target_generation IS DISTINCT FROM NEW.target_generation + OR entry_row.target_kid IS DISTINCT FROM NEW.target_kid + OR entry_row.expected_active_generation IS DISTINCT FROM NEW.expected_active_generation + OR entry_row.expected_active_kid IS DISTINCT FROM NEW.expected_active_kid + OR pod_row.expected_outcome IS DISTINCT FROM NEW.outcome + OR pod_row.exact_pod_endpoint IS NULL + OR pod_row.exact_pod_endpoint IS DISTINCT FROM NEW.receiver_endpoint + OR pod_row.canonical_service_uri IS DISTINCT FROM NEW.receiver_service_uri + OR pod_row.expected_pod_leaf_spki_sha256 IS DISTINCT FROM NEW.receiver_peer_spki_sha256 + OR pod_row.pod_uid IS DISTINCT FROM NEW.observed_pod_uid + OR pod_row.image IS DISTINCT FROM NEW.observed_image + OR pod_row.verifier_config_sha256 IS DISTINCT FROM NEW.observed_verifier_config_sha256 + OR NEW.verified_kid IS DISTINCT FROM NEW.target_kid + OR NEW.observed_at_epoch_seconds < entry_row.planned_issued_at_epoch_seconds + OR NEW.observed_at_epoch_seconds >= entry_row.expires_at_epoch_seconds + OR NEW.observed_at_epoch_seconds > floor(extract(epoch FROM CURRENT_TIMESTAMP))::BIGINT + OR CURRENT_TIMESTAMP < to_timestamp(entry_row.planned_issued_at_epoch_seconds) + OR CURRENT_TIMESTAMP >= to_timestamp(entry_row.expires_at_epoch_seconds) THEN + RAISE EXCEPTION 'Readiness Pod receipt differs from exact current inventory, probe, or TLS identity' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER account_jwt_readiness_pod_receipt_insert_guard + BEFORE INSERT OR UPDATE OR DELETE ON account_jwt_readiness_pod_receipts + FOR EACH ROW EXECUTE FUNCTION account_jwt_readiness_pod_receipt_guard(); + +CREATE FUNCTION account_jwt_readiness_entry_v2_lifecycle_guard() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +DECLARE + plan_row account_jwt_readiness_probe_plans%ROWTYPE; + expected_pod_count integer; + receipt_count integer; +BEGIN + IF TG_OP = 'INSERT' THEN + SELECT * INTO plan_row + FROM account_jwt_readiness_probe_plans + WHERE rotation_operation_id = NEW.rotation_operation_id + AND plan_digest = NEW.plan_digest; + IF NOT FOUND OR plan_row.plan_version <> 2 + OR NEW.state <> 'PLANNED' + OR NEW.entry_version <> 1 + OR NEW.registry_version <> 1 + OR NEW.terminal_outcome IS NOT NULL + OR NEW.compact_token_sha256 IS NOT NULL + OR NEW.signing_attempted_at_epoch_seconds IS NOT NULL + OR NEW.verification_receipt_sha256 IS NOT NULL + OR NEW.target_generation IS DISTINCT FROM plan_row.target_generation + OR NEW.target_kid IS DISTINCT FROM plan_row.target_kid + OR NEW.expected_active_generation IS DISTINCT FROM plan_row.expected_active_generation + OR NEW.expected_active_kid IS DISTINCT FROM plan_row.expected_active_kid + OR NEW.planned_issued_at_epoch_seconds IS DISTINCT FROM plan_row.not_before_epoch_seconds + OR NEW.expires_at_epoch_seconds IS DISTINCT FROM plan_row.expires_at_epoch_seconds THEN + RAISE EXCEPTION 'Readiness V2 entry differs from its immutable plan' + USING ERRCODE = '23514'; + END IF; + IF NEW.probe_kind = 'CANARY' THEN + IF NEW.token_profile <> 'account-jwt-readiness-canary' + OR NEW.audience <> 'firemud-account-jwt-readiness' + OR NOT EXISTS (SELECT 1 FROM jsonb_array_elements(plan_row.applicability_matrix_json::jsonb -> 'validators') AS v(value) + WHERE v.value ->> 'validatorId' = NEW.validator_id) THEN + RAISE EXCEPTION 'Readiness V2 canary entry is outside the closed validator set' + USING ERRCODE = '23514'; + END IF; + ELSIF NOT EXISTS ( + SELECT 1 + FROM jsonb_array_elements(plan_row.applicability_matrix_json::jsonb -> 'validators') AS v(value) + CROSS JOIN LATERAL jsonb_array_elements(plan_row.applicability_matrix_json::jsonb -> 'productionProfiles') AS p(value) + WHERE v.value ->> 'validatorId' = NEW.validator_id + AND p.value ->> 'tokenProfile' = NEW.token_profile + AND p.value ->> 'audience' = NEW.audience) THEN + RAISE EXCEPTION 'Readiness V2 representative entry is outside its exact profile matrix' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; + END IF; + + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'Account JWT readiness evidence is retained' USING ERRCODE = '23514'; + END IF; + IF OLD.entry_plan_version <> 2 OR NEW.entry_plan_version <> 2 + OR NEW.rotation_operation_id IS DISTINCT FROM OLD.rotation_operation_id + OR NEW.plan_digest IS DISTINCT FROM OLD.plan_digest + OR NEW.validator_id IS DISTINCT FROM OLD.validator_id + OR NEW.token_profile IS DISTINCT FROM OLD.token_profile + OR NEW.audience IS DISTINCT FROM OLD.audience + OR NEW.probe_kind IS DISTINCT FROM OLD.probe_kind + OR NEW.jti IS DISTINCT FROM OLD.jti + OR NEW.target_generation IS DISTINCT FROM OLD.target_generation + OR NEW.target_kid IS DISTINCT FROM OLD.target_kid + OR NEW.expected_active_generation IS DISTINCT FROM OLD.expected_active_generation + OR NEW.expected_active_kid IS DISTINCT FROM OLD.expected_active_kid + OR NEW.registry_version IS DISTINCT FROM OLD.registry_version + OR NEW.planned_issued_at_epoch_seconds IS DISTINCT FROM OLD.planned_issued_at_epoch_seconds + OR NEW.expires_at_epoch_seconds IS DISTINCT FROM OLD.expires_at_epoch_seconds + OR NEW.entry_version <> OLD.entry_version + 1 THEN + RAISE EXCEPTION 'Readiness V2 entry identity/version is immutable except for one exact transition' + USING ERRCODE = '23514'; + END IF; + IF OLD.state = 'PLANNED' AND NEW.state = 'PLANNED' + AND OLD.compact_token_sha256 IS NULL + AND NEW.compact_token_sha256 IS NOT NULL + AND NEW.signing_attempted_at_epoch_seconds IS NOT NULL + AND NEW.signing_attempted_at_epoch_seconds >= OLD.planned_issued_at_epoch_seconds + AND NEW.signing_attempted_at_epoch_seconds < OLD.expires_at_epoch_seconds + AND NEW.verification_receipt_sha256 IS NULL + AND CURRENT_TIMESTAMP >= to_timestamp(OLD.planned_issued_at_epoch_seconds) + AND CURRENT_TIMESTAMP < to_timestamp(OLD.expires_at_epoch_seconds) + AND NEW.terminal_outcome IS NULL THEN + RETURN NEW; + END IF; + IF OLD.state = 'PLANNED' AND NEW.state = 'ISSUED' + AND OLD.compact_token_sha256 IS NOT NULL + AND NEW.compact_token_sha256 = OLD.compact_token_sha256 + AND NEW.signing_attempted_at_epoch_seconds = OLD.signing_attempted_at_epoch_seconds + AND NEW.verification_receipt_sha256 IS NULL + AND CURRENT_TIMESTAMP >= to_timestamp(OLD.planned_issued_at_epoch_seconds) + AND CURRENT_TIMESTAMP < to_timestamp(OLD.expires_at_epoch_seconds) + AND NEW.terminal_outcome IS NULL THEN + RETURN NEW; + END IF; + IF OLD.state = 'ISSUED' AND NEW.state = 'VERIFIED' THEN + SELECT count(*) INTO expected_pod_count + FROM account_jwt_readiness_validator_pods + WHERE rotation_operation_id = NEW.rotation_operation_id + AND validator_id = NEW.validator_id + AND token_profile = NEW.token_profile + AND audience = NEW.audience + AND probe_kind = NEW.probe_kind; + SELECT count(*) INTO receipt_count + FROM account_jwt_readiness_pod_receipts + WHERE rotation_operation_id = NEW.rotation_operation_id + AND validator_id = NEW.validator_id + AND token_profile = NEW.token_profile + AND audience = NEW.audience + AND probe_kind = NEW.probe_kind; + IF expected_pod_count <= 0 OR expected_pod_count <> receipt_count + OR NEW.verification_receipt_version IS DISTINCT FROM 2 + OR NEW.verification_source_entry_version IS DISTINCT FROM OLD.entry_version + OR NEW.verification_receipt_sha256 IS NULL + OR NEW.pod_receipt_count IS DISTINCT FROM expected_pod_count + OR NEW.pod_receipt_closure_sha256 IS DISTINCT FROM NEW.verification_receipt_sha256 + OR NEW.entry_version IS DISTINCT FROM OLD.entry_version + 1 + OR NEW.target_kid IS DISTINCT FROM OLD.target_kid + OR NEW.compact_token_sha256 IS DISTINCT FROM OLD.compact_token_sha256 + OR NEW.verified_at_epoch_seconds IS NULL + OR NEW.verified_at_epoch_seconds < OLD.planned_issued_at_epoch_seconds + OR NEW.verified_at_epoch_seconds >= OLD.expires_at_epoch_seconds + OR to_timestamp(NEW.verified_at_epoch_seconds) > CURRENT_TIMESTAMP + OR NEW.validator_instance_id IS NULL + OR NEW.validator_binding_digest IS NULL + OR NEW.validator_config_revision IS NULL + OR NEW.validator_peer_uri IS NULL + OR NEW.validator_peer_spki_sha256 IS NULL + OR CURRENT_TIMESTAMP < to_timestamp(OLD.planned_issued_at_epoch_seconds) + OR CURRENT_TIMESTAMP >= to_timestamp(OLD.expires_at_epoch_seconds) + OR NEW.terminal_outcome IS NOT NULL THEN + RAISE EXCEPTION 'Readiness V2 VERIFIED transition lacks complete exact per-Pod receipts' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; + END IF; + IF OLD.state IN ('PLANNED', 'ISSUED', 'VERIFIED') + AND NEW.state = 'ABORTED' + AND NEW.compact_token_sha256 IS NOT DISTINCT FROM OLD.compact_token_sha256 + AND NEW.signing_attempted_at_epoch_seconds IS NOT DISTINCT FROM OLD.signing_attempted_at_epoch_seconds + AND NEW.verification_receipt_sha256 IS NOT DISTINCT FROM OLD.verification_receipt_sha256 + AND NEW.verification_receipt_version IS NOT DISTINCT FROM OLD.verification_receipt_version + AND NEW.verification_source_entry_version IS NOT DISTINCT FROM OLD.verification_source_entry_version + AND NEW.verified_at_epoch_seconds IS NOT DISTINCT FROM OLD.verified_at_epoch_seconds + AND NEW.verified_kid IS NOT DISTINCT FROM OLD.verified_kid + AND NEW.validator_instance_id IS NOT DISTINCT FROM OLD.validator_instance_id + AND NEW.validator_binding_digest IS NOT DISTINCT FROM OLD.validator_binding_digest + AND NEW.validator_config_revision IS NOT DISTINCT FROM OLD.validator_config_revision + AND NEW.validator_peer_uri IS NOT DISTINCT FROM OLD.validator_peer_uri + AND NEW.validator_peer_spki_sha256 IS NOT DISTINCT FROM OLD.validator_peer_spki_sha256 + AND NEW.pod_receipt_count IS NOT DISTINCT FROM OLD.pod_receipt_count + AND NEW.pod_receipt_closure_sha256 IS NOT DISTINCT FROM OLD.pod_receipt_closure_sha256 + AND NEW.terminal_outcome = 'ABORTED' THEN + RETURN NEW; + END IF; + IF OLD.state IN ('PLANNED', 'ISSUED', 'VERIFIED') + AND NEW.state = 'EXPIRED' + AND CURRENT_TIMESTAMP >= to_timestamp(OLD.expires_at_epoch_seconds) + AND NEW.compact_token_sha256 IS NOT DISTINCT FROM OLD.compact_token_sha256 + AND NEW.signing_attempted_at_epoch_seconds IS NOT DISTINCT FROM OLD.signing_attempted_at_epoch_seconds + AND NEW.verification_receipt_sha256 IS NOT DISTINCT FROM OLD.verification_receipt_sha256 + AND NEW.verification_receipt_version IS NOT DISTINCT FROM OLD.verification_receipt_version + AND NEW.verification_source_entry_version IS NOT DISTINCT FROM OLD.verification_source_entry_version + AND NEW.verified_at_epoch_seconds IS NOT DISTINCT FROM OLD.verified_at_epoch_seconds + AND NEW.verified_kid IS NOT DISTINCT FROM OLD.verified_kid + AND NEW.validator_instance_id IS NOT DISTINCT FROM OLD.validator_instance_id + AND NEW.validator_binding_digest IS NOT DISTINCT FROM OLD.validator_binding_digest + AND NEW.validator_config_revision IS NOT DISTINCT FROM OLD.validator_config_revision + AND NEW.validator_peer_uri IS NOT DISTINCT FROM OLD.validator_peer_uri + AND NEW.validator_peer_spki_sha256 IS NOT DISTINCT FROM OLD.validator_peer_spki_sha256 + AND NEW.pod_receipt_count IS NOT DISTINCT FROM OLD.pod_receipt_count + AND NEW.pod_receipt_closure_sha256 IS NOT DISTINCT FROM OLD.pod_receipt_closure_sha256 + AND NEW.terminal_outcome = 'EXPIRED' THEN + RETURN NEW; + END IF; + IF OLD.state IN ('ABORTED', 'EXPIRED') AND NEW.state = 'CLEANED' + AND NEW.terminal_outcome = OLD.terminal_outcome + AND NEW.compact_token_sha256 IS NOT DISTINCT FROM OLD.compact_token_sha256 + AND NEW.signing_attempted_at_epoch_seconds IS NOT DISTINCT FROM OLD.signing_attempted_at_epoch_seconds + AND NEW.verification_receipt_sha256 IS NOT DISTINCT FROM OLD.verification_receipt_sha256 + AND NEW.verification_receipt_version IS NOT DISTINCT FROM OLD.verification_receipt_version + AND NEW.verification_source_entry_version IS NOT DISTINCT FROM OLD.verification_source_entry_version + AND NEW.verified_at_epoch_seconds IS NOT DISTINCT FROM OLD.verified_at_epoch_seconds + AND NEW.verified_kid IS NOT DISTINCT FROM OLD.verified_kid + AND NEW.validator_instance_id IS NOT DISTINCT FROM OLD.validator_instance_id + AND NEW.validator_binding_digest IS NOT DISTINCT FROM OLD.validator_binding_digest + AND NEW.validator_config_revision IS NOT DISTINCT FROM OLD.validator_config_revision + AND NEW.validator_peer_uri IS NOT DISTINCT FROM OLD.validator_peer_uri + AND NEW.validator_peer_spki_sha256 IS NOT DISTINCT FROM OLD.validator_peer_spki_sha256 + AND NEW.pod_receipt_count IS NOT DISTINCT FROM OLD.pod_receipt_count + AND NEW.pod_receipt_closure_sha256 IS NOT DISTINCT FROM OLD.pod_receipt_closure_sha256 THEN + RETURN NEW; + END IF; + RAISE EXCEPTION 'Account JWT readiness V2 lifecycle transition is unavailable' + USING ERRCODE = '23514'; +END; +$$; + +CREATE TRIGGER account_jwt_readiness_entry_lifecycle_v2 + BEFORE INSERT OR UPDATE ON account_jwt_readiness_probe_entries + FOR EACH ROW WHEN (NEW.entry_plan_version = 2) + EXECUTE FUNCTION account_jwt_readiness_entry_v2_lifecycle_guard(); + +CREATE FUNCTION account_jwt_readiness_inventory_plan_closure_guard() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +DECLARE + operation_id UUID; + plan_row account_jwt_readiness_probe_plans%ROWTYPE; + snapshot_json jsonb; + expected_entry_count integer; + actual_entry_count integer; + expected_pod_count integer; + actual_pod_count integer; +BEGIN + operation_id := CASE WHEN TG_OP = 'DELETE' THEN OLD.rotation_operation_id ELSE NEW.rotation_operation_id END; + SELECT * INTO plan_row FROM account_jwt_readiness_probe_plans WHERE rotation_operation_id = operation_id; + IF NOT FOUND OR plan_row.plan_version <> 2 THEN + RETURN NULL; + END IF; + SELECT convert_from(canonical_snapshot, 'UTF8')::jsonb INTO snapshot_json + FROM account_jwt_validator_inventory_snapshots + WHERE snapshot_digest = plan_row.inventory_snapshot_digest; + IF snapshot_json IS NULL THEN + RAISE EXCEPTION 'Readiness V2 inventory snapshot is missing' USING ERRCODE = '23514'; + END IF; + SELECT count(*) * 4 INTO expected_entry_count + FROM jsonb_array_elements(snapshot_json -> 'validators'); + SELECT count(*) INTO actual_entry_count + FROM account_jwt_readiness_probe_entries + WHERE rotation_operation_id = operation_id AND plan_digest = plan_row.plan_digest; + SELECT COALESCE(sum(jsonb_array_length(validator.value -> 'pods') * 4), 0) + INTO expected_pod_count + FROM jsonb_array_elements(snapshot_json -> 'validators') AS validator(value); + SELECT count(*) INTO actual_pod_count + FROM account_jwt_readiness_validator_pods + WHERE rotation_operation_id = operation_id AND plan_digest = plan_row.plan_digest; + IF actual_entry_count <> expected_entry_count + OR actual_pod_count <> expected_pod_count + OR actual_entry_count > 256 OR actual_pod_count > 256 + OR EXISTS ( + SELECT 1 + FROM jsonb_array_elements(snapshot_json -> 'validators') AS validator(value) + CROSS JOIN LATERAL jsonb_array_elements(plan_row.applicability_matrix_json::jsonb -> 'productionProfiles') AS profile(value) + WHERE NOT EXISTS ( + SELECT 1 FROM account_jwt_readiness_probe_entries entry + WHERE entry.rotation_operation_id = operation_id + AND entry.plan_digest = plan_row.plan_digest + AND entry.validator_id = validator.value ->> 'validatorId' + AND entry.token_profile = profile.value ->> 'tokenProfile' + AND entry.audience = profile.value ->> 'audience' + AND entry.probe_kind = 'REPRESENTATIVE')) + OR EXISTS ( + SELECT 1 + FROM jsonb_array_elements(snapshot_json -> 'validators') AS validator(value) + WHERE NOT EXISTS ( + SELECT 1 FROM account_jwt_readiness_probe_entries entry + WHERE entry.rotation_operation_id = operation_id + AND entry.plan_digest = plan_row.plan_digest + AND entry.validator_id = validator.value ->> 'validatorId' + AND entry.token_profile = 'account-jwt-readiness-canary' + AND entry.audience = 'firemud-account-jwt-readiness' + AND entry.probe_kind = 'CANARY')) + OR EXISTS ( + SELECT 1 + FROM account_jwt_readiness_probe_entries entry + WHERE entry.rotation_operation_id = operation_id + AND entry.plan_digest = plan_row.plan_digest + AND (SELECT count(*) FROM account_jwt_readiness_validator_pods target + WHERE target.rotation_operation_id = entry.rotation_operation_id + AND target.validator_id = entry.validator_id + AND target.token_profile = entry.token_profile + AND target.audience = entry.audience + AND target.probe_kind = entry.probe_kind) + <> (SELECT jsonb_array_length(validator.value -> 'pods') + FROM jsonb_array_elements(snapshot_json -> 'validators') AS validator(value) + WHERE validator.value ->> 'validatorId' = entry.validator_id)) THEN + RAISE EXCEPTION 'Readiness V2 plan is missing a validator entry or exact per-Pod inventory row' + USING ERRCODE = '23514'; + END IF; + RETURN NULL; +END; +$$; + +CREATE CONSTRAINT TRIGGER account_jwt_readiness_plan_v2_closure + AFTER INSERT ON account_jwt_readiness_probe_plans + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW + EXECUTE FUNCTION account_jwt_readiness_inventory_plan_closure_guard(); +CREATE CONSTRAINT TRIGGER account_jwt_readiness_entry_v2_closure + AFTER INSERT ON account_jwt_readiness_probe_entries + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW + EXECUTE FUNCTION account_jwt_readiness_inventory_plan_closure_guard(); +CREATE CONSTRAINT TRIGGER account_jwt_readiness_pod_v2_closure + AFTER INSERT ON account_jwt_readiness_validator_pods + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW + EXECUTE FUNCTION account_jwt_readiness_inventory_plan_closure_guard(); +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V104__account_jwt_signer_promotion_receipt_binding.sql b/services/account-service/src/main/resources/db/migration/V104__account_jwt_signer_promotion_receipt_binding.sql new file mode 100644 index 0000000000..ceb2aa436f --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V104__account_jwt_signer_promotion_receipt_binding.sql @@ -0,0 +1,126 @@ +-- Correct the promotion insert guard's receipt source without adding a duplicate promotion-row +-- field. The immutable readiness plan already binds the generation receipt digest. +-- [jooq ignore start] +CREATE OR REPLACE FUNCTION account_jwt_signer_promotion_insert_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + state_row RECORD; + generation_row RECORD; + result_row RECORD; + plan_generation_receipt_digest VARCHAR(64); + plan_inventory_complete BOOLEAN; + plan_expires_at BIGINT; + entry_count BIGINT; + verified_count BIGINT; +BEGIN + IF NEW.operation_action <> 'PROMOTE_PENDING' + OR NEW.generation_operation_id IS NULL + OR NEW.expected_cluster_incarnation_uid IS NULL + OR NEW.expected_namespace_uid IS NULL + OR NEW.expected_private_secret_uid IS NULL + OR NEW.expected_public_config_map_uid IS NULL THEN + RAISE EXCEPTION 'Promotion request lacks its exact lifecycle binding' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_promotion_insert_binding'; + END IF; + + -- Lock order is desired state, then source generation, then immutable evidence. + SELECT * INTO state_row FROM account_jwt_signer_desired_states + WHERE environment_id = NEW.environment_id FOR UPDATE; + IF NOT FOUND THEN + RAISE EXCEPTION 'Account JWT signer desired state is missing' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_promotion_insert_binding'; + END IF; + SELECT * INTO generation_row FROM account_jwt_signer_generation_operations + WHERE operation_id = NEW.generation_operation_id FOR UPDATE; + IF NOT FOUND THEN + RAISE EXCEPTION 'Account JWT generation operation is missing' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_promotion_insert_binding'; + END IF; + SELECT * INTO result_row FROM account_jwt_signer_generation_results + WHERE operation_id = NEW.generation_operation_id FOR UPDATE; + IF NOT FOUND THEN + RAISE EXCEPTION 'Account JWT generation result is missing' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_promotion_insert_binding'; + END IF; + IF state_row.generation_operation_id IS DISTINCT FROM NEW.generation_operation_id + OR state_row.prepared_operation_id IS NOT NULL + OR state_row.record_version IS DISTINCT FROM NEW.expected_record_version + OR (state_row.cluster_id, state_row.kubernetes_namespace, state_row.custody_mode) + IS DISTINCT FROM (NEW.cluster_id, NEW.kubernetes_namespace, NEW.custody_mode) + OR (state_row.durable_active_generation, state_row.durable_active_kid) + IS DISTINCT FROM (NEW.expected_previous_generation, NEW.expected_previous_kid) + OR (state_row.published_active_generation, state_row.published_active_kid) + IS DISTINCT FROM (NEW.expected_public_active_generation, NEW.expected_public_active_kid) + OR state_row.enrollment_cluster_incarnation_uid IS DISTINCT FROM NEW.expected_cluster_incarnation_uid + OR state_row.enrollment_namespace_uid IS DISTINCT FROM NEW.expected_namespace_uid + OR state_row.enrollment_materializer_binding_digest IS DISTINCT FROM NEW.materializer_trust_binding_digest + OR state_row.enrollment_materializer_config_revision IS DISTINCT FROM NEW.materializer_trust_config_revision + OR state_row.enrollment_api_binding_digest IS DISTINCT FROM NEW.api_binding_digest + OR state_row.enrollment_api_config_revision IS DISTINCT FROM NEW.api_config_revision + OR state_row.enrollment_public_config_map_uid IS DISTINCT FROM NEW.expected_public_config_map_uid + OR generation_row.operation_id IS NULL + OR generation_row.environment_id IS DISTINCT FROM NEW.environment_id + OR generation_row.expected_cluster_incarnation_uid IS DISTINCT FROM NEW.expected_cluster_incarnation_uid + OR generation_row.expected_namespace_uid IS DISTINCT FROM NEW.expected_namespace_uid + OR generation_row.trust_binding_digest IS DISTINCT FROM NEW.materializer_trust_binding_digest + OR generation_row.trust_config_revision IS DISTINCT FROM NEW.materializer_trust_config_revision + OR generation_row.target_generation IS DISTINCT FROM NEW.target_generation + OR generation_row.target_kid IS DISTINCT FROM NEW.target_kid + OR generation_row.expected_record_version + 1 IS DISTINCT FROM result_row.desired_state_version + OR result_row.secret_uid IS DISTINCT FROM NEW.expected_private_secret_uid + OR result_row.observed_resource_version IS DISTINCT FROM NEW.expected_private_secret_resource_version + OR result_row.public_key_fingerprint IS DISTINCT FROM NEW.target_public_key_fingerprint THEN + RAISE EXCEPTION 'JWT promotion request does not match current Account generation evidence' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_promotion_insert_binding'; + END IF; + + SELECT generation_receipt_digest, validator_inventory_complete, expires_at_epoch_seconds + INTO plan_generation_receipt_digest, plan_inventory_complete, plan_expires_at + FROM account_jwt_readiness_probe_plans + WHERE rotation_operation_id = NEW.generation_operation_id + AND plan_digest = NEW.readiness_plan_digest FOR SHARE; + IF plan_generation_receipt_digest IS DISTINCT FROM result_row.receipt_digest + OR plan_inventory_complete IS DISTINCT FROM TRUE + OR plan_expires_at IS NULL + OR plan_expires_at <= floor(extract(epoch FROM CURRENT_TIMESTAMP))::BIGINT THEN + RAISE EXCEPTION 'JWT promotion requires current complete validator inventory proof' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_promotion_readiness_incomplete'; + END IF; + SELECT count(*), count(*) FILTER (WHERE state = 'VERIFIED' + AND verified_at_epoch_seconds < expires_at_epoch_seconds) + INTO entry_count, verified_count + FROM account_jwt_readiness_probe_entries + WHERE rotation_operation_id = NEW.generation_operation_id + AND plan_digest = NEW.readiness_plan_digest; + IF entry_count = 0 OR verified_count <> entry_count THEN + RAISE EXCEPTION 'JWT promotion requires every exact readiness probe to be VERIFIED' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_promotion_readiness_incomplete'; + END IF; + + IF NOT EXISTS ( + SELECT 1 FROM account_jwt_jwks_prepublication_intents AS intent + JOIN account_jwt_jwks_publication_receipts AS receipt + ON receipt.operation_id = intent.operation_id + AND receipt.intent_digest = intent.intent_digest + JOIN account_jwt_jwks_mount_observations AS mount + ON mount.operation_id = intent.operation_id + WHERE intent.operation_id = NEW.generation_operation_id + AND intent.intent_digest = NEW.prepublication_intent_digest + AND receipt.receipt_digest = NEW.prepublication_receipt_digest + AND mount.observation_digest = NEW.mounted_observation_digest + AND intent.config_map_uid = NEW.expected_public_config_map_uid + AND intent.api_binding_digest = NEW.api_binding_digest + AND intent.api_config_revision = NEW.api_config_revision + AND receipt.observed_resource_version = NEW.expected_public_jwks_resource_version + AND intent.public_key_fingerprint = NEW.target_public_key_fingerprint + AND intent.jwks_json = NEW.expected_public_jwks_json) THEN + RAISE EXCEPTION 'JWT promotion request does not match exact current prepublication evidence' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_promotion_insert_binding'; + END IF; + RETURN NEW; +END; +$$; +-- [jooq ignore stop] + diff --git a/services/account-service/src/main/resources/db/migration/V41__account_jwt_signer_desired_state.sql b/services/account-service/src/main/resources/db/migration/V41__account_jwt_signer_desired_state.sql new file mode 100644 index 0000000000..1e71c085a5 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V41__account_jwt_signer_desired_state.sql @@ -0,0 +1,405 @@ +-- Account-owned signer desired state, Account-selected generation requests, and a dormant +-- PREPARED schema for the later lifecycle phase. Generation/materialization evidence is not a +-- PREPARED promotion record and never authorizes signing. +CREATE TABLE account_jwt_signer_desired_states ( + environment_id VARCHAR(63) PRIMARY KEY, + cluster_id VARCHAR(128) NOT NULL, + kubernetes_namespace VARCHAR(63) NOT NULL, + custody_mode VARCHAR(64) NOT NULL, + private_secret_name VARCHAR(63) NOT NULL DEFAULT 'jwt-signing-keys', + public_jwks_config_map_name VARCHAR(63) NOT NULL DEFAULT 'jwt-jwks', + record_version BIGINT NOT NULL DEFAULT 1, + durable_active_generation BIGINT, + durable_active_kid VARCHAR(128), + published_active_generation BIGINT, + published_active_kid VARCHAR(128), + generation_operation_id UUID, + prepared_operation_id UUID, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT account_jwt_signer_state_binding_unique + UNIQUE (environment_id, cluster_id, kubernetes_namespace, custody_mode), + CONSTRAINT account_jwt_signer_state_environment_check + CHECK (environment_id ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$'), + CONSTRAINT account_jwt_signer_state_cluster_check + CHECK (cluster_id ~ '^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$'), + CONSTRAINT account_jwt_signer_state_namespace_check + CHECK (kubernetes_namespace ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$'), + CONSTRAINT account_jwt_signer_state_mode_check + CHECK (custody_mode = 'INTERIM_ACCOUNT_ONLY_MOUNTED_FALLBACK'), + CONSTRAINT account_jwt_signer_state_resource_names_check + CHECK (private_secret_name = 'jwt-signing-keys' + AND public_jwks_config_map_name = 'jwt-jwks'), + CONSTRAINT account_jwt_signer_state_version_check CHECK (record_version > 0), + CONSTRAINT account_jwt_signer_state_durable_active_shape_check + CHECK ((durable_active_generation IS NULL AND durable_active_kid IS NULL) + OR (durable_active_generation IS NOT NULL + AND durable_active_generation > 0 + AND durable_active_kid IS NOT NULL + AND durable_active_kid ~ '^[A-Za-z0-9_-]{1,64}$')), + CONSTRAINT account_jwt_signer_state_published_active_shape_check + CHECK ((published_active_generation IS NULL AND published_active_kid IS NULL) + OR (published_active_generation IS NOT NULL + AND published_active_generation > 0 + AND published_active_kid IS NOT NULL + AND published_active_kid ~ '^[A-Za-z0-9_-]{1,64}$')) +); + +CREATE TABLE account_jwt_signer_promotion_operations ( + operation_id UUID PRIMARY KEY, + environment_id VARCHAR(63) NOT NULL, + cluster_id VARCHAR(128) NOT NULL, + kubernetes_namespace VARCHAR(63) NOT NULL, + custody_mode VARCHAR(64) NOT NULL, + request_digest_version SMALLINT NOT NULL, + request_digest VARCHAR(64) NOT NULL, + expected_record_version BIGINT NOT NULL, + expected_previous_generation BIGINT, + expected_previous_kid VARCHAR(128), + target_generation BIGINT NOT NULL, + target_kid VARCHAR(128) NOT NULL, + target_algorithm VARCHAR(16) NOT NULL, + target_public_key_fingerprint VARCHAR(64) NOT NULL, + expected_private_secret_resource_version VARCHAR(256) NOT NULL, + expected_public_jwks_resource_version VARCHAR(256) NOT NULL, + expected_public_active_generation BIGINT, + expected_public_active_kid VARCHAR(128), + operation_action VARCHAR(32) NOT NULL, + allowed_private_slots_canonical_bytes BYTEA NOT NULL, + status VARCHAR(16) NOT NULL DEFAULT 'PREPARED', + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT account_jwt_signer_promotion_operation_state_fk + FOREIGN KEY (environment_id) + REFERENCES account_jwt_signer_desired_states(environment_id) + ON DELETE RESTRICT, + CONSTRAINT account_jwt_signer_promotion_exact_binding_fk + FOREIGN KEY (environment_id, cluster_id, kubernetes_namespace, custody_mode) + REFERENCES account_jwt_signer_desired_states( + environment_id, cluster_id, kubernetes_namespace, custody_mode) + ON DELETE RESTRICT, + CONSTRAINT account_jwt_signer_promotion_cluster_check + CHECK (cluster_id ~ '^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$'), + CONSTRAINT account_jwt_signer_promotion_namespace_check + CHECK (kubernetes_namespace ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$'), + CONSTRAINT account_jwt_signer_promotion_mode_check + CHECK (custody_mode = 'INTERIM_ACCOUNT_ONLY_MOUNTED_FALLBACK'), + CONSTRAINT account_jwt_signer_promotion_id_v4_check + CHECK (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}$'), + CONSTRAINT account_jwt_signer_promotion_digest_check + CHECK (request_digest_version = 1 AND request_digest ~ '^[0-9a-f]{64}$'), + CONSTRAINT account_jwt_signer_promotion_record_version_check + CHECK (expected_record_version > 0 + AND expected_record_version < 9223372036854775807), + CONSTRAINT account_jwt_signer_promotion_previous_shape_check + CHECK ((expected_previous_generation IS NULL AND expected_previous_kid IS NULL) + OR (expected_previous_generation IS NOT NULL + AND expected_previous_generation > 0 + AND expected_previous_kid IS NOT NULL + AND expected_previous_kid ~ '^[A-Za-z0-9_-]{1,64}$')), + CONSTRAINT account_jwt_signer_promotion_target_check + CHECK (target_generation > 0 + AND target_kid ~ '^[A-Za-z0-9_-]{1,64}$' + AND (expected_previous_generation IS NULL + OR (expected_previous_generation IS NOT NULL + AND target_generation > expected_previous_generation + AND target_kid <> expected_previous_kid))), + CONSTRAINT account_jwt_signer_promotion_algorithm_check + CHECK (target_algorithm = 'RS256'), + CONSTRAINT account_jwt_signer_promotion_fingerprint_check + CHECK (target_public_key_fingerprint ~ '^[0-9a-f]{64}$'), + CONSTRAINT account_jwt_signer_promotion_resource_versions_check + CHECK (expected_private_secret_resource_version ~ '^[!-~]+$' + AND char_length(expected_private_secret_resource_version) BETWEEN 1 AND 256 + AND expected_public_jwks_resource_version ~ '^[!-~]+$' + AND char_length(expected_public_jwks_resource_version) BETWEEN 1 AND 256), + CONSTRAINT account_jwt_signer_promotion_public_active_shape_check + CHECK ((expected_public_active_generation IS NULL AND expected_public_active_kid IS NULL) + OR (expected_public_active_generation IS NOT NULL + AND expected_public_active_generation > 0 + AND expected_public_active_kid IS NOT NULL + AND expected_public_active_kid ~ '^[A-Za-z0-9_-]{1,64}$')), + CONSTRAINT account_jwt_signer_promotion_published_generation_check + CHECK (expected_public_active_generation IS NULL + OR (target_generation > expected_public_active_generation + AND target_kid <> expected_public_active_kid)), + CONSTRAINT account_jwt_signer_promotion_action_check + CHECK (operation_action = 'MATERIALIZE_PENDING'), + CONSTRAINT account_jwt_signer_promotion_slots_check + CHECK (allowed_private_slots_canonical_bytes = '\x5b2270656e64696e67225d'::bytea), + CONSTRAINT account_jwt_signer_promotion_status_check CHECK (status = 'PREPARED') +); + +ALTER TABLE account_jwt_signer_desired_states + ADD CONSTRAINT account_jwt_signer_state_prepared_operation_fk + FOREIGN KEY (prepared_operation_id) + REFERENCES account_jwt_signer_promotion_operations(operation_id) + ON DELETE RESTRICT; + +CREATE TABLE account_jwt_signer_generation_operations ( + operation_id UUID PRIMARY KEY, + environment_id VARCHAR(63) NOT NULL, + cluster_id VARCHAR(128) NOT NULL, + kubernetes_namespace VARCHAR(63) NOT NULL, + custody_mode VARCHAR(64) NOT NULL, + operation_digest_version SMALLINT NOT NULL, + operation_digest VARCHAR(64) NOT NULL, + expected_record_version BIGINT NOT NULL, + expected_previous_generation BIGINT, + expected_previous_kid VARCHAR(128), + expected_published_generation BIGINT, + expected_published_kid VARCHAR(128), + target_generation BIGINT NOT NULL, + target_kid VARCHAR(64) NOT NULL, + target_algorithm VARCHAR(16) NOT NULL, + expected_cluster_incarnation_uid UUID NOT NULL, + expected_namespace_uid UUID NOT NULL, + trust_binding_digest VARCHAR(64) NOT NULL, + trust_config_revision VARCHAR(128) NOT NULL, + operation_action VARCHAR(32) NOT NULL, + allowed_private_slots_canonical_bytes BYTEA NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT account_jwt_signer_generation_state_fk + FOREIGN KEY (environment_id) + REFERENCES account_jwt_signer_desired_states(environment_id) + ON DELETE RESTRICT, + CONSTRAINT account_jwt_signer_generation_exact_binding_fk + FOREIGN KEY (environment_id, cluster_id, kubernetes_namespace, custody_mode) + REFERENCES account_jwt_signer_desired_states( + environment_id, cluster_id, kubernetes_namespace, custody_mode) + ON DELETE RESTRICT, + CONSTRAINT account_jwt_signer_generation_binding_unique + UNIQUE (operation_id, environment_id, cluster_id, kubernetes_namespace, custody_mode, + operation_digest, expected_record_version, target_generation, target_kid, + expected_published_generation, expected_published_kid, target_algorithm, + expected_cluster_incarnation_uid, expected_namespace_uid, + trust_binding_digest, trust_config_revision), + CONSTRAINT account_jwt_signer_generation_observation_binding_unique + UNIQUE (operation_id, environment_id, cluster_id, kubernetes_namespace, custody_mode, + operation_digest, expected_record_version, expected_cluster_incarnation_uid, + expected_namespace_uid, trust_binding_digest, trust_config_revision), + CONSTRAINT account_jwt_signer_generation_receipt_binding_unique + UNIQUE (operation_id, environment_id, cluster_id, kubernetes_namespace, custody_mode, + operation_digest, target_generation, target_kid, target_algorithm, + expected_cluster_incarnation_uid, expected_namespace_uid, + trust_binding_digest, trust_config_revision), + CONSTRAINT account_jwt_signer_generation_id_v4_check + CHECK (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}$'), + CONSTRAINT account_jwt_signer_generation_binding_check + CHECK (cluster_id ~ '^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$' + AND kubernetes_namespace ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$' + AND custody_mode = 'INTERIM_ACCOUNT_ONLY_MOUNTED_FALLBACK'), + CONSTRAINT account_jwt_signer_generation_digest_check + CHECK (operation_digest_version = 1 AND operation_digest ~ '^[0-9a-f]{64}$'), + CONSTRAINT account_jwt_signer_generation_state_version_check + CHECK (expected_record_version > 0 AND expected_record_version < 9223372036854775807), + CONSTRAINT account_jwt_signer_generation_previous_shape_check + CHECK ((expected_previous_generation IS NULL AND expected_previous_kid IS NULL) + OR (expected_previous_generation IS NOT NULL AND expected_previous_generation > 0 + AND expected_previous_kid IS NOT NULL + AND expected_previous_kid ~ '^[A-Za-z0-9_-]{1,64}$')), + CONSTRAINT account_jwt_signer_generation_target_check + CHECK (target_generation > 0 + AND target_kid ~ '^[A-Za-z0-9_-]{1,64}$' + AND (expected_previous_generation IS NULL + OR (target_generation > expected_previous_generation + AND target_kid <> expected_previous_kid))), + CONSTRAINT account_jwt_signer_generation_algorithm_check + CHECK (target_algorithm = 'RS256'), + CONSTRAINT account_jwt_signer_generation_published_shape_check + CHECK ((expected_published_generation IS NULL AND expected_published_kid IS NULL) + OR (expected_published_generation IS NOT NULL AND expected_published_generation > 0 + AND expected_published_kid IS NOT NULL + AND expected_published_kid ~ '^[A-Za-z0-9_-]{1,64}$')), + CONSTRAINT account_jwt_signer_generation_trust_check + CHECK (expected_cluster_incarnation_uid <> '00000000-0000-0000-0000-000000000000'::UUID + AND expected_namespace_uid <> '00000000-0000-0000-0000-000000000000'::UUID + AND trust_binding_digest ~ '^[0-9a-f]{64}$' + AND trust_config_revision ~ '^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$'), + CONSTRAINT account_jwt_signer_generation_action_check + CHECK (operation_action = 'MATERIALIZE_PENDING'), + CONSTRAINT account_jwt_signer_generation_slots_check + CHECK (allowed_private_slots_canonical_bytes = '\x5b2270656e64696e67225d'::bytea) +); + +ALTER TABLE account_jwt_signer_desired_states + ADD CONSTRAINT account_jwt_signer_state_generation_operation_fk + FOREIGN KEY (generation_operation_id) + REFERENCES account_jwt_signer_generation_operations(operation_id) + ON DELETE RESTRICT; + +CREATE UNIQUE INDEX account_jwt_signer_generation_target_once + ON account_jwt_signer_generation_operations (environment_id, target_generation); + +CREATE UNIQUE INDEX account_jwt_signer_generation_kid_once + ON account_jwt_signer_generation_operations (environment_id, target_kid); + +CREATE UNIQUE INDEX account_jwt_signer_one_prepared_operation_per_environment + ON account_jwt_signer_promotion_operations (environment_id) + WHERE status = 'PREPARED'; + +CREATE UNIQUE INDEX account_jwt_signer_target_generation_once + ON account_jwt_signer_promotion_operations (environment_id, target_generation); + +CREATE UNIQUE INDEX account_jwt_signer_target_kid_once + ON account_jwt_signer_promotion_operations (environment_id, target_kid); + +-- [jooq ignore start] +CREATE FUNCTION account_jwt_signer_desired_state_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + operation_environment VARCHAR(63); + operation_expected_version BIGINT; + operation_previous_generation BIGINT; + operation_previous_kid VARCHAR(128); + operation_published_generation BIGINT; + operation_published_kid VARCHAR(128); + operation_status VARCHAR(16); + operation_cluster VARCHAR(128); + operation_namespace VARCHAR(63); + operation_mode VARCHAR(64); + operation_target_generation BIGINT; + operation_target_kid VARCHAR(64); + operation_algorithm VARCHAR(16); + operation_cluster_uid UUID; + operation_namespace_uid UUID; + operation_trust_digest VARCHAR(64); + operation_trust_revision VARCHAR(128); +BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'Account JWT signer desired state cannot be deleted' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_desired_state_immutable'; + END IF; + + IF NEW.environment_id IS DISTINCT FROM OLD.environment_id + OR NEW.cluster_id IS DISTINCT FROM OLD.cluster_id + OR NEW.kubernetes_namespace IS DISTINCT FROM OLD.kubernetes_namespace + OR NEW.custody_mode IS DISTINCT FROM OLD.custody_mode + OR NEW.private_secret_name IS DISTINCT FROM OLD.private_secret_name + OR NEW.public_jwks_config_map_name IS DISTINCT FROM OLD.public_jwks_config_map_name + OR NEW.durable_active_generation IS DISTINCT FROM OLD.durable_active_generation + OR NEW.durable_active_kid IS DISTINCT FROM OLD.durable_active_kid + OR NEW.published_active_generation IS DISTINCT FROM OLD.published_active_generation + OR NEW.published_active_kid IS DISTINCT FROM OLD.published_active_kid + OR NEW.created_at IS DISTINCT FROM OLD.created_at + OR NEW.record_version <> OLD.record_version + 1 THEN + RAISE EXCEPTION 'Account JWT signer desired state permits only a versioned owner transition' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_desired_state_immutable'; + END IF; + + IF NEW.prepared_operation_id IS DISTINCT FROM OLD.prepared_operation_id THEN + RAISE EXCEPTION 'JWT signer promotion prerequisites are incomplete' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_prepared_operation_binding'; + END IF; + + IF OLD.generation_operation_id IS NOT NULL + OR NEW.generation_operation_id IS NULL + OR OLD.prepared_operation_id IS NOT NULL + OR NEW.prepared_operation_id IS NOT NULL THEN + RAISE EXCEPTION 'Account JWT signer generation operation is already fenced or not promotable' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_generation_operation_binding'; + END IF; + + SELECT environment_id, cluster_id, kubernetes_namespace, custody_mode, + expected_record_version, expected_previous_generation, expected_previous_kid, + expected_published_generation, expected_published_kid, + target_generation, target_kid, target_algorithm, + expected_cluster_incarnation_uid, expected_namespace_uid, + trust_binding_digest, trust_config_revision + INTO operation_environment, operation_cluster, operation_namespace, operation_mode, + operation_expected_version, operation_previous_generation, operation_previous_kid, + operation_published_generation, operation_published_kid, + operation_target_generation, operation_target_kid, operation_algorithm, + operation_cluster_uid, operation_namespace_uid, + operation_trust_digest, operation_trust_revision + FROM account_jwt_signer_generation_operations + WHERE operation_id = NEW.generation_operation_id; + IF operation_environment IS DISTINCT FROM NEW.environment_id + OR operation_cluster IS DISTINCT FROM NEW.cluster_id + OR operation_namespace IS DISTINCT FROM NEW.kubernetes_namespace + OR operation_mode IS DISTINCT FROM NEW.custody_mode + OR operation_expected_version IS DISTINCT FROM OLD.record_version + OR operation_previous_generation IS DISTINCT FROM OLD.durable_active_generation + OR operation_previous_kid IS DISTINCT FROM OLD.durable_active_kid + OR operation_published_generation IS DISTINCT FROM OLD.published_active_generation + OR operation_published_kid IS DISTINCT FROM OLD.published_active_kid + OR operation_algorithm IS DISTINCT FROM 'RS256' + OR operation_cluster_uid IS NULL OR operation_namespace_uid IS NULL + OR operation_trust_digest IS NULL OR operation_trust_revision IS NULL THEN + RAISE EXCEPTION 'Account JWT signer state must point to its exact owner-selected generation operation' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_generation_operation_binding'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_jwt_signer_desired_state_no_truncate() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'Account JWT signer desired state cannot be truncated' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_desired_state_immutable'; + RETURN NULL; +END; +$$; + +CREATE FUNCTION account_jwt_signer_operation_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'Account JWT signer operation history is immutable and PREPARED-only' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_operation_immutable'; + RETURN NULL; +END; +$$; + +CREATE FUNCTION account_jwt_signer_operation_no_truncate() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'Account JWT signer operation history cannot be truncated' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_operation_immutable'; + RETURN NULL; +END; +$$; + +CREATE FUNCTION account_jwt_signer_generation_operation_immutable() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'Account JWT signer generation operation is immutable' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_generation_operation_immutable'; + RETURN NULL; +END; +$$; + +CREATE TRIGGER account_jwt_signer_desired_state_guard + BEFORE UPDATE OR DELETE ON account_jwt_signer_desired_states + FOR EACH ROW EXECUTE FUNCTION account_jwt_signer_desired_state_guard(); + +CREATE TRIGGER account_jwt_signer_desired_state_no_truncate + BEFORE TRUNCATE ON account_jwt_signer_desired_states + FOR EACH STATEMENT EXECUTE FUNCTION account_jwt_signer_desired_state_no_truncate(); + +CREATE TRIGGER account_jwt_signer_operation_guard + BEFORE UPDATE OR DELETE ON account_jwt_signer_promotion_operations + FOR EACH ROW EXECUTE FUNCTION account_jwt_signer_operation_guard(); + +CREATE TRIGGER account_jwt_signer_operation_no_truncate + BEFORE TRUNCATE ON account_jwt_signer_promotion_operations + FOR EACH STATEMENT EXECUTE FUNCTION account_jwt_signer_operation_no_truncate(); + +CREATE TRIGGER account_jwt_signer_generation_operation_immutable + BEFORE UPDATE OR DELETE ON account_jwt_signer_generation_operations + FOR EACH ROW EXECUTE FUNCTION account_jwt_signer_generation_operation_immutable(); + +CREATE TRIGGER account_jwt_signer_generation_operation_no_truncate + BEFORE TRUNCATE ON account_jwt_signer_generation_operations + FOR EACH STATEMENT EXECUTE FUNCTION account_jwt_signer_generation_operation_immutable(); +-- [jooq ignore stop] + diff --git a/services/account-service/src/main/resources/db/migration/V42__account_jwt_signer_materialization_readback.sql b/services/account-service/src/main/resources/db/migration/V42__account_jwt_signer_materialization_readback.sql new file mode 100644 index 0000000000..baab6841bd --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V42__account_jwt_signer_materialization_readback.sql @@ -0,0 +1,327 @@ +-- Immutable Account-bound reports for the fixed private Secret. The first report observes only +-- the fixed-name pre-created Secret; the second records one pending-key generation/CAS result. +-- Neither report changes active state, PREPARED state, JWKS, token signing, or readiness. +CREATE TABLE account_jwt_signer_secret_observations ( + operation_id UUID PRIMARY KEY, + environment_id VARCHAR(63) NOT NULL, + cluster_id VARCHAR(128) NOT NULL, + kubernetes_namespace VARCHAR(63) NOT NULL, + custody_mode VARCHAR(64) NOT NULL, + operation_digest_version SMALLINT NOT NULL, + operation_digest VARCHAR(64) NOT NULL, + expected_record_version BIGINT NOT NULL, + expected_cluster_incarnation_uid UUID NOT NULL, + expected_namespace_uid UUID NOT NULL, + trust_binding_digest VARCHAR(64) NOT NULL, + trust_config_revision VARCHAR(128) NOT NULL, + private_secret_name VARCHAR(63) NOT NULL, + secret_uid UUID NOT NULL, + observed_resource_version VARCHAR(256) NOT NULL, + observation_digest_version SMALLINT NOT NULL, + observation_digest VARCHAR(64) NOT NULL, + generation_request_digest VARCHAR(64) NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT account_jwt_signer_observation_exact_state_fk + FOREIGN KEY (environment_id, cluster_id, kubernetes_namespace, custody_mode) + REFERENCES account_jwt_signer_desired_states( + environment_id, cluster_id, kubernetes_namespace, custody_mode) + ON DELETE RESTRICT, + CONSTRAINT account_jwt_signer_observation_exact_operation_fk + FOREIGN KEY (operation_id, environment_id, cluster_id, kubernetes_namespace, + custody_mode, operation_digest, expected_record_version, + expected_cluster_incarnation_uid, expected_namespace_uid, + trust_binding_digest, trust_config_revision) + REFERENCES account_jwt_signer_generation_operations( + operation_id, environment_id, cluster_id, kubernetes_namespace, custody_mode, + operation_digest, expected_record_version, expected_cluster_incarnation_uid, + expected_namespace_uid, trust_binding_digest, trust_config_revision) + ON DELETE RESTRICT, + CONSTRAINT account_jwt_signer_observation_readback_unique + UNIQUE (operation_id, operation_digest, generation_request_digest, + secret_uid, observed_resource_version), + CONSTRAINT account_jwt_signer_observation_name_check + CHECK (private_secret_name = 'jwt-signing-keys'), + CONSTRAINT account_jwt_signer_observation_uid_check + CHECK (expected_cluster_incarnation_uid <> '00000000-0000-0000-0000-000000000000'::UUID + AND expected_namespace_uid <> '00000000-0000-0000-0000-000000000000'::UUID + AND secret_uid <> '00000000-0000-0000-0000-000000000000'::UUID), + CONSTRAINT account_jwt_signer_observation_trust_check + CHECK (trust_binding_digest ~ '^[0-9a-f]{64}$' + AND trust_config_revision ~ '^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$'), + CONSTRAINT account_jwt_signer_observation_version_check + CHECK (expected_record_version > 0 AND operation_digest_version = 1 + AND observation_digest_version = 1), + CONSTRAINT account_jwt_signer_observation_digest_check + CHECK (operation_digest ~ '^[0-9a-f]{64}$' + AND observation_digest ~ '^[0-9a-f]{64}$' + AND generation_request_digest ~ '^[0-9a-f]{64}$'), + CONSTRAINT account_jwt_signer_observation_resource_version_check + CHECK (observed_resource_version ~ '^[!-~]+$' + AND char_length(observed_resource_version) BETWEEN 1 AND 256) +); + +CREATE TABLE account_jwt_signer_generation_results ( + operation_id UUID PRIMARY KEY, + environment_id VARCHAR(63) NOT NULL, + cluster_id VARCHAR(128) NOT NULL, + kubernetes_namespace VARCHAR(63) NOT NULL, + custody_mode VARCHAR(64) NOT NULL, + operation_digest VARCHAR(64) NOT NULL, + generation_request_digest VARCHAR(64) NOT NULL, + desired_state_version BIGINT NOT NULL, + expected_cluster_incarnation_uid UUID NOT NULL, + expected_namespace_uid UUID NOT NULL, + trust_binding_digest VARCHAR(64) NOT NULL, + trust_config_revision VARCHAR(128) NOT NULL, + private_secret_name VARCHAR(63) NOT NULL, + secret_uid UUID NOT NULL, + expected_prior_resource_version VARCHAR(256) NOT NULL, + observed_resource_version VARCHAR(256) NOT NULL, + target_generation BIGINT NOT NULL, + target_kid VARCHAR(64) NOT NULL, + target_algorithm VARCHAR(16) NOT NULL, + public_key_fingerprint VARCHAR(64) NOT NULL, + public_jwk_json VARCHAR(8192) NOT NULL, + receipt_digest VARCHAR(64) NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT account_jwt_signer_generation_result_exact_state_fk + FOREIGN KEY (environment_id, cluster_id, kubernetes_namespace, custody_mode) + REFERENCES account_jwt_signer_desired_states( + environment_id, cluster_id, kubernetes_namespace, custody_mode) + ON DELETE RESTRICT, + CONSTRAINT account_jwt_signer_generation_result_exact_operation_fk + FOREIGN KEY (operation_id, environment_id, cluster_id, kubernetes_namespace, + custody_mode, operation_digest, + target_generation, target_kid, target_algorithm, + expected_cluster_incarnation_uid, expected_namespace_uid, + trust_binding_digest, trust_config_revision) + REFERENCES account_jwt_signer_generation_operations( + operation_id, environment_id, cluster_id, kubernetes_namespace, custody_mode, + operation_digest, target_generation, target_kid, + target_algorithm, expected_cluster_incarnation_uid, expected_namespace_uid, + trust_binding_digest, trust_config_revision) + ON DELETE RESTRICT, + CONSTRAINT account_jwt_signer_generation_result_exact_observation_fk + FOREIGN KEY (operation_id, operation_digest, generation_request_digest, + secret_uid, expected_prior_resource_version) + REFERENCES account_jwt_signer_secret_observations( + operation_id, operation_digest, generation_request_digest, + secret_uid, observed_resource_version) + ON DELETE RESTRICT, + CONSTRAINT account_jwt_signer_generation_result_name_check + CHECK (private_secret_name = 'jwt-signing-keys'), + CONSTRAINT account_jwt_signer_generation_result_uid_check + CHECK (expected_cluster_incarnation_uid <> '00000000-0000-0000-0000-000000000000'::UUID + AND expected_namespace_uid <> '00000000-0000-0000-0000-000000000000'::UUID + AND secret_uid <> '00000000-0000-0000-0000-000000000000'::UUID), + CONSTRAINT account_jwt_signer_generation_result_trust_check + CHECK (trust_binding_digest ~ '^[0-9a-f]{64}$' + AND trust_config_revision ~ '^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$'), + CONSTRAINT account_jwt_signer_generation_result_version_check + CHECK (desired_state_version > 1), + CONSTRAINT account_jwt_signer_generation_result_digest_check + CHECK (operation_digest ~ '^[0-9a-f]{64}$' + AND generation_request_digest ~ '^[0-9a-f]{64}$' + AND receipt_digest ~ '^[0-9a-f]{64}$'), + CONSTRAINT account_jwt_signer_generation_result_resource_versions_check + CHECK (expected_prior_resource_version ~ '^[!-~]+$' + AND char_length(expected_prior_resource_version) BETWEEN 1 AND 256 + AND observed_resource_version ~ '^[!-~]+$' + AND char_length(observed_resource_version) BETWEEN 1 AND 256 + AND expected_prior_resource_version <> observed_resource_version), + CONSTRAINT account_jwt_signer_generation_result_key_check + CHECK (target_generation > 0 + AND target_kid ~ '^[A-Za-z0-9_-]{1,64}$' + AND target_algorithm = 'RS256' + AND public_key_fingerprint ~ '^[0-9a-f]{64}$') +); + +-- [jooq ignore start] +ALTER TABLE account_jwt_signer_generation_results + ADD CONSTRAINT account_jwt_signer_generation_result_public_jwk_check + CHECK (octet_length(public_jwk_json) <= 8192 + AND jsonb_typeof(public_jwk_json::jsonb) = 'object' + AND (public_jwk_json::jsonb ?& ARRAY['kty', 'use', 'alg', 'kid', 'key_ops', 'n', 'e']) + AND NOT (public_jwk_json::jsonb ?| ARRAY['d', 'p', 'q', 'dp', 'dq', 'qi', 'oth', 'k']) + AND public_jwk_json::jsonb - ARRAY['kty', 'use', 'alg', 'kid', 'key_ops', 'n', 'e'] = '{}'::jsonb); +-- [jooq ignore stop] + +-- [jooq ignore start] +CREATE FUNCTION account_jwt_signer_secret_observation_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + state_operation_id UUID; + state_record_version BIGINT; + operation_digest VARCHAR(64); + operation_expected_version BIGINT; + operation_environment VARCHAR(63); + operation_cluster VARCHAR(128); + operation_namespace VARCHAR(63); + operation_mode VARCHAR(64); + operation_cluster_uid UUID; + operation_namespace_uid UUID; + operation_trust_digest VARCHAR(64); + operation_trust_revision VARCHAR(128); +BEGIN + SELECT desired_state.generation_operation_id, desired_state.record_version + INTO state_operation_id, state_record_version + FROM account_jwt_signer_desired_states AS desired_state + WHERE desired_state.environment_id = NEW.environment_id + AND desired_state.cluster_id = NEW.cluster_id + AND desired_state.kubernetes_namespace = NEW.kubernetes_namespace + AND desired_state.custody_mode = NEW.custody_mode + FOR UPDATE; + + SELECT generation_op.operation_digest, generation_op.expected_record_version, + generation_op.environment_id, generation_op.cluster_id, generation_op.kubernetes_namespace, + generation_op.custody_mode, generation_op.expected_cluster_incarnation_uid, + generation_op.expected_namespace_uid, generation_op.trust_binding_digest, + generation_op.trust_config_revision + INTO operation_digest, operation_expected_version, operation_environment, + operation_cluster, operation_namespace, operation_mode, operation_cluster_uid, + operation_namespace_uid, operation_trust_digest, operation_trust_revision + FROM account_jwt_signer_generation_operations AS generation_op + WHERE generation_op.operation_id = NEW.operation_id + FOR UPDATE; + + IF state_operation_id IS DISTINCT FROM NEW.operation_id + OR state_record_version IS DISTINCT FROM operation_expected_version + 1 + OR operation_digest IS DISTINCT FROM NEW.operation_digest + OR operation_expected_version IS DISTINCT FROM NEW.expected_record_version + OR operation_environment IS DISTINCT FROM NEW.environment_id + OR operation_cluster IS DISTINCT FROM NEW.cluster_id + OR operation_namespace IS DISTINCT FROM NEW.kubernetes_namespace + OR operation_mode IS DISTINCT FROM NEW.custody_mode + OR operation_cluster_uid IS DISTINCT FROM NEW.expected_cluster_incarnation_uid + OR operation_namespace_uid IS DISTINCT FROM NEW.expected_namespace_uid + OR operation_trust_digest IS DISTINCT FROM NEW.trust_binding_digest + OR operation_trust_revision IS DISTINCT FROM NEW.trust_config_revision + OR NEW.private_secret_name IS DISTINCT FROM 'jwt-signing-keys' THEN + RAISE EXCEPTION 'JWT signer Secret observation must bind the current Account operation and trust' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_secret_observation_binding'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_jwt_signer_generation_result_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + state_operation_id UUID; + state_record_version BIGINT; + operation_digest VARCHAR(64); + operation_expected_version BIGINT; + operation_environment VARCHAR(63); + operation_cluster VARCHAR(128); + operation_namespace VARCHAR(63); + operation_mode VARCHAR(64); + operation_generation BIGINT; + operation_kid VARCHAR(64); + operation_algorithm VARCHAR(16); + operation_cluster_uid UUID; + operation_namespace_uid UUID; + operation_trust_digest VARCHAR(64); + operation_trust_revision VARCHAR(128); + observation_generation_request_digest VARCHAR(64); + observation_secret_uid UUID; + observation_resource_version VARCHAR(256); +BEGIN + -- Lock order matches every Account repository write: desired state, then operation. + SELECT desired_state.generation_operation_id, desired_state.record_version + INTO state_operation_id, state_record_version + FROM account_jwt_signer_desired_states AS desired_state + WHERE desired_state.environment_id = NEW.environment_id + AND desired_state.cluster_id = NEW.cluster_id + AND desired_state.kubernetes_namespace = NEW.kubernetes_namespace + AND desired_state.custody_mode = NEW.custody_mode + FOR UPDATE; + + SELECT generation_op.operation_digest, generation_op.expected_record_version, + generation_op.environment_id, generation_op.cluster_id, generation_op.kubernetes_namespace, + generation_op.custody_mode, generation_op.target_generation, generation_op.target_kid, + generation_op.target_algorithm, generation_op.expected_cluster_incarnation_uid, + generation_op.expected_namespace_uid, generation_op.trust_binding_digest, + generation_op.trust_config_revision + INTO operation_digest, operation_expected_version, operation_environment, + operation_cluster, operation_namespace, operation_mode, operation_generation, + operation_kid, operation_algorithm, operation_cluster_uid, + operation_namespace_uid, operation_trust_digest, operation_trust_revision + FROM account_jwt_signer_generation_operations AS generation_op + WHERE generation_op.operation_id = NEW.operation_id + FOR UPDATE; + + SELECT observation.generation_request_digest, observation.secret_uid, + observation.observed_resource_version + INTO observation_generation_request_digest, observation_secret_uid, + observation_resource_version + FROM account_jwt_signer_secret_observations AS observation + WHERE observation.operation_id = NEW.operation_id + FOR UPDATE; + + IF state_operation_id IS DISTINCT FROM NEW.operation_id + OR state_record_version IS DISTINCT FROM operation_expected_version + 1 + OR NEW.desired_state_version IS DISTINCT FROM state_record_version + OR operation_digest IS DISTINCT FROM NEW.operation_digest + OR operation_expected_version IS NULL + OR operation_environment IS DISTINCT FROM NEW.environment_id + OR operation_cluster IS DISTINCT FROM NEW.cluster_id + OR operation_namespace IS DISTINCT FROM NEW.kubernetes_namespace + OR operation_mode IS DISTINCT FROM NEW.custody_mode + OR operation_generation IS DISTINCT FROM NEW.target_generation + OR operation_kid IS DISTINCT FROM NEW.target_kid + OR operation_algorithm IS DISTINCT FROM NEW.target_algorithm + OR operation_cluster_uid IS DISTINCT FROM NEW.expected_cluster_incarnation_uid + OR operation_namespace_uid IS DISTINCT FROM NEW.expected_namespace_uid + OR operation_trust_digest IS DISTINCT FROM NEW.trust_binding_digest + OR operation_trust_revision IS DISTINCT FROM NEW.trust_config_revision + OR observation_generation_request_digest IS DISTINCT FROM NEW.generation_request_digest + OR observation_secret_uid IS DISTINCT FROM NEW.secret_uid + OR observation_resource_version IS DISTINCT FROM NEW.expected_prior_resource_version + OR NEW.private_secret_name IS DISTINCT FROM 'jwt-signing-keys' THEN + RAISE EXCEPTION 'JWT signer generation result must bind the exact current request and observation' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_generation_result_binding'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_jwt_signer_generation_evidence_immutable() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'Account JWT signer generation evidence is immutable' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_generation_evidence_immutable'; + RETURN NULL; +END; +$$; + +CREATE TRIGGER account_jwt_signer_secret_observation_guard + BEFORE INSERT ON account_jwt_signer_secret_observations + FOR EACH ROW EXECUTE FUNCTION account_jwt_signer_secret_observation_guard(); + +CREATE TRIGGER account_jwt_signer_secret_observation_immutable + BEFORE UPDATE OR DELETE ON account_jwt_signer_secret_observations + FOR EACH ROW EXECUTE FUNCTION account_jwt_signer_generation_evidence_immutable(); + +CREATE TRIGGER account_jwt_signer_secret_observation_no_truncate + BEFORE TRUNCATE ON account_jwt_signer_secret_observations + FOR EACH STATEMENT EXECUTE FUNCTION account_jwt_signer_generation_evidence_immutable(); + +CREATE TRIGGER account_jwt_signer_generation_result_guard + BEFORE INSERT ON account_jwt_signer_generation_results + FOR EACH ROW EXECUTE FUNCTION account_jwt_signer_generation_result_guard(); + +CREATE TRIGGER account_jwt_signer_generation_result_immutable + BEFORE UPDATE OR DELETE ON account_jwt_signer_generation_results + FOR EACH ROW EXECUTE FUNCTION account_jwt_signer_generation_evidence_immutable(); + +CREATE TRIGGER account_jwt_signer_generation_result_no_truncate + BEFORE TRUNCATE ON account_jwt_signer_generation_results + FOR EACH STATEMENT EXECUTE FUNCTION account_jwt_signer_generation_evidence_immutable(); +-- [jooq ignore stop] + diff --git a/services/account-service/src/main/resources/db/migration/V43__account_jwt_jwks_prepublication.sql b/services/account-service/src/main/resources/db/migration/V43__account_jwt_jwks_prepublication.sql new file mode 100644 index 0000000000..3914eef34d --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V43__account_jwt_jwks_prepublication.sql @@ -0,0 +1,600 @@ +-- Account records its exact public-JWKS intent before the protected ConfigMap CAS, then binds +-- server readback and local mounted correspondence to the same current generation operation. +-- These observations are non-authorizing and never advance signer lifecycle state. +CREATE TABLE account_jwt_jwks_prepublication_intents ( + operation_id UUID PRIMARY KEY, + environment_id VARCHAR(63) NOT NULL, + cluster_id VARCHAR(128) NOT NULL, + kubernetes_namespace VARCHAR(63) NOT NULL, + custody_mode VARCHAR(64) NOT NULL, + operation_digest VARCHAR(64) NOT NULL, + generation_request_digest VARCHAR(64) NOT NULL, + generation_receipt_digest VARCHAR(64) NOT NULL, + desired_state_version BIGINT NOT NULL, + expected_cluster_incarnation_uid UUID NOT NULL, + expected_namespace_uid UUID NOT NULL, + trust_binding_digest VARCHAR(64) NOT NULL, + trust_config_revision VARCHAR(128) NOT NULL, + api_binding_digest VARCHAR(64) NOT NULL, + api_config_revision VARCHAR(128) NOT NULL, + config_map_name VARCHAR(63) NOT NULL, + config_map_uid UUID NOT NULL, + expected_resource_version VARCHAR(256) NOT NULL, + expected_snapshot_digest VARCHAR(64) NOT NULL, + target_generation BIGINT NOT NULL, + target_kid VARCHAR(64) NOT NULL, + public_key_fingerprint VARCHAR(64) NOT NULL, + expected_durable_active_json VARCHAR(512) NOT NULL, + expected_published_active_json VARCHAR(512) NOT NULL, + jwks_json TEXT NOT NULL, + generation_marker_json TEXT NOT NULL, + public_data_digest VARCHAR(64) NOT NULL, + generation_marker_digest VARCHAR(64) NOT NULL, + intent_digest VARCHAR(64) NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT account_jwt_jwks_intent_state_fk + FOREIGN KEY (environment_id, cluster_id, kubernetes_namespace, custody_mode) + REFERENCES account_jwt_signer_desired_states( + environment_id, cluster_id, kubernetes_namespace, custody_mode) + ON DELETE RESTRICT, + CONSTRAINT account_jwt_jwks_intent_generation_result_fk + FOREIGN KEY (operation_id) + REFERENCES account_jwt_signer_generation_results(operation_id) + ON DELETE RESTRICT, + CONSTRAINT account_jwt_jwks_intent_digest_unique + UNIQUE (operation_id, intent_digest), + CONSTRAINT account_jwt_jwks_intent_identity_check + CHECK (custody_mode = 'INTERIM_ACCOUNT_ONLY_MOUNTED_FALLBACK' + AND config_map_name = 'jwt-jwks' + AND desired_state_version > 1 + AND target_generation > 0 + AND target_kid ~ '^[A-Za-z0-9_-]+$' + AND char_length(target_kid) BETWEEN 1 AND 64), + CONSTRAINT account_jwt_jwks_intent_uid_check + CHECK (expected_cluster_incarnation_uid <> '00000000-0000-0000-0000-000000000000'::UUID + AND expected_namespace_uid <> '00000000-0000-0000-0000-000000000000'::UUID + AND config_map_uid <> '00000000-0000-0000-0000-000000000000'::UUID), + CONSTRAINT account_jwt_jwks_intent_resource_version_check + CHECK (expected_resource_version ~ '^[!-~]+$' + AND char_length(expected_resource_version) BETWEEN 1 AND 256), + CONSTRAINT account_jwt_jwks_intent_digest_check + CHECK (operation_digest ~ '^[0-9a-f]{64}$' + AND generation_request_digest ~ '^[0-9a-f]{64}$' + AND generation_receipt_digest ~ '^[0-9a-f]{64}$' + AND trust_binding_digest ~ '^[0-9a-f]{64}$' + AND api_binding_digest ~ '^[0-9a-f]{64}$' + AND expected_snapshot_digest ~ '^[0-9a-f]{64}$' + AND public_key_fingerprint ~ '^[0-9a-f]{64}$' + AND public_data_digest ~ '^[0-9a-f]{64}$' + AND generation_marker_digest ~ '^[0-9a-f]{64}$' + AND intent_digest ~ '^[0-9a-f]{64}$'), + CONSTRAINT account_jwt_jwks_intent_revision_check + CHECK (trust_config_revision ~ '^[A-Za-z0-9][A-Za-z0-9._:-]*$' + AND char_length(trust_config_revision) BETWEEN 1 AND 128 + AND api_config_revision ~ '^[A-Za-z0-9][A-Za-z0-9._:-]*$' + AND char_length(api_config_revision) BETWEEN 1 AND 128), + CONSTRAINT account_jwt_jwks_intent_content_bounds_check + CHECK (octet_length(jwks_json) BETWEEN 1 AND 262144 + AND octet_length(generation_marker_json) BETWEEN 1 AND 16384 + AND octet_length(expected_durable_active_json) BETWEEN 1 AND 512 + AND octet_length(expected_published_active_json) BETWEEN 1 AND 512) +); + +CREATE TABLE account_jwt_jwks_publication_receipts ( + operation_id UUID PRIMARY KEY, + environment_id VARCHAR(63) NOT NULL, + cluster_id VARCHAR(128) NOT NULL, + kubernetes_namespace VARCHAR(63) NOT NULL, + custody_mode VARCHAR(64) NOT NULL, + intent_digest VARCHAR(64) NOT NULL, + config_map_uid UUID NOT NULL, + expected_resource_version VARCHAR(256) NOT NULL, + observed_resource_version VARCHAR(256) NOT NULL, + public_data_digest VARCHAR(64) NOT NULL, + receipt_digest VARCHAR(64) NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT account_jwt_jwks_receipt_state_fk + FOREIGN KEY (environment_id, cluster_id, kubernetes_namespace, custody_mode) + REFERENCES account_jwt_signer_desired_states( + environment_id, cluster_id, kubernetes_namespace, custody_mode) + ON DELETE RESTRICT, + CONSTRAINT account_jwt_jwks_receipt_intent_fk + FOREIGN KEY (operation_id, intent_digest) + REFERENCES account_jwt_jwks_prepublication_intents(operation_id, intent_digest) + ON DELETE RESTRICT, + CONSTRAINT account_jwt_jwks_receipt_digest_unique + UNIQUE (operation_id, intent_digest, receipt_digest), + CONSTRAINT account_jwt_jwks_receipt_identity_check + CHECK (custody_mode = 'INTERIM_ACCOUNT_ONLY_MOUNTED_FALLBACK' + AND config_map_uid <> '00000000-0000-0000-0000-000000000000'::UUID + AND expected_resource_version ~ '^[!-~]+$' + AND char_length(expected_resource_version) BETWEEN 1 AND 256 + AND observed_resource_version ~ '^[!-~]+$' + AND char_length(observed_resource_version) BETWEEN 1 AND 256 + AND expected_resource_version <> observed_resource_version), + CONSTRAINT account_jwt_jwks_receipt_digest_check + CHECK (intent_digest ~ '^[0-9a-f]{64}$' + AND public_data_digest ~ '^[0-9a-f]{64}$' + AND receipt_digest ~ '^[0-9a-f]{64}$') +); + +CREATE TABLE account_jwt_jwks_mount_observations ( + operation_id UUID PRIMARY KEY, + environment_id VARCHAR(63) NOT NULL, + cluster_id VARCHAR(128) NOT NULL, + kubernetes_namespace VARCHAR(63) NOT NULL, + custody_mode VARCHAR(64) NOT NULL, + intent_digest VARCHAR(64) NOT NULL, + publication_receipt_digest VARCHAR(64) NOT NULL, + generation_marker_digest VARCHAR(64) NOT NULL, + public_data_digest VARCHAR(64) NOT NULL, + public_key_fingerprint VARCHAR(64) NOT NULL, + observation_digest VARCHAR(64) NOT NULL, + observed_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT account_jwt_jwks_mount_state_fk + FOREIGN KEY (environment_id, cluster_id, kubernetes_namespace, custody_mode) + REFERENCES account_jwt_signer_desired_states( + environment_id, cluster_id, kubernetes_namespace, custody_mode) + ON DELETE RESTRICT, + CONSTRAINT account_jwt_jwks_mount_receipt_fk + FOREIGN KEY (operation_id, intent_digest, publication_receipt_digest) + REFERENCES account_jwt_jwks_publication_receipts( + operation_id, intent_digest, receipt_digest) + ON DELETE RESTRICT, + CONSTRAINT account_jwt_jwks_mount_digest_check + CHECK (custody_mode = 'INTERIM_ACCOUNT_ONLY_MOUNTED_FALLBACK' + AND intent_digest ~ '^[0-9a-f]{64}$' + AND publication_receipt_digest ~ '^[0-9a-f]{64}$' + AND generation_marker_digest ~ '^[0-9a-f]{64}$' + AND public_data_digest ~ '^[0-9a-f]{64}$' + AND public_key_fingerprint ~ '^[0-9a-f]{64}$' + AND observation_digest ~ '^[0-9a-f]{64}$') +); + +-- Keep the trigger bodies out of jOOQ DDL parsing; the database still enforces these invariants. +-- [jooq ignore start] +CREATE FUNCTION account_jwt_jwks_lock_current_generation( + p_operation_id UUID, + p_environment_id VARCHAR, + p_cluster_id VARCHAR, + p_namespace VARCHAR, + p_custody_mode VARCHAR, + p_operation_digest VARCHAR, + p_generation_request_digest VARCHAR, + p_generation_receipt_digest VARCHAR, + p_desired_state_version BIGINT, + p_cluster_uid UUID, + p_namespace_uid UUID, + p_trust_binding_digest VARCHAR, + p_trust_config_revision VARCHAR, + p_target_generation BIGINT, + p_target_kid VARCHAR, + p_public_key_fingerprint VARCHAR +) +RETURNS JSONB +LANGUAGE plpgsql +AS $$ +DECLARE + state_operation_id UUID; + state_version BIGINT; + state_prepared_operation_id UUID; + durable_active JSONB; + published_active JSONB; + operation_environment VARCHAR(63); + operation_cluster VARCHAR(128); + operation_namespace VARCHAR(63); + operation_mode VARCHAR(64); + operation_digest VARCHAR(64); + operation_expected_version BIGINT; + operation_cluster_uid UUID; + operation_namespace_uid UUID; + operation_trust_digest VARCHAR(64); + operation_trust_revision VARCHAR(128); + operation_target_generation BIGINT; + operation_target_kid VARCHAR(64); + operation_target_algorithm VARCHAR(16); + operation_previous_generation BIGINT; + operation_previous_kid VARCHAR(128); + operation_published_generation BIGINT; + operation_published_kid VARCHAR(128); + result_environment VARCHAR(63); + result_cluster VARCHAR(128); + result_namespace VARCHAR(63); + result_mode VARCHAR(64); + result_operation_digest VARCHAR(64); + result_generation_request_digest VARCHAR(64); + result_desired_state_version BIGINT; + result_cluster_uid UUID; + result_namespace_uid UUID; + result_trust_digest VARCHAR(64); + result_trust_revision VARCHAR(128); + result_generation BIGINT; + result_kid VARCHAR(64); + result_fingerprint VARCHAR(64); + result_receipt_digest VARCHAR(64); + result_jwk VARCHAR(8192); +BEGIN + SELECT desired_state.generation_operation_id, + desired_state.record_version, + desired_state.prepared_operation_id, + CASE WHEN desired_state.durable_active_generation IS NULL + THEN '{"present":false}'::jsonb + ELSE jsonb_build_object('present', true, + 'generation', desired_state.durable_active_generation::text, + 'kid', desired_state.durable_active_kid) + END, + CASE WHEN desired_state.published_active_generation IS NULL + THEN '{"present":false}'::jsonb + ELSE jsonb_build_object('present', true, + 'generation', desired_state.published_active_generation::text, + 'kid', desired_state.published_active_kid) + END + INTO state_operation_id, state_version, state_prepared_operation_id, + durable_active, published_active + FROM account_jwt_signer_desired_states AS desired_state + WHERE desired_state.environment_id = p_environment_id + AND desired_state.cluster_id = p_cluster_id + AND desired_state.kubernetes_namespace = p_namespace + AND desired_state.custody_mode = p_custody_mode + FOR UPDATE; + + IF NOT FOUND THEN + RAISE EXCEPTION 'Account JWT JWKS current desired state is missing' USING ERRCODE = '23514'; + END IF; + + SELECT generation_op.environment_id, generation_op.cluster_id, + generation_op.kubernetes_namespace, generation_op.custody_mode, + generation_op.operation_digest, generation_op.expected_record_version, + generation_op.expected_cluster_incarnation_uid, + generation_op.expected_namespace_uid, generation_op.trust_binding_digest, + generation_op.trust_config_revision, generation_op.target_generation, + generation_op.target_kid, generation_op.target_algorithm, + generation_op.expected_previous_generation, generation_op.expected_previous_kid, + generation_op.expected_published_generation, generation_op.expected_published_kid + INTO operation_environment, operation_cluster, operation_namespace, operation_mode, + operation_digest, operation_expected_version, operation_cluster_uid, + operation_namespace_uid, operation_trust_digest, operation_trust_revision, + operation_target_generation, operation_target_kid, operation_target_algorithm, + operation_previous_generation, operation_previous_kid, + operation_published_generation, operation_published_kid + FROM account_jwt_signer_generation_operations AS generation_op + WHERE generation_op.operation_id = p_operation_id + FOR UPDATE; + + IF NOT FOUND THEN + RAISE EXCEPTION 'Account JWT JWKS generation operation is missing' USING ERRCODE = '23514'; + END IF; + + SELECT generation_result.environment_id, generation_result.cluster_id, + generation_result.kubernetes_namespace, generation_result.custody_mode, + generation_result.operation_digest, generation_result.generation_request_digest, + generation_result.desired_state_version, + generation_result.expected_cluster_incarnation_uid, + generation_result.expected_namespace_uid, generation_result.trust_binding_digest, + generation_result.trust_config_revision, generation_result.target_generation, + generation_result.target_kid, generation_result.public_key_fingerprint, + generation_result.receipt_digest, generation_result.public_jwk_json + INTO result_environment, result_cluster, result_namespace, result_mode, + result_operation_digest, result_generation_request_digest, result_desired_state_version, + result_cluster_uid, result_namespace_uid, result_trust_digest, result_trust_revision, + result_generation, result_kid, result_fingerprint, result_receipt_digest, result_jwk + FROM account_jwt_signer_generation_results AS generation_result + WHERE generation_result.operation_id = p_operation_id + FOR UPDATE; + + IF NOT FOUND + OR state_operation_id IS DISTINCT FROM p_operation_id + OR state_version IS DISTINCT FROM p_desired_state_version + OR state_prepared_operation_id IS NOT NULL + OR operation_environment IS DISTINCT FROM p_environment_id + OR operation_cluster IS DISTINCT FROM p_cluster_id + OR operation_namespace IS DISTINCT FROM p_namespace + OR operation_mode IS DISTINCT FROM p_custody_mode + OR operation_digest IS DISTINCT FROM p_operation_digest + OR operation_expected_version + 1 IS DISTINCT FROM p_desired_state_version + OR operation_cluster_uid IS DISTINCT FROM p_cluster_uid + OR operation_namespace_uid IS DISTINCT FROM p_namespace_uid + OR operation_trust_digest IS DISTINCT FROM p_trust_binding_digest + OR operation_trust_revision IS DISTINCT FROM p_trust_config_revision + OR operation_target_generation IS DISTINCT FROM p_target_generation + OR operation_target_kid IS DISTINCT FROM p_target_kid + OR operation_target_algorithm IS DISTINCT FROM 'RS256' + OR result_environment IS DISTINCT FROM p_environment_id + OR result_cluster IS DISTINCT FROM p_cluster_id + OR result_namespace IS DISTINCT FROM p_namespace + OR result_mode IS DISTINCT FROM p_custody_mode + OR result_operation_digest IS DISTINCT FROM p_operation_digest + OR result_generation_request_digest IS DISTINCT FROM p_generation_request_digest + OR result_receipt_digest IS DISTINCT FROM p_generation_receipt_digest + OR result_desired_state_version IS DISTINCT FROM p_desired_state_version + OR result_cluster_uid IS DISTINCT FROM p_cluster_uid + OR result_namespace_uid IS DISTINCT FROM p_namespace_uid + OR result_trust_digest IS DISTINCT FROM p_trust_binding_digest + OR result_trust_revision IS DISTINCT FROM p_trust_config_revision + OR result_generation IS DISTINCT FROM p_target_generation + OR result_kid IS DISTINCT FROM p_target_kid + OR result_fingerprint IS DISTINCT FROM p_public_key_fingerprint + OR operation_previous_generation IS DISTINCT FROM + NULLIF(durable_active->>'generation', '')::BIGINT + OR operation_previous_kid IS DISTINCT FROM NULLIF(durable_active->>'kid', '') + OR operation_published_generation IS DISTINCT FROM + NULLIF(published_active->>'generation', '')::BIGINT + OR operation_published_kid IS DISTINCT FROM NULLIF(published_active->>'kid', '') THEN + RAISE EXCEPTION 'Account JWT JWKS evidence is stale or mismatched' USING ERRCODE = '23514'; + END IF; + + RETURN jsonb_build_object( + 'durableActive', durable_active, + 'publishedActive', published_active, + 'publicJwk', result_jwk::jsonb); +END; +$$; + +CREATE FUNCTION account_jwt_jwks_validate_public_intent() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + current_evidence JSONB; + jwks_document JSONB; + marker_document JSONB; + key_document JSONB; + key_kid TEXT; + seen_kids TEXT[] := ARRAY[]::TEXT[]; + target_key_count INTEGER := 0; + public_jwk JSONB; +BEGIN + current_evidence := account_jwt_jwks_lock_current_generation( + NEW.operation_id, NEW.environment_id, NEW.cluster_id, NEW.kubernetes_namespace, + NEW.custody_mode, NEW.operation_digest, NEW.generation_request_digest, + NEW.generation_receipt_digest, NEW.desired_state_version, + NEW.expected_cluster_incarnation_uid, NEW.expected_namespace_uid, + NEW.trust_binding_digest, NEW.trust_config_revision, + NEW.target_generation, NEW.target_kid, NEW.public_key_fingerprint); + + IF NEW.expected_durable_active_json::jsonb IS DISTINCT FROM current_evidence->'durableActive' + OR NEW.expected_published_active_json::jsonb IS DISTINCT FROM current_evidence->'publishedActive' THEN + RAISE EXCEPTION 'Account JWT JWKS active fence is stale' USING ERRCODE = '23514'; + END IF; + + jwks_document := NEW.jwks_json::jsonb; + IF jsonb_typeof(jwks_document) IS DISTINCT FROM 'object' + OR jwks_document - ARRAY['keys'] <> '{}'::jsonb + OR jsonb_typeof(jwks_document->'keys') IS DISTINCT FROM 'array' + OR jsonb_array_length(jwks_document->'keys') < 1 + OR jsonb_array_length(jwks_document->'keys') > 64 THEN + RAISE EXCEPTION 'Account public JWKS has an unsupported shape' USING ERRCODE = '23514'; + END IF; + public_jwk := current_evidence->'publicJwk'; + FOR key_document IN + SELECT jwks_key.value + FROM jsonb_array_elements(jwks_document->'keys') AS jwks_key(value) + LOOP + IF jsonb_typeof(key_document) IS DISTINCT FROM 'object' + OR key_document - ARRAY['kty', 'use', 'alg', 'kid', 'key_ops', 'n', 'e'] <> '{}'::jsonb + OR (SELECT count(*) FROM jsonb_object_keys(key_document)) NOT BETWEEN 6 AND 7 + OR key_document ?| ARRAY['d', 'p', 'q', 'dp', 'dq', 'qi', 'oth', 'k'] + OR key_document->>'kty' IS DISTINCT FROM 'RSA' + OR key_document->>'use' IS DISTINCT FROM 'sig' + OR key_document->>'alg' IS DISTINCT FROM 'RS256' + OR key_document->>'kid' IS NULL + OR key_document->>'kid' !~ '^[A-Za-z0-9_-]{1,64}$' + OR jsonb_typeof(key_document->'n') IS DISTINCT FROM 'string' + OR jsonb_typeof(key_document->'e') IS DISTINCT FROM 'string' + OR key_document->>'n' !~ '^[A-Za-z0-9_-]+$' + OR key_document->>'e' !~ '^[A-Za-z0-9_-]+$' + OR (key_document ? 'key_ops' + AND (jsonb_typeof(key_document->'key_ops') IS DISTINCT FROM 'array' + OR key_document->'key_ops' <> '["verify"]'::jsonb)) THEN + RAISE EXCEPTION 'Account public JWKS contains an invalid or private key' USING ERRCODE = '23514'; + END IF; + key_kid := key_document->>'kid'; + IF key_kid = ANY(seen_kids) THEN + RAISE EXCEPTION 'Account public JWKS has duplicate kids' USING ERRCODE = '23514'; + END IF; + seen_kids := array_append(seen_kids, key_kid); + IF key_kid = NEW.target_kid THEN + target_key_count := target_key_count + 1; + IF key_document IS DISTINCT FROM public_jwk THEN + RAISE EXCEPTION 'Account public JWKS pending key differs from receipt' USING ERRCODE = '23514'; + END IF; + END IF; + END LOOP; + IF target_key_count <> 1 THEN + RAISE EXCEPTION 'Account public JWKS does not contain exactly one pending key' USING ERRCODE = '23514'; + END IF; + + marker_document := NEW.generation_marker_json::jsonb; + IF jsonb_typeof(marker_document) IS DISTINCT FROM 'object' + OR (marker_document - ARRAY['schemaVersion', 'phase', 'operationId', 'operationDigest', + 'generationRequestDigest', 'generationReceiptDigest', 'binding', 'publicConfigMap', + 'expectedDurableActive', 'expectedPublishedActive', 'pending']) <> '{}'::jsonb + OR (SELECT count(*) FROM jsonb_object_keys(marker_document)) <> 11 + OR jsonb_typeof((marker_document -> 'binding')) IS DISTINCT FROM 'object' + OR ((marker_document -> 'binding') - ARRAY['environmentId', 'clusterId', 'namespace', + 'expectedClusterIncarnationUid', 'expectedNamespaceUid', 'trustBindingDigest', + 'trustConfigRevision', 'apiBindingDigest', 'apiConfigRevision']) <> '{}'::jsonb + OR (SELECT count(*) FROM jsonb_object_keys((marker_document -> 'binding'))) <> 9 + OR jsonb_typeof((marker_document -> 'publicConfigMap')) IS DISTINCT FROM 'object' + OR ((marker_document -> 'publicConfigMap') - ARRAY['name']) <> '{}'::jsonb + OR (SELECT count(*) FROM jsonb_object_keys((marker_document -> 'publicConfigMap'))) <> 1 + OR jsonb_typeof((marker_document -> 'pending')) IS DISTINCT FROM 'object' + OR ((marker_document -> 'pending') - ARRAY['generation', 'kid', 'algorithm', + 'publicKeyFingerprint']) <> '{}'::jsonb + OR (SELECT count(*) FROM jsonb_object_keys((marker_document -> 'pending'))) <> 4 + OR (marker_document ->> 'schemaVersion') IS DISTINCT FROM '1' + OR (marker_document ->> 'phase') IS DISTINCT FROM 'PREPUBLISHED' + OR (marker_document ->> 'operationId') IS DISTINCT FROM NEW.operation_id::TEXT + OR (marker_document ->> 'operationDigest') IS DISTINCT FROM NEW.operation_digest + OR (marker_document ->> 'generationRequestDigest') IS DISTINCT FROM NEW.generation_request_digest + OR (marker_document ->> 'generationReceiptDigest') IS DISTINCT FROM NEW.generation_receipt_digest + OR ((marker_document -> 'binding') ->> 'environmentId') IS DISTINCT FROM NEW.environment_id + OR ((marker_document -> 'binding') ->> 'clusterId') IS DISTINCT FROM NEW.cluster_id + OR ((marker_document -> 'binding') ->> 'namespace') IS DISTINCT FROM NEW.kubernetes_namespace + OR ((marker_document -> 'binding') ->> 'expectedClusterIncarnationUid') IS DISTINCT FROM NEW.expected_cluster_incarnation_uid::TEXT + OR ((marker_document -> 'binding') ->> 'expectedNamespaceUid') IS DISTINCT FROM NEW.expected_namespace_uid::TEXT + OR ((marker_document -> 'binding') ->> 'trustBindingDigest') IS DISTINCT FROM NEW.trust_binding_digest + OR ((marker_document -> 'binding') ->> 'trustConfigRevision') IS DISTINCT FROM NEW.trust_config_revision + OR ((marker_document -> 'binding') ->> 'apiBindingDigest') IS DISTINCT FROM NEW.api_binding_digest + OR ((marker_document -> 'binding') ->> 'apiConfigRevision') IS DISTINCT FROM NEW.api_config_revision + OR ((marker_document -> 'publicConfigMap') ->> 'name') IS DISTINCT FROM 'jwt-jwks' + OR (marker_document -> 'expectedDurableActive') IS DISTINCT FROM (NEW.expected_durable_active_json::jsonb) + OR (marker_document -> 'expectedPublishedActive') IS DISTINCT FROM (NEW.expected_published_active_json::jsonb) + OR ((marker_document -> 'pending') ->> 'generation') IS DISTINCT FROM NEW.target_generation::TEXT + OR ((marker_document -> 'pending') ->> 'kid') IS DISTINCT FROM NEW.target_kid + OR ((marker_document -> 'pending') ->> 'algorithm') IS DISTINCT FROM 'RS256' + OR ((marker_document -> 'pending') ->> 'publicKeyFingerprint') IS DISTINCT FROM NEW.public_key_fingerprint THEN + RAISE EXCEPTION 'Account public generation marker is stale or mismatched' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_jwt_jwks_validate_publication_receipt() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + intent_row account_jwt_jwks_prepublication_intents%ROWTYPE; +BEGIN + PERFORM account_jwt_jwks_lock_current_generation( + NEW.operation_id, NEW.environment_id, NEW.cluster_id, NEW.kubernetes_namespace, + NEW.custody_mode, (SELECT intent.operation_digest FROM account_jwt_jwks_prepublication_intents AS intent + WHERE intent.operation_id = NEW.operation_id), + (SELECT intent.generation_request_digest FROM account_jwt_jwks_prepublication_intents AS intent + WHERE intent.operation_id = NEW.operation_id), + (SELECT intent.generation_receipt_digest FROM account_jwt_jwks_prepublication_intents AS intent + WHERE intent.operation_id = NEW.operation_id), + (SELECT intent.desired_state_version FROM account_jwt_jwks_prepublication_intents AS intent + WHERE intent.operation_id = NEW.operation_id), + (SELECT intent.expected_cluster_incarnation_uid FROM account_jwt_jwks_prepublication_intents AS intent + WHERE intent.operation_id = NEW.operation_id), + (SELECT intent.expected_namespace_uid FROM account_jwt_jwks_prepublication_intents AS intent + WHERE intent.operation_id = NEW.operation_id), + (SELECT intent.trust_binding_digest FROM account_jwt_jwks_prepublication_intents AS intent + WHERE intent.operation_id = NEW.operation_id), + (SELECT intent.trust_config_revision FROM account_jwt_jwks_prepublication_intents AS intent + WHERE intent.operation_id = NEW.operation_id), + (SELECT intent.target_generation FROM account_jwt_jwks_prepublication_intents AS intent + WHERE intent.operation_id = NEW.operation_id), + (SELECT intent.target_kid FROM account_jwt_jwks_prepublication_intents AS intent + WHERE intent.operation_id = NEW.operation_id), + (SELECT intent.public_key_fingerprint FROM account_jwt_jwks_prepublication_intents AS intent + WHERE intent.operation_id = NEW.operation_id)); + SELECT intent.* INTO intent_row + FROM account_jwt_jwks_prepublication_intents AS intent + WHERE intent.operation_id = NEW.operation_id + FOR UPDATE; + IF NOT FOUND + OR intent_row.environment_id IS DISTINCT FROM NEW.environment_id + OR intent_row.cluster_id IS DISTINCT FROM NEW.cluster_id + OR intent_row.kubernetes_namespace IS DISTINCT FROM NEW.kubernetes_namespace + OR intent_row.custody_mode IS DISTINCT FROM NEW.custody_mode + OR intent_row.intent_digest IS DISTINCT FROM NEW.intent_digest + OR intent_row.config_map_uid IS DISTINCT FROM NEW.config_map_uid + OR intent_row.expected_resource_version IS DISTINCT FROM NEW.expected_resource_version + OR intent_row.public_data_digest IS DISTINCT FROM NEW.public_data_digest + OR NEW.expected_resource_version = NEW.observed_resource_version THEN + RAISE EXCEPTION 'Account JWT publication receipt does not match current intent' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_jwt_jwks_validate_mount_observation() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + intent_row account_jwt_jwks_prepublication_intents%ROWTYPE; + receipt_row account_jwt_jwks_publication_receipts%ROWTYPE; +BEGIN + PERFORM account_jwt_jwks_lock_current_generation( + NEW.operation_id, NEW.environment_id, NEW.cluster_id, NEW.kubernetes_namespace, + NEW.custody_mode, (SELECT intent.operation_digest FROM account_jwt_jwks_prepublication_intents AS intent + WHERE intent.operation_id = NEW.operation_id), + (SELECT intent.generation_request_digest FROM account_jwt_jwks_prepublication_intents AS intent + WHERE intent.operation_id = NEW.operation_id), + (SELECT intent.generation_receipt_digest FROM account_jwt_jwks_prepublication_intents AS intent + WHERE intent.operation_id = NEW.operation_id), + (SELECT intent.desired_state_version FROM account_jwt_jwks_prepublication_intents AS intent + WHERE intent.operation_id = NEW.operation_id), + (SELECT intent.expected_cluster_incarnation_uid FROM account_jwt_jwks_prepublication_intents AS intent + WHERE intent.operation_id = NEW.operation_id), + (SELECT intent.expected_namespace_uid FROM account_jwt_jwks_prepublication_intents AS intent + WHERE intent.operation_id = NEW.operation_id), + (SELECT intent.trust_binding_digest FROM account_jwt_jwks_prepublication_intents AS intent + WHERE intent.operation_id = NEW.operation_id), + (SELECT intent.trust_config_revision FROM account_jwt_jwks_prepublication_intents AS intent + WHERE intent.operation_id = NEW.operation_id), + (SELECT intent.target_generation FROM account_jwt_jwks_prepublication_intents AS intent + WHERE intent.operation_id = NEW.operation_id), + (SELECT intent.target_kid FROM account_jwt_jwks_prepublication_intents AS intent + WHERE intent.operation_id = NEW.operation_id), + (SELECT intent.public_key_fingerprint FROM account_jwt_jwks_prepublication_intents AS intent + WHERE intent.operation_id = NEW.operation_id)); + SELECT intent.* INTO intent_row + FROM account_jwt_jwks_prepublication_intents AS intent + WHERE intent.operation_id = NEW.operation_id + FOR UPDATE; + SELECT receipt.* INTO receipt_row + FROM account_jwt_jwks_publication_receipts AS receipt + WHERE receipt.operation_id = NEW.operation_id + FOR UPDATE; + IF NOT FOUND + OR intent_row.environment_id IS DISTINCT FROM NEW.environment_id + OR intent_row.cluster_id IS DISTINCT FROM NEW.cluster_id + OR intent_row.kubernetes_namespace IS DISTINCT FROM NEW.kubernetes_namespace + OR intent_row.custody_mode IS DISTINCT FROM NEW.custody_mode + OR intent_row.intent_digest IS DISTINCT FROM NEW.intent_digest + OR receipt_row.intent_digest IS DISTINCT FROM NEW.intent_digest + OR receipt_row.receipt_digest IS DISTINCT FROM NEW.publication_receipt_digest + OR intent_row.generation_marker_digest IS DISTINCT FROM NEW.generation_marker_digest + OR intent_row.public_data_digest IS DISTINCT FROM NEW.public_data_digest + OR intent_row.public_key_fingerprint IS DISTINCT FROM NEW.public_key_fingerprint THEN + RAISE EXCEPTION 'Mounted Account JWT correspondence is stale or mismatched' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_jwt_jwks_reject_mutation() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'Account JWT JWKS publication evidence is immutable' USING ERRCODE = '55000'; +END; +$$; + +CREATE TRIGGER account_jwt_jwks_intent_current_guard + BEFORE INSERT ON account_jwt_jwks_prepublication_intents + FOR EACH ROW EXECUTE FUNCTION account_jwt_jwks_validate_public_intent(); +CREATE TRIGGER account_jwt_jwks_receipt_current_guard + BEFORE INSERT ON account_jwt_jwks_publication_receipts + FOR EACH ROW EXECUTE FUNCTION account_jwt_jwks_validate_publication_receipt(); +CREATE TRIGGER account_jwt_jwks_mount_current_guard + BEFORE INSERT ON account_jwt_jwks_mount_observations + FOR EACH ROW EXECUTE FUNCTION account_jwt_jwks_validate_mount_observation(); + +CREATE TRIGGER account_jwt_jwks_intent_immutable + BEFORE UPDATE OR DELETE ON account_jwt_jwks_prepublication_intents + FOR EACH ROW EXECUTE FUNCTION account_jwt_jwks_reject_mutation(); +CREATE TRIGGER account_jwt_jwks_receipt_immutable + BEFORE UPDATE OR DELETE ON account_jwt_jwks_publication_receipts + FOR EACH ROW EXECUTE FUNCTION account_jwt_jwks_reject_mutation(); +CREATE TRIGGER account_jwt_jwks_mount_immutable + BEFORE UPDATE OR DELETE ON account_jwt_jwks_mount_observations + FOR EACH ROW EXECUTE FUNCTION account_jwt_jwks_reject_mutation(); + +CREATE TRIGGER account_jwt_jwks_intent_no_truncate + BEFORE TRUNCATE ON account_jwt_jwks_prepublication_intents + FOR EACH STATEMENT EXECUTE FUNCTION account_jwt_jwks_reject_mutation(); +CREATE TRIGGER account_jwt_jwks_receipt_no_truncate + BEFORE TRUNCATE ON account_jwt_jwks_publication_receipts + FOR EACH STATEMENT EXECUTE FUNCTION account_jwt_jwks_reject_mutation(); +CREATE TRIGGER account_jwt_jwks_mount_no_truncate + BEFORE TRUNCATE ON account_jwt_jwks_mount_observations + FOR EACH STATEMENT EXECUTE FUNCTION account_jwt_jwks_reject_mutation(); +-- [jooq ignore stop] + diff --git a/services/account-service/src/main/resources/db/migration/V45__account_jwt_readiness_probes.sql b/services/account-service/src/main/resources/db/migration/V45__account_jwt_readiness_probes.sql new file mode 100644 index 0000000000..2f22decf0f --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V45__account_jwt_readiness_probes.sql @@ -0,0 +1,466 @@ +-- Durable, operation-scoped probe plans for the interim Account-mounted JWT signer. +-- Plans bind existing desired-state, generation-result, JWKS publication, and mount evidence; +-- this migration creates no second key authority, validator endpoint, or promotion transition. +CREATE TABLE account_jwt_readiness_probe_plans ( + rotation_operation_id UUID PRIMARY KEY, + environment_id VARCHAR(63) NOT NULL, + cluster_id VARCHAR(128) NOT NULL, + kubernetes_namespace VARCHAR(63) NOT NULL, + custody_mode VARCHAR(64) NOT NULL, + operation_digest VARCHAR(64) NOT NULL, + generation_request_digest VARCHAR(64) NOT NULL, + generation_receipt_digest VARCHAR(64) NOT NULL, + desired_state_version BIGINT NOT NULL, + expected_cluster_incarnation_uid UUID NOT NULL, + expected_namespace_uid UUID NOT NULL, + trust_binding_digest VARCHAR(64) NOT NULL, + trust_config_revision VARCHAR(128) NOT NULL, + target_generation BIGINT NOT NULL, + target_kid VARCHAR(64) NOT NULL, + target_public_key_fingerprint VARCHAR(64) NOT NULL, + expected_active_generation BIGINT, + expected_active_kid VARCHAR(64), + expected_published_generation BIGINT, + expected_published_kid VARCHAR(64), + publication_intent_digest VARCHAR(64) NOT NULL, + publication_receipt_digest VARCHAR(64) NOT NULL, + mounted_observation_digest VARCHAR(64) NOT NULL, + applicability_matrix_json TEXT NOT NULL, + applicability_matrix_digest VARCHAR(64) NOT NULL, + validator_inventory_complete BOOLEAN NOT NULL DEFAULT FALSE, + maximum_cache_age_seconds SMALLINT NOT NULL, + planned_at_epoch_seconds BIGINT NOT NULL, + not_before_epoch_seconds BIGINT NOT NULL, + expires_at_epoch_seconds BIGINT NOT NULL, + plan_version SMALLINT NOT NULL DEFAULT 1, + plan_digest VARCHAR(64) NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT account_jwt_readiness_plan_binding_fk + FOREIGN KEY (environment_id, cluster_id, kubernetes_namespace, custody_mode) + REFERENCES account_jwt_signer_desired_states( + environment_id, cluster_id, kubernetes_namespace, custody_mode) + ON DELETE RESTRICT, + CONSTRAINT account_jwt_readiness_plan_operation_fk + FOREIGN KEY (rotation_operation_id) + REFERENCES account_jwt_signer_generation_operations(operation_id) + ON DELETE RESTRICT, + CONSTRAINT account_jwt_readiness_plan_result_fk + FOREIGN KEY (rotation_operation_id) + REFERENCES account_jwt_signer_generation_results(operation_id) + ON DELETE RESTRICT, + CONSTRAINT account_jwt_readiness_plan_publication_intent_fk + FOREIGN KEY (rotation_operation_id, publication_intent_digest) + REFERENCES account_jwt_jwks_prepublication_intents(operation_id, intent_digest) + ON DELETE RESTRICT, + CONSTRAINT account_jwt_readiness_plan_publication_receipt_fk + FOREIGN KEY (rotation_operation_id, publication_intent_digest, publication_receipt_digest) + REFERENCES account_jwt_jwks_publication_receipts( + operation_id, intent_digest, receipt_digest) + ON DELETE RESTRICT, + CONSTRAINT account_jwt_readiness_plan_mount_observation_fk + FOREIGN KEY (rotation_operation_id) + REFERENCES account_jwt_jwks_mount_observations(operation_id) + ON DELETE RESTRICT, + CONSTRAINT account_jwt_readiness_plan_identity_check + CHECK (rotation_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 custody_mode = 'INTERIM_ACCOUNT_ONLY_MOUNTED_FALLBACK' + AND desired_state_version > 1 + AND target_generation > COALESCE(expected_active_generation, 0) + AND ((expected_active_generation IS NULL AND expected_active_kid IS NULL + AND expected_published_generation IS NULL AND expected_published_kid IS NULL) + OR (expected_active_generation IS NOT NULL AND expected_active_kid IS NOT NULL + AND expected_published_generation IS NOT NULL AND expected_published_kid IS NOT NULL + AND expected_active_generation > 0 + AND expected_active_generation = expected_published_generation + AND expected_active_kid = expected_published_kid)) + AND target_kid ~ '^[A-Za-z0-9_-]{1,64}$' + AND (expected_active_kid IS NULL OR expected_active_kid ~ '^[A-Za-z0-9_-]{1,64}$') + AND target_kid <> expected_active_kid + AND target_public_key_fingerprint ~ '^[0-9a-f]{64}$'), + CONSTRAINT account_jwt_readiness_plan_digest_check + CHECK (operation_digest ~ '^[0-9a-f]{64}$' + AND generation_request_digest ~ '^[0-9a-f]{64}$' + AND generation_receipt_digest ~ '^[0-9a-f]{64}$' + AND trust_binding_digest ~ '^[0-9a-f]{64}$' + AND publication_intent_digest ~ '^[0-9a-f]{64}$' + AND publication_receipt_digest ~ '^[0-9a-f]{64}$' + AND mounted_observation_digest ~ '^[0-9a-f]{64}$' + AND applicability_matrix_digest ~ '^[0-9a-f]{64}$' + AND plan_digest ~ '^[0-9a-f]{64}$'), + CONSTRAINT account_jwt_readiness_plan_revision_check + CHECK (trust_config_revision ~ '^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$'), + CONSTRAINT account_jwt_readiness_plan_trust_uid_check + CHECK (expected_cluster_incarnation_uid <> '00000000-0000-0000-0000-000000000000'::UUID + AND expected_namespace_uid <> '00000000-0000-0000-0000-000000000000'::UUID), + CONSTRAINT account_jwt_readiness_plan_inventory_check + CHECK (octet_length(applicability_matrix_json) BETWEEN 2 AND 8192), + CONSTRAINT account_jwt_readiness_plan_window_check + CHECK (maximum_cache_age_seconds BETWEEN 1 AND 300 + AND planned_at_epoch_seconds > 0 + AND not_before_epoch_seconds >= planned_at_epoch_seconds + maximum_cache_age_seconds + AND expires_at_epoch_seconds > not_before_epoch_seconds + AND expires_at_epoch_seconds - not_before_epoch_seconds <= 300 + AND plan_version = 1), + CONSTRAINT account_jwt_readiness_plan_digest_unique + UNIQUE (rotation_operation_id, plan_digest) +); + +CREATE TABLE account_jwt_readiness_probe_entries ( + rotation_operation_id UUID NOT NULL, + plan_digest VARCHAR(64) NOT NULL, + validator_id VARCHAR(63) NOT NULL, + token_profile VARCHAR(128) NOT NULL, + audience VARCHAR(128) NOT NULL, + probe_kind VARCHAR(16) NOT NULL, + jti UUID NOT NULL UNIQUE, + target_generation BIGINT NOT NULL, + target_kid VARCHAR(64) NOT NULL, + expected_active_generation BIGINT, + expected_active_kid VARCHAR(64), + registry_version SMALLINT NOT NULL DEFAULT 1, + entry_version BIGINT NOT NULL DEFAULT 1, + planned_issued_at_epoch_seconds BIGINT NOT NULL, + expires_at_epoch_seconds BIGINT NOT NULL, + state VARCHAR(16) NOT NULL DEFAULT 'PLANNED', + terminal_outcome VARCHAR(16), + signing_attempted_at_epoch_seconds BIGINT, + compact_token_sha256 VARCHAR(64), + verification_receipt_version SMALLINT, + verification_source_entry_version BIGINT, + verified_at_epoch_seconds BIGINT, + verified_kid VARCHAR(64), + validator_instance_id VARCHAR(128), + validator_binding_digest VARCHAR(64), + validator_config_revision VARCHAR(128), + validator_peer_uri VARCHAR(256), + validator_peer_spki_sha256 VARCHAR(64), + verification_receipt_sha256 VARCHAR(64), + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (rotation_operation_id, validator_id, token_profile, audience, probe_kind), + CONSTRAINT account_jwt_readiness_probe_plan_fk + FOREIGN KEY (rotation_operation_id, plan_digest) + REFERENCES account_jwt_readiness_probe_plans(rotation_operation_id, plan_digest) + ON DELETE RESTRICT, + CONSTRAINT account_jwt_readiness_probe_jti_v4_check + CHECK (jti::text ~ '^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$'), + CONSTRAINT account_jwt_readiness_probe_identity_check + CHECK (validator_id ~ '^[a-z0-9][a-z0-9-]{0,62}$' + AND token_profile ~ '^[a-z0-9][a-z0-9-]{0,127}$' + AND audience ~ '^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$' + AND probe_kind IN ('CANARY', 'REPRESENTATIVE') + AND target_generation > COALESCE(expected_active_generation, 0) + AND target_kid ~ '^[A-Za-z0-9_-]{1,64}$' + AND ((expected_active_generation IS NULL AND expected_active_kid IS NULL) + OR (expected_active_generation IS NOT NULL AND expected_active_kid IS NOT NULL + AND expected_active_generation > 0 + AND expected_active_kid ~ '^[A-Za-z0-9_-]{1,64}$')) + AND target_kid <> expected_active_kid), + CONSTRAINT account_jwt_readiness_probe_state_check + CHECK (state IN ('PLANNED', 'ISSUED', 'VERIFIED', 'RETIRED', 'CLEANED', 'EXPIRED', 'ABORTED') + AND (terminal_outcome IS NULL OR terminal_outcome IN ('EXPIRED', 'ABORTED')) + AND ((state IN ('EXPIRED', 'ABORTED', 'CLEANED') AND terminal_outcome IS NOT NULL) + OR (state NOT IN ('EXPIRED', 'ABORTED', 'CLEANED') AND terminal_outcome IS NULL))), + CONSTRAINT account_jwt_readiness_probe_evidence_check + CHECK (plan_digest ~ '^[0-9a-f]{64}$' + AND registry_version = 1 + AND entry_version > 0 + AND planned_issued_at_epoch_seconds > 0 + AND expires_at_epoch_seconds > planned_issued_at_epoch_seconds + AND (compact_token_sha256 IS NULL OR compact_token_sha256 ~ '^[0-9a-f]{64}$') + AND (signing_attempted_at_epoch_seconds IS NULL + OR (signing_attempted_at_epoch_seconds >= planned_issued_at_epoch_seconds + AND signing_attempted_at_epoch_seconds < expires_at_epoch_seconds)) + AND ((compact_token_sha256 IS NULL AND signing_attempted_at_epoch_seconds IS NULL) + OR (compact_token_sha256 IS NOT NULL AND signing_attempted_at_epoch_seconds IS NOT NULL)) + AND (state NOT IN ('ISSUED', 'VERIFIED', 'RETIRED') + OR compact_token_sha256 IS NOT NULL) + AND (verification_receipt_version IS NULL OR verification_receipt_version = 1) + AND (verification_source_entry_version IS NULL OR verification_source_entry_version > 0) + AND (verified_at_epoch_seconds IS NULL + OR (verified_at_epoch_seconds >= planned_issued_at_epoch_seconds + AND verified_at_epoch_seconds < expires_at_epoch_seconds)) + AND (verified_kid IS NULL OR verified_kid = target_kid) + AND (validator_instance_id IS NULL + OR validator_instance_id ~ '^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$') + AND (validator_binding_digest IS NULL OR validator_binding_digest ~ '^[0-9a-f]{64}$') + AND (validator_config_revision IS NULL + OR validator_config_revision ~ '^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$') + AND (validator_peer_uri IS NULL + OR validator_peer_uri ~ '^spiffe://firemud/ns/[a-z0-9-]{1,63}/sa/account-jwt-readiness-harness$') + AND (validator_peer_spki_sha256 IS NULL + OR validator_peer_spki_sha256 ~ '^[0-9a-f]{64}$') + AND (verification_receipt_sha256 IS NULL + OR verification_receipt_sha256 ~ '^[0-9a-f]{64}$') + AND ((verification_receipt_sha256 IS NULL + AND verification_receipt_version IS NULL + AND verification_source_entry_version IS NULL + AND verified_at_epoch_seconds IS NULL + AND verified_kid IS NULL + AND validator_instance_id IS NULL + AND validator_binding_digest IS NULL + AND validator_config_revision IS NULL + AND validator_peer_uri IS NULL + AND validator_peer_spki_sha256 IS NULL) + OR (verification_receipt_sha256 IS NOT NULL + AND verification_receipt_version = 1 + AND verification_source_entry_version IS NOT NULL + AND verified_at_epoch_seconds IS NOT NULL + AND verified_kid IS NOT NULL + AND validator_instance_id IS NOT NULL + AND validator_binding_digest IS NOT NULL + AND validator_config_revision IS NOT NULL + AND validator_peer_uri IS NOT NULL + AND validator_peer_spki_sha256 IS NOT NULL)) + AND (state NOT IN ('VERIFIED', 'RETIRED') OR verification_receipt_sha256 IS NOT NULL) + AND (state NOT IN ('PLANNED', 'ISSUED') OR verification_receipt_sha256 IS NULL)) +); + +-- [jooq ignore start] +CREATE FUNCTION account_jwt_readiness_plan_inventory_guard() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +DECLARE + matrix jsonb; +BEGIN + IF NEW.validator_inventory_complete THEN + RAISE EXCEPTION 'Readiness inventory is incomplete without authenticated validator evidence' + USING ERRCODE = '23514'; + END IF; + matrix := NEW.applicability_matrix_json::jsonb; + IF matrix ->> 'inventoryStatus' <> 'PARTIAL_UNCONFIRMED' + OR matrix ->> 'schemaVersion' <> '1' + OR jsonb_array_length(matrix -> 'validators') <> 1 + OR matrix #>> '{validators,0,validatorId}' <> 'account-service' + OR jsonb_array_length(matrix #> '{validators,0,applicableProfiles}') <> 3 + OR NOT (matrix #> '{validators,0,applicableProfiles}' @> + '[{"tokenProfile":"control-ui","audience":"control-ui"}]'::jsonb) + OR NOT (matrix #> '{validators,0,applicableProfiles}' @> + '[{"tokenProfile":"player-bootstrap","audience":"player-bootstrap"}]'::jsonb) + OR NOT (matrix #> '{validators,0,applicableProfiles}' @> + '[{"tokenProfile":"game-session-account-delegation","audience":"account-service"}]'::jsonb) THEN + RAISE EXCEPTION 'Readiness applicability must bind the exact partial Account profile set' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER account_jwt_readiness_plan_inventory + BEFORE INSERT ON account_jwt_readiness_probe_plans + FOR EACH ROW EXECUTE FUNCTION account_jwt_readiness_plan_inventory_guard(); + +CREATE FUNCTION account_jwt_readiness_plan_immutable_guard() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'Account JWT readiness probe plans are immutable' USING ERRCODE = '23514'; +END; +$$; + +CREATE TRIGGER account_jwt_readiness_plan_immutable + BEFORE UPDATE OR DELETE ON account_jwt_readiness_probe_plans + FOR EACH ROW EXECUTE FUNCTION account_jwt_readiness_plan_immutable_guard(); + +CREATE FUNCTION account_jwt_readiness_entry_lifecycle_guard() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +DECLARE + plan_row account_jwt_readiness_probe_plans%ROWTYPE; +BEGIN + IF TG_OP = 'INSERT' THEN + IF NEW.state <> 'PLANNED' + OR NEW.entry_version <> 1 + OR NEW.terminal_outcome IS NOT NULL + OR NEW.compact_token_sha256 IS NOT NULL + OR NEW.signing_attempted_at_epoch_seconds IS NOT NULL + OR NEW.verification_receipt_sha256 IS NOT NULL THEN + RAISE EXCEPTION 'Account JWT readiness entries must begin PLANNED' USING ERRCODE = '23514'; + END IF; + SELECT * INTO plan_row + FROM account_jwt_readiness_probe_plans + WHERE rotation_operation_id = NEW.rotation_operation_id + AND plan_digest = NEW.plan_digest; + IF NOT FOUND + OR NEW.target_generation IS DISTINCT FROM plan_row.target_generation + OR NEW.target_kid IS DISTINCT FROM plan_row.target_kid + OR NEW.expected_active_generation IS DISTINCT FROM plan_row.expected_active_generation + OR NEW.expected_active_kid IS DISTINCT FROM plan_row.expected_active_kid + OR NEW.planned_issued_at_epoch_seconds IS DISTINCT FROM plan_row.not_before_epoch_seconds + OR NEW.expires_at_epoch_seconds IS DISTINCT FROM plan_row.expires_at_epoch_seconds THEN + RAISE EXCEPTION 'Account JWT readiness entry differs from its immutable plan' + USING ERRCODE = '23514'; + END IF; + IF NEW.probe_kind = 'CANARY' THEN + IF NEW.validator_id <> 'account-service' + OR NEW.token_profile <> 'account-jwt-readiness-canary' + OR NEW.audience <> 'firemud-account-jwt-readiness' THEN + RAISE EXCEPTION 'Account JWT readiness canary shape is not fixed' + USING ERRCODE = '23514'; + END IF; + ELSIF NOT EXISTS ( + SELECT 1 + FROM jsonb_array_elements(plan_row.applicability_matrix_json::jsonb -> 'validators') + AS validator(value) + CROSS JOIN LATERAL jsonb_array_elements(validator.value -> 'applicableProfiles') + AS applicable(value) + WHERE validator.value ->> 'validatorId' = NEW.validator_id + AND applicable.value ->> 'tokenProfile' = NEW.token_profile + AND applicable.value ->> 'audience' = NEW.audience + ) THEN + RAISE EXCEPTION 'Account JWT readiness profile is outside its applicability matrix' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; + END IF; + + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'Account JWT readiness evidence is retained' USING ERRCODE = '23514'; + END IF; + + IF NEW.rotation_operation_id IS DISTINCT FROM OLD.rotation_operation_id + OR NEW.plan_digest IS DISTINCT FROM OLD.plan_digest + OR NEW.validator_id IS DISTINCT FROM OLD.validator_id + OR NEW.token_profile IS DISTINCT FROM OLD.token_profile + OR NEW.audience IS DISTINCT FROM OLD.audience + OR NEW.probe_kind IS DISTINCT FROM OLD.probe_kind + OR NEW.jti IS DISTINCT FROM OLD.jti + OR NEW.target_generation IS DISTINCT FROM OLD.target_generation + OR NEW.target_kid IS DISTINCT FROM OLD.target_kid + OR NEW.expected_active_generation IS DISTINCT FROM OLD.expected_active_generation + OR NEW.expected_active_kid IS DISTINCT FROM OLD.expected_active_kid + OR NEW.registry_version IS DISTINCT FROM OLD.registry_version + OR NEW.planned_issued_at_epoch_seconds IS DISTINCT FROM OLD.planned_issued_at_epoch_seconds + OR NEW.expires_at_epoch_seconds IS DISTINCT FROM OLD.expires_at_epoch_seconds THEN + RAISE EXCEPTION 'Account JWT readiness probe identity is immutable' USING ERRCODE = '23514'; + END IF; + + IF NEW.entry_version <> OLD.entry_version + 1 THEN + RAISE EXCEPTION 'Account JWT readiness entry version must advance once' USING ERRCODE = '23514'; + END IF; + + IF OLD.state = 'PLANNED' + AND NEW.state = 'PLANNED' + AND OLD.compact_token_sha256 IS NULL + AND NEW.compact_token_sha256 IS NOT NULL + AND NEW.signing_attempted_at_epoch_seconds IS NOT NULL + AND NEW.signing_attempted_at_epoch_seconds >= OLD.planned_issued_at_epoch_seconds + AND NEW.signing_attempted_at_epoch_seconds < OLD.expires_at_epoch_seconds + AND NEW.verification_receipt_sha256 IS NULL + AND CURRENT_TIMESTAMP >= to_timestamp(OLD.planned_issued_at_epoch_seconds) + AND CURRENT_TIMESTAMP < to_timestamp(OLD.expires_at_epoch_seconds) + AND NEW.terminal_outcome IS NULL THEN + RETURN NEW; + END IF; + + IF OLD.state = 'PLANNED' + AND NEW.state = 'ISSUED' + AND OLD.compact_token_sha256 IS NOT NULL + AND NEW.compact_token_sha256 = OLD.compact_token_sha256 + AND NEW.signing_attempted_at_epoch_seconds = OLD.signing_attempted_at_epoch_seconds + AND NEW.verification_receipt_sha256 IS NULL + AND CURRENT_TIMESTAMP >= to_timestamp(OLD.planned_issued_at_epoch_seconds) + AND CURRENT_TIMESTAMP < to_timestamp(OLD.expires_at_epoch_seconds) + AND NEW.terminal_outcome IS NULL THEN + RETURN NEW; + END IF; + + IF OLD.state = 'ISSUED' AND NEW.state = 'VERIFIED' THEN + SELECT * INTO plan_row + FROM account_jwt_readiness_probe_plans + WHERE rotation_operation_id = NEW.rotation_operation_id + AND plan_digest = NEW.plan_digest; + IF NOT FOUND + OR NEW.target_generation IS DISTINCT FROM plan_row.target_generation + OR NEW.target_kid IS DISTINCT FROM plan_row.target_kid + OR NEW.compact_token_sha256 IS DISTINCT FROM OLD.compact_token_sha256 + OR NEW.signing_attempted_at_epoch_seconds + IS DISTINCT FROM OLD.signing_attempted_at_epoch_seconds + OR NEW.verification_receipt_version IS DISTINCT FROM 1 + OR NEW.verification_source_entry_version IS DISTINCT FROM OLD.entry_version + OR NEW.entry_version IS DISTINCT FROM OLD.entry_version + 1 + OR NEW.verified_kid IS DISTINCT FROM OLD.target_kid + OR NEW.verified_at_epoch_seconds IS NULL + OR NEW.verified_at_epoch_seconds < OLD.planned_issued_at_epoch_seconds + OR NEW.verified_at_epoch_seconds >= OLD.expires_at_epoch_seconds + OR to_timestamp(NEW.verified_at_epoch_seconds) > CURRENT_TIMESTAMP + OR NEW.validator_id IS DISTINCT FROM 'account-service' + OR NEW.validator_peer_uri IS DISTINCT FROM + 'spiffe://firemud/ns/' || plan_row.kubernetes_namespace || '/sa/account-jwt-readiness-harness' + OR CURRENT_TIMESTAMP < to_timestamp(OLD.planned_issued_at_epoch_seconds) + OR CURRENT_TIMESTAMP >= to_timestamp(OLD.expires_at_epoch_seconds) + OR NEW.terminal_outcome IS NOT NULL THEN + RAISE EXCEPTION 'Verified readiness probe differs from its current immutable plan' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; + END IF; + + IF OLD.state IN ('PLANNED', 'ISSUED', 'VERIFIED') + AND NEW.state = 'ABORTED' + AND NEW.compact_token_sha256 IS NOT DISTINCT FROM OLD.compact_token_sha256 + AND NEW.signing_attempted_at_epoch_seconds IS NOT DISTINCT FROM OLD.signing_attempted_at_epoch_seconds + AND NEW.verification_receipt_sha256 IS NOT DISTINCT FROM OLD.verification_receipt_sha256 + AND NEW.verification_receipt_version IS NOT DISTINCT FROM OLD.verification_receipt_version + AND NEW.verification_source_entry_version IS NOT DISTINCT FROM OLD.verification_source_entry_version + AND NEW.verified_at_epoch_seconds IS NOT DISTINCT FROM OLD.verified_at_epoch_seconds + AND NEW.verified_kid IS NOT DISTINCT FROM OLD.verified_kid + AND NEW.validator_instance_id IS NOT DISTINCT FROM OLD.validator_instance_id + AND NEW.validator_binding_digest IS NOT DISTINCT FROM OLD.validator_binding_digest + AND NEW.validator_config_revision IS NOT DISTINCT FROM OLD.validator_config_revision + AND NEW.validator_peer_uri IS NOT DISTINCT FROM OLD.validator_peer_uri + AND NEW.validator_peer_spki_sha256 IS NOT DISTINCT FROM OLD.validator_peer_spki_sha256 + AND NEW.terminal_outcome = 'ABORTED' THEN + RETURN NEW; + END IF; + + IF OLD.state IN ('PLANNED', 'ISSUED', 'VERIFIED') + AND NEW.state = 'EXPIRED' + AND CURRENT_TIMESTAMP >= to_timestamp(OLD.expires_at_epoch_seconds) + AND NEW.compact_token_sha256 IS NOT DISTINCT FROM OLD.compact_token_sha256 + AND NEW.signing_attempted_at_epoch_seconds IS NOT DISTINCT FROM OLD.signing_attempted_at_epoch_seconds + AND NEW.verification_receipt_sha256 IS NOT DISTINCT FROM OLD.verification_receipt_sha256 + AND NEW.verification_receipt_version IS NOT DISTINCT FROM OLD.verification_receipt_version + AND NEW.verification_source_entry_version IS NOT DISTINCT FROM OLD.verification_source_entry_version + AND NEW.verified_at_epoch_seconds IS NOT DISTINCT FROM OLD.verified_at_epoch_seconds + AND NEW.verified_kid IS NOT DISTINCT FROM OLD.verified_kid + AND NEW.validator_instance_id IS NOT DISTINCT FROM OLD.validator_instance_id + AND NEW.validator_binding_digest IS NOT DISTINCT FROM OLD.validator_binding_digest + AND NEW.validator_config_revision IS NOT DISTINCT FROM OLD.validator_config_revision + AND NEW.validator_peer_uri IS NOT DISTINCT FROM OLD.validator_peer_uri + AND NEW.validator_peer_spki_sha256 IS NOT DISTINCT FROM OLD.validator_peer_spki_sha256 + AND NEW.terminal_outcome = 'EXPIRED' THEN + RETURN NEW; + END IF; + + IF OLD.state IN ('ABORTED', 'EXPIRED') + AND NEW.state = 'CLEANED' + AND NEW.terminal_outcome = OLD.terminal_outcome + AND NEW.compact_token_sha256 IS NOT DISTINCT FROM OLD.compact_token_sha256 + AND NEW.signing_attempted_at_epoch_seconds IS NOT DISTINCT FROM OLD.signing_attempted_at_epoch_seconds + AND NEW.verification_receipt_sha256 IS NOT DISTINCT FROM OLD.verification_receipt_sha256 + AND NEW.verification_receipt_version IS NOT DISTINCT FROM OLD.verification_receipt_version + AND NEW.verification_source_entry_version IS NOT DISTINCT FROM OLD.verification_source_entry_version + AND NEW.verified_at_epoch_seconds IS NOT DISTINCT FROM OLD.verified_at_epoch_seconds + AND NEW.verified_kid IS NOT DISTINCT FROM OLD.verified_kid + AND NEW.validator_instance_id IS NOT DISTINCT FROM OLD.validator_instance_id + AND NEW.validator_binding_digest IS NOT DISTINCT FROM OLD.validator_binding_digest + AND NEW.validator_config_revision IS NOT DISTINCT FROM OLD.validator_config_revision + AND NEW.validator_peer_uri IS NOT DISTINCT FROM OLD.validator_peer_uri + AND NEW.validator_peer_spki_sha256 IS NOT DISTINCT FROM OLD.validator_peer_spki_sha256 THEN + RETURN NEW; + END IF; + + -- This table records bounded non-authorizing observations only. RETIRED and every promotion + -- transition remain unavailable until their separate Account owner contracts are implemented. + RAISE EXCEPTION 'Account JWT readiness probe lifecycle transition is unavailable' USING ERRCODE = '23514'; +END; +$$; + +CREATE TRIGGER account_jwt_readiness_entry_lifecycle + BEFORE INSERT OR UPDATE OR DELETE ON account_jwt_readiness_probe_entries + FOR EACH ROW EXECUTE FUNCTION account_jwt_readiness_entry_lifecycle_guard(); +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V49__account_jwt_signer_promotion_lifecycle.sql b/services/account-service/src/main/resources/db/migration/V49__account_jwt_signer_promotion_lifecycle.sql new file mode 100644 index 0000000000..edee4e5601 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V49__account_jwt_signer_promotion_lifecycle.sql @@ -0,0 +1,570 @@ +-- Forward-only lifecycle extension for the existing Account-owned signer authority. The +-- generation operation remains immutable; one separate promotion operation binds it to the +-- authenticated Secret/JWKS/probe evidence and owns the PREPARED -> COMMITTED|ABORTED CAS. + +ALTER TABLE account_jwt_signer_promotion_operations + DROP CONSTRAINT account_jwt_signer_promotion_action_check; + +ALTER TABLE account_jwt_signer_promotion_operations + DROP CONSTRAINT account_jwt_signer_promotion_slots_check; + +ALTER TABLE account_jwt_signer_promotion_operations + DROP CONSTRAINT account_jwt_signer_promotion_status_check; + +ALTER TABLE account_jwt_signer_promotion_operations + ADD COLUMN generation_operation_id UUID, + ADD COLUMN expected_cluster_incarnation_uid UUID, + ADD COLUMN expected_namespace_uid UUID, + ADD COLUMN materializer_trust_binding_digest VARCHAR(64), + ADD COLUMN materializer_trust_config_revision VARCHAR(128), + ADD COLUMN api_binding_digest VARCHAR(64), + ADD COLUMN api_config_revision VARCHAR(128), + ADD COLUMN expected_private_secret_uid UUID, + ADD COLUMN expected_public_config_map_uid UUID, + ADD COLUMN prepublication_intent_digest VARCHAR(64), + ADD COLUMN prepublication_receipt_digest VARCHAR(64), + ADD COLUMN mounted_observation_digest VARCHAR(64), + ADD COLUMN readiness_plan_digest VARCHAR(64), + ADD COLUMN readiness_evidence_digest VARCHAR(64), + ADD COLUMN expected_public_jwks_json TEXT, + ADD COLUMN expected_active_generation_marker_json TEXT, + ADD COLUMN private_promotion_observed_resource_version VARCHAR(256), + ADD COLUMN private_promotion_receipt_digest VARCHAR(64), + ADD COLUMN private_promotion_dispatched_at TIMESTAMPTZ, + ADD COLUMN active_jwks_observed_resource_version VARCHAR(256), + ADD COLUMN active_jwks_public_data_digest VARCHAR(64), + ADD COLUMN active_jwks_receipt_digest VARCHAR(64), + ADD CONSTRAINT account_jwt_signer_promotion_generation_fk + FOREIGN KEY (generation_operation_id) + REFERENCES account_jwt_signer_generation_operations(operation_id) + ON DELETE RESTRICT, + ADD CONSTRAINT account_jwt_signer_promotion_lifecycle_action_check + CHECK ((operation_action = 'MATERIALIZE_PENDING' + AND allowed_private_slots_canonical_bytes = '\x5b2270656e64696e67225d'::bytea) + OR (operation_action = 'PROMOTE_PENDING' + AND allowed_private_slots_canonical_bytes = + '\x5b2263757272656e74222c2270656e64696e67222c2270726576696f7573225d'::bytea)), + ADD CONSTRAINT account_jwt_signer_promotion_lifecycle_status_check + CHECK (status IN ('PREPARED', 'COMMITTED', 'ABORTED')), + ADD CONSTRAINT account_jwt_signer_promotion_lifecycle_identity_check + CHECK (operation_action <> 'PROMOTE_PENDING' + OR (generation_operation_id IS NOT NULL + AND expected_cluster_incarnation_uid IS NOT NULL + AND expected_namespace_uid IS NOT NULL + AND materializer_trust_binding_digest IS NOT NULL + AND materializer_trust_binding_digest ~ '^[0-9a-f]{64}$' + AND materializer_trust_config_revision IS NOT NULL + AND materializer_trust_config_revision ~ '^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$' + AND api_binding_digest IS NOT NULL + AND api_binding_digest ~ '^[0-9a-f]{64}$' + AND api_config_revision IS NOT NULL + AND api_config_revision ~ '^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$' + AND expected_private_secret_uid IS NOT NULL + AND expected_public_config_map_uid IS NOT NULL + AND prepublication_intent_digest IS NOT NULL + AND prepublication_intent_digest ~ '^[0-9a-f]{64}$' + AND prepublication_receipt_digest IS NOT NULL + AND prepublication_receipt_digest ~ '^[0-9a-f]{64}$' + AND mounted_observation_digest IS NOT NULL + AND mounted_observation_digest ~ '^[0-9a-f]{64}$' + AND readiness_plan_digest IS NOT NULL + AND readiness_plan_digest ~ '^[0-9a-f]{64}$' + AND readiness_evidence_digest IS NOT NULL + AND readiness_evidence_digest ~ '^[0-9a-f]{64}$' + AND expected_public_jwks_json IS NOT NULL + AND expected_active_generation_marker_json IS NOT NULL)), + ADD CONSTRAINT account_jwt_signer_promotion_lifecycle_uid_check + CHECK ((expected_cluster_incarnation_uid IS NULL + OR expected_cluster_incarnation_uid <> '00000000-0000-0000-0000-000000000000'::UUID) + AND (expected_namespace_uid IS NULL + OR expected_namespace_uid <> '00000000-0000-0000-0000-000000000000'::UUID) + AND (expected_private_secret_uid IS NULL + OR expected_private_secret_uid <> '00000000-0000-0000-0000-000000000000'::UUID) + AND (expected_public_config_map_uid IS NULL + OR expected_public_config_map_uid <> '00000000-0000-0000-0000-000000000000'::UUID)), + ADD CONSTRAINT account_jwt_signer_promotion_lifecycle_digest_check + CHECK ((materializer_trust_binding_digest IS NULL + OR materializer_trust_binding_digest ~ '^[0-9a-f]{64}$') + AND (api_binding_digest IS NULL OR api_binding_digest ~ '^[0-9a-f]{64}$') + AND (prepublication_intent_digest IS NULL + OR prepublication_intent_digest ~ '^[0-9a-f]{64}$') + AND (prepublication_receipt_digest IS NULL + OR prepublication_receipt_digest ~ '^[0-9a-f]{64}$') + AND (mounted_observation_digest IS NULL + OR mounted_observation_digest ~ '^[0-9a-f]{64}$') + AND (readiness_plan_digest IS NULL + OR readiness_plan_digest ~ '^[0-9a-f]{64}$') + AND (readiness_evidence_digest IS NULL + OR readiness_evidence_digest ~ '^[0-9a-f]{64}$') + AND (private_promotion_receipt_digest IS NULL + OR private_promotion_receipt_digest ~ '^[0-9a-f]{64}$') + AND (active_jwks_public_data_digest IS NULL + OR active_jwks_public_data_digest ~ '^[0-9a-f]{64}$') + AND (active_jwks_receipt_digest IS NULL + OR active_jwks_receipt_digest ~ '^[0-9a-f]{64}$')), + ADD CONSTRAINT account_jwt_signer_promotion_lifecycle_rv_check + CHECK ((private_promotion_observed_resource_version IS NULL + OR (private_promotion_observed_resource_version ~ '^[!-~]+$' + AND char_length(private_promotion_observed_resource_version) BETWEEN 1 AND 256)) + AND (active_jwks_observed_resource_version IS NULL + OR (active_jwks_observed_resource_version ~ '^[!-~]+$' + AND char_length(active_jwks_observed_resource_version) BETWEEN 1 AND 256))), + ADD CONSTRAINT account_jwt_signer_promotion_lifecycle_content_check + CHECK ((expected_public_jwks_json IS NULL OR octet_length(expected_public_jwks_json) BETWEEN 1 AND 262144) + AND (expected_active_generation_marker_json IS NULL + OR octet_length(expected_active_generation_marker_json) BETWEEN 1 AND 16384)), + ADD CONSTRAINT account_jwt_signer_promotion_dispatch_check + CHECK ((private_promotion_receipt_digest IS NULL + OR private_promotion_dispatched_at IS NOT NULL) + AND (status <> 'COMMITTED' + OR (private_promotion_dispatched_at IS NOT NULL + AND private_promotion_receipt_digest IS NOT NULL + AND active_jwks_receipt_digest IS NOT NULL)) + AND (status <> 'ABORTED' + OR (private_promotion_dispatched_at IS NULL + AND private_promotion_receipt_digest IS NULL + AND active_jwks_receipt_digest IS NULL))); + +-- Enrollment is admitted only after both independently protected bindings and a live read of the +-- fixed pre-created public ConfigMap agree on the environment/cluster/namespace incarnation. +-- Existing rows with NULL pins are intentionally not backfilled or promoted. +ALTER TABLE account_jwt_signer_desired_states + ADD COLUMN enrollment_cluster_incarnation_uid UUID, + ADD COLUMN enrollment_namespace_uid UUID, + ADD COLUMN enrollment_materializer_binding_digest VARCHAR(64), + ADD COLUMN enrollment_materializer_config_revision VARCHAR(128), + ADD COLUMN enrollment_api_binding_digest VARCHAR(64), + ADD COLUMN enrollment_api_config_revision VARCHAR(128), + ADD COLUMN enrollment_public_config_map_uid UUID, + ADD COLUMN enrollment_public_config_map_resource_version VARCHAR(256), + ADD COLUMN enrollment_public_config_map_snapshot_digest VARCHAR(64), + ADD CONSTRAINT account_jwt_signer_enrollment_shape_check + CHECK ((enrollment_cluster_incarnation_uid IS NULL + AND enrollment_namespace_uid IS NULL + AND enrollment_materializer_binding_digest IS NULL + AND enrollment_materializer_config_revision IS NULL + AND enrollment_api_binding_digest IS NULL + AND enrollment_api_config_revision IS NULL + AND enrollment_public_config_map_uid IS NULL + AND enrollment_public_config_map_resource_version IS NULL + AND enrollment_public_config_map_snapshot_digest IS NULL) + OR (enrollment_cluster_incarnation_uid <> '00000000-0000-0000-0000-000000000000'::UUID + AND enrollment_cluster_incarnation_uid IS NOT NULL + AND enrollment_namespace_uid IS NOT NULL + AND enrollment_namespace_uid <> '00000000-0000-0000-0000-000000000000'::UUID + AND enrollment_materializer_binding_digest IS NOT NULL + AND enrollment_materializer_binding_digest ~ '^[0-9a-f]{64}$' + AND enrollment_materializer_config_revision IS NOT NULL + AND enrollment_materializer_config_revision ~ '^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$' + AND enrollment_api_binding_digest IS NOT NULL + AND enrollment_api_binding_digest ~ '^[0-9a-f]{64}$' + AND enrollment_api_config_revision IS NOT NULL + AND enrollment_api_config_revision ~ '^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$' + AND enrollment_public_config_map_uid IS NOT NULL + AND enrollment_public_config_map_uid <> '00000000-0000-0000-0000-000000000000'::UUID + AND enrollment_public_config_map_resource_version IS NOT NULL + AND enrollment_public_config_map_resource_version ~ '^[!-~]+$' + AND char_length(enrollment_public_config_map_resource_version) BETWEEN 1 AND 256 + AND enrollment_public_config_map_snapshot_digest IS NOT NULL + AND enrollment_public_config_map_snapshot_digest ~ '^[0-9a-f]{64}$')); + +-- PREPARED proof is immutable. Account first durably records its one-way peer dispatch before +-- returning mutation authority. Only the two exact public-only CAS receipts may then be filled +-- once, followed by one terminal state transition. No receipt includes, hashes, or returns +-- private Secret bytes. +-- [jooq ignore start] +CREATE OR REPLACE FUNCTION account_jwt_signer_operation_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + private_receipt_changed BOOLEAN; + private_dispatch_changed BOOLEAN; + jwks_receipt_changed BOOLEAN; +BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'Account JWT signer promotion history cannot be deleted' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_operation_immutable'; + END IF; + IF (NEW.operation_id, NEW.environment_id, NEW.cluster_id, NEW.kubernetes_namespace, + NEW.custody_mode, NEW.request_digest_version, NEW.request_digest, + NEW.expected_record_version, NEW.expected_previous_generation, NEW.expected_previous_kid, + NEW.target_generation, NEW.target_kid, NEW.target_algorithm, + NEW.target_public_key_fingerprint, NEW.expected_private_secret_resource_version, + NEW.expected_public_jwks_resource_version, NEW.expected_public_active_generation, + NEW.expected_public_active_kid, NEW.operation_action, + NEW.allowed_private_slots_canonical_bytes, NEW.generation_operation_id, + NEW.expected_cluster_incarnation_uid, NEW.expected_namespace_uid, + NEW.materializer_trust_binding_digest, NEW.materializer_trust_config_revision, + NEW.api_binding_digest, NEW.api_config_revision, NEW.expected_private_secret_uid, + NEW.expected_public_config_map_uid, NEW.prepublication_intent_digest, + NEW.prepublication_receipt_digest, NEW.mounted_observation_digest, + NEW.readiness_plan_digest, NEW.readiness_evidence_digest, + NEW.expected_public_jwks_json, NEW.expected_active_generation_marker_json, + NEW.created_at) + IS DISTINCT FROM + (OLD.operation_id, OLD.environment_id, OLD.cluster_id, OLD.kubernetes_namespace, + OLD.custody_mode, OLD.request_digest_version, OLD.request_digest, + OLD.expected_record_version, OLD.expected_previous_generation, OLD.expected_previous_kid, + OLD.target_generation, OLD.target_kid, OLD.target_algorithm, + OLD.target_public_key_fingerprint, OLD.expected_private_secret_resource_version, + OLD.expected_public_jwks_resource_version, OLD.expected_public_active_generation, + OLD.expected_public_active_kid, OLD.operation_action, + OLD.allowed_private_slots_canonical_bytes, OLD.generation_operation_id, + OLD.expected_cluster_incarnation_uid, OLD.expected_namespace_uid, + OLD.materializer_trust_binding_digest, OLD.materializer_trust_config_revision, + OLD.api_binding_digest, OLD.api_config_revision, OLD.expected_private_secret_uid, + OLD.expected_public_config_map_uid, OLD.prepublication_intent_digest, + OLD.prepublication_receipt_digest, OLD.mounted_observation_digest, + OLD.readiness_plan_digest, OLD.readiness_evidence_digest, + OLD.expected_public_jwks_json, OLD.expected_active_generation_marker_json, + OLD.created_at) THEN + RAISE EXCEPTION 'Account JWT signer promotion request is immutable' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_operation_immutable'; + END IF; + IF OLD.status <> 'PREPARED' OR NEW.status NOT IN ('PREPARED', 'COMMITTED', 'ABORTED') THEN + RAISE EXCEPTION 'Account JWT signer promotion is already terminal' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_operation_immutable'; + END IF; + + private_receipt_changed := + (NEW.private_promotion_observed_resource_version, + NEW.private_promotion_receipt_digest) + IS DISTINCT FROM + (OLD.private_promotion_observed_resource_version, + OLD.private_promotion_receipt_digest); + private_dispatch_changed := + NEW.private_promotion_dispatched_at IS DISTINCT FROM OLD.private_promotion_dispatched_at; + jwks_receipt_changed := + (NEW.active_jwks_observed_resource_version, NEW.active_jwks_public_data_digest, + NEW.active_jwks_receipt_digest) + IS DISTINCT FROM + (OLD.active_jwks_observed_resource_version, OLD.active_jwks_public_data_digest, + OLD.active_jwks_receipt_digest); + + IF private_receipt_changed THEN + IF OLD.private_promotion_receipt_digest IS NOT NULL + OR NEW.private_promotion_receipt_digest IS NULL + OR NEW.private_promotion_observed_resource_version IS NULL + OR jwks_receipt_changed OR NEW.status <> 'PREPARED' THEN + RAISE EXCEPTION 'JWT private promotion receipt is not a first exact readback' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_operation_immutable'; + END IF; + END IF; + IF private_dispatch_changed THEN + IF OLD.private_promotion_dispatched_at IS NOT NULL + OR NEW.private_promotion_dispatched_at IS NULL + OR NEW.status <> 'PREPARED' + OR private_receipt_changed OR jwks_receipt_changed THEN + RAISE EXCEPTION 'JWT private promotion dispatch is not a first durable authorization' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_operation_immutable'; + END IF; + END IF; + IF jwks_receipt_changed THEN + IF OLD.active_jwks_receipt_digest IS NOT NULL + OR NEW.active_jwks_receipt_digest IS NULL + OR NEW.active_jwks_observed_resource_version IS NULL + OR NEW.active_jwks_public_data_digest IS NULL + OR OLD.private_promotion_receipt_digest IS NULL + OR NEW.status <> 'PREPARED' THEN + RAISE EXCEPTION 'JWT active JWKS receipt is not a first exact readback' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_operation_immutable'; + END IF; + END IF; + IF NEW.status = OLD.status AND NOT private_dispatch_changed + AND NOT private_receipt_changed AND NOT jwks_receipt_changed THEN + RAISE EXCEPTION 'JWT promotion update has no exact receipt transition' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_operation_immutable'; + END IF; + IF NEW.status = 'COMMITTED' + AND (NEW.private_promotion_dispatched_at IS NULL + OR NEW.private_promotion_receipt_digest IS NULL + OR NEW.active_jwks_receipt_digest IS NULL) THEN + RAISE EXCEPTION 'JWT promotion cannot commit without both exact resource receipts' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_operation_immutable'; + END IF; + IF NEW.status = 'ABORTED' + AND (OLD.private_promotion_dispatched_at IS NOT NULL + OR OLD.private_promotion_receipt_digest IS NOT NULL + OR OLD.active_jwks_receipt_digest IS NOT NULL) THEN + RAISE EXCEPTION 'Dispatched JWT promotion must remain PREPARED for reconciliation' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_operation_immutable'; + END IF; + RETURN NEW; +END; +$$; + +CREATE OR REPLACE FUNCTION account_jwt_signer_desired_state_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + operation_row RECORD; +BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'Account JWT signer desired state cannot be deleted' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_desired_state_immutable'; + END IF; + IF (NEW.environment_id, NEW.cluster_id, NEW.kubernetes_namespace, NEW.custody_mode, + NEW.private_secret_name, NEW.public_jwks_config_map_name, NEW.created_at, + NEW.enrollment_cluster_incarnation_uid, NEW.enrollment_namespace_uid, + NEW.enrollment_materializer_binding_digest, NEW.enrollment_materializer_config_revision, + NEW.enrollment_api_binding_digest, NEW.enrollment_api_config_revision, + NEW.enrollment_public_config_map_uid, NEW.enrollment_public_config_map_resource_version, + NEW.enrollment_public_config_map_snapshot_digest) + IS DISTINCT FROM + (OLD.environment_id, OLD.cluster_id, OLD.kubernetes_namespace, OLD.custody_mode, + OLD.private_secret_name, OLD.public_jwks_config_map_name, OLD.created_at, + OLD.enrollment_cluster_incarnation_uid, OLD.enrollment_namespace_uid, + OLD.enrollment_materializer_binding_digest, OLD.enrollment_materializer_config_revision, + OLD.enrollment_api_binding_digest, OLD.enrollment_api_config_revision, + OLD.enrollment_public_config_map_uid, OLD.enrollment_public_config_map_resource_version, + OLD.enrollment_public_config_map_snapshot_digest) + OR NEW.record_version <> OLD.record_version + 1 THEN + RAISE EXCEPTION 'Account JWT signer desired state permits only a versioned owner transition' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_desired_state_immutable'; + END IF; + + -- Creating a generation operation is the only transition from an idle state to a new key + -- request. Active identities and publication fences remain unchanged. + IF OLD.generation_operation_id IS NULL AND OLD.prepared_operation_id IS NULL + AND NEW.generation_operation_id IS NOT NULL AND NEW.prepared_operation_id IS NULL + AND NEW.durable_active_generation IS NOT DISTINCT FROM OLD.durable_active_generation + AND NEW.durable_active_kid IS NOT DISTINCT FROM OLD.durable_active_kid + AND NEW.published_active_generation IS NOT DISTINCT FROM OLD.published_active_generation + AND NEW.published_active_kid IS NOT DISTINCT FROM OLD.published_active_kid THEN + IF OLD.enrollment_cluster_incarnation_uid IS NULL + OR OLD.enrollment_namespace_uid IS NULL + OR OLD.enrollment_materializer_binding_digest IS NULL + OR OLD.enrollment_api_binding_digest IS NULL + OR OLD.enrollment_public_config_map_uid IS NULL THEN + RAISE EXCEPTION 'JWT signer state has no independently protected enrollment pins' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_generation_operation_binding'; + END IF; + PERFORM 1 FROM account_jwt_signer_generation_operations AS generation_op + WHERE generation_op.operation_id = NEW.generation_operation_id + AND generation_op.environment_id = NEW.environment_id + AND generation_op.cluster_id = NEW.cluster_id + AND generation_op.kubernetes_namespace = NEW.kubernetes_namespace + AND generation_op.custody_mode = NEW.custody_mode + AND generation_op.expected_record_version = OLD.record_version + AND generation_op.expected_previous_generation IS NOT DISTINCT FROM OLD.durable_active_generation + AND generation_op.expected_previous_kid IS NOT DISTINCT FROM OLD.durable_active_kid + AND generation_op.expected_published_generation IS NOT DISTINCT FROM OLD.published_active_generation + AND generation_op.expected_published_kid IS NOT DISTINCT FROM OLD.published_active_kid; + IF NOT FOUND THEN + RAISE EXCEPTION 'JWT generation pointer is not the exact current Account operation' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_generation_operation_binding'; + END IF; + RETURN NEW; + END IF; + + -- Enter PREPARED only after insertion of the exact durable promotion request. + IF OLD.generation_operation_id IS NOT NULL AND OLD.prepared_operation_id IS NULL + AND NEW.generation_operation_id IS NULL AND NEW.prepared_operation_id IS NOT NULL + AND NEW.durable_active_generation IS NOT DISTINCT FROM OLD.durable_active_generation + AND NEW.durable_active_kid IS NOT DISTINCT FROM OLD.durable_active_kid + AND NEW.published_active_generation IS NOT DISTINCT FROM OLD.published_active_generation + AND NEW.published_active_kid IS NOT DISTINCT FROM OLD.published_active_kid THEN + SELECT promotion.* INTO operation_row + FROM account_jwt_signer_promotion_operations AS promotion + WHERE promotion.operation_id = NEW.prepared_operation_id + AND promotion.generation_operation_id = OLD.generation_operation_id + AND promotion.environment_id = OLD.environment_id + AND promotion.cluster_id = OLD.cluster_id + AND promotion.kubernetes_namespace = OLD.kubernetes_namespace + AND promotion.custody_mode = OLD.custody_mode + AND promotion.expected_record_version = OLD.record_version + AND promotion.expected_previous_generation IS NOT DISTINCT FROM OLD.durable_active_generation + AND promotion.expected_previous_kid IS NOT DISTINCT FROM OLD.durable_active_kid + AND promotion.expected_public_active_generation IS NOT DISTINCT FROM OLD.published_active_generation + AND promotion.expected_public_active_kid IS NOT DISTINCT FROM OLD.published_active_kid + AND promotion.status = 'PREPARED' + AND promotion.operation_action = 'PROMOTE_PENDING'; + IF NOT FOUND THEN + RAISE EXCEPTION 'JWT PREPARED pointer is not the exact Account promotion operation' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_prepared_operation_binding'; + END IF; + RETURN NEW; + END IF; + + -- Close only the exact PREPARED operation. COMMITTED changes both active fences to target; + -- ABORTED preserves both previous fences. No resource observation can perform either CAS. + IF OLD.generation_operation_id IS NULL AND OLD.prepared_operation_id IS NOT NULL + AND NEW.generation_operation_id IS NULL AND NEW.prepared_operation_id IS NULL THEN + SELECT promotion.* INTO operation_row + FROM account_jwt_signer_promotion_operations AS promotion + WHERE promotion.operation_id = OLD.prepared_operation_id + AND promotion.environment_id = OLD.environment_id + AND promotion.cluster_id = OLD.cluster_id + AND promotion.kubernetes_namespace = OLD.kubernetes_namespace + AND promotion.custody_mode = OLD.custody_mode + AND promotion.expected_record_version + 1 = OLD.record_version + AND promotion.status IN ('COMMITTED', 'ABORTED'); + IF NOT FOUND THEN + RAISE EXCEPTION 'JWT promotion terminal transition has no exact durable result' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_prepared_operation_binding'; + END IF; + IF operation_row.status = 'COMMITTED' THEN + IF NEW.durable_active_generation IS DISTINCT FROM operation_row.target_generation + OR NEW.durable_active_kid IS DISTINCT FROM operation_row.target_kid + OR NEW.published_active_generation IS DISTINCT FROM operation_row.target_generation + OR NEW.published_active_kid IS DISTINCT FROM operation_row.target_kid THEN + RAISE EXCEPTION 'Committed JWT signer and published active fences must equal target' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_prepared_operation_binding'; + END IF; + ELSIF NEW.durable_active_generation IS DISTINCT FROM OLD.durable_active_generation + OR NEW.durable_active_kid IS DISTINCT FROM OLD.durable_active_kid + OR NEW.published_active_generation IS DISTINCT FROM OLD.published_active_generation + OR NEW.published_active_kid IS DISTINCT FROM OLD.published_active_kid THEN + RAISE EXCEPTION 'Aborted JWT signer operation must preserve previous active fences' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_prepared_operation_binding'; + END IF; + RETURN NEW; + END IF; + + RAISE EXCEPTION 'Account JWT signer state transition is not in the lifecycle CAS' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_generation_operation_binding'; +END; +$$; + +CREATE FUNCTION account_jwt_signer_promotion_insert_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + state_row RECORD; + generation_row RECORD; + result_row RECORD; + plan_inventory_complete BOOLEAN; + plan_expires_at BIGINT; + entry_count BIGINT; + verified_count BIGINT; +BEGIN + IF NEW.operation_action <> 'PROMOTE_PENDING' + OR NEW.generation_operation_id IS NULL + OR NEW.expected_cluster_incarnation_uid IS NULL + OR NEW.expected_namespace_uid IS NULL + OR NEW.expected_private_secret_uid IS NULL + OR NEW.expected_public_config_map_uid IS NULL THEN + RAISE EXCEPTION 'Promotion request lacks its exact lifecycle binding' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_promotion_insert_binding'; + END IF; + + -- Lock order is desired state, then source generation, then immutable evidence. + SELECT * INTO state_row FROM account_jwt_signer_desired_states + WHERE environment_id = NEW.environment_id FOR UPDATE; + IF NOT FOUND THEN + RAISE EXCEPTION 'Account JWT signer desired state is missing' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_promotion_insert_binding'; + END IF; + SELECT * INTO generation_row FROM account_jwt_signer_generation_operations + WHERE operation_id = NEW.generation_operation_id FOR UPDATE; + IF NOT FOUND THEN + RAISE EXCEPTION 'Account JWT generation operation is missing' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_promotion_insert_binding'; + END IF; + SELECT * INTO result_row FROM account_jwt_signer_generation_results + WHERE operation_id = NEW.generation_operation_id FOR UPDATE; + IF NOT FOUND THEN + RAISE EXCEPTION 'Account JWT generation result is missing' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_promotion_insert_binding'; + END IF; + IF state_row.generation_operation_id IS DISTINCT FROM NEW.generation_operation_id + OR state_row.prepared_operation_id IS NOT NULL + OR state_row.record_version IS DISTINCT FROM NEW.expected_record_version + OR (state_row.cluster_id, state_row.kubernetes_namespace, state_row.custody_mode) + IS DISTINCT FROM (NEW.cluster_id, NEW.kubernetes_namespace, NEW.custody_mode) + OR (state_row.durable_active_generation, state_row.durable_active_kid) + IS DISTINCT FROM (NEW.expected_previous_generation, NEW.expected_previous_kid) + OR (state_row.published_active_generation, state_row.published_active_kid) + IS DISTINCT FROM (NEW.expected_public_active_generation, NEW.expected_public_active_kid) + OR state_row.enrollment_cluster_incarnation_uid IS DISTINCT FROM NEW.expected_cluster_incarnation_uid + OR state_row.enrollment_namespace_uid IS DISTINCT FROM NEW.expected_namespace_uid + OR state_row.enrollment_materializer_binding_digest IS DISTINCT FROM NEW.materializer_trust_binding_digest + OR state_row.enrollment_materializer_config_revision IS DISTINCT FROM NEW.materializer_trust_config_revision + OR state_row.enrollment_api_binding_digest IS DISTINCT FROM NEW.api_binding_digest + OR state_row.enrollment_api_config_revision IS DISTINCT FROM NEW.api_config_revision + OR state_row.enrollment_public_config_map_uid IS DISTINCT FROM NEW.expected_public_config_map_uid + OR generation_row.operation_id IS NULL + OR generation_row.environment_id IS DISTINCT FROM NEW.environment_id + OR generation_row.expected_cluster_incarnation_uid IS DISTINCT FROM NEW.expected_cluster_incarnation_uid + OR generation_row.expected_namespace_uid IS DISTINCT FROM NEW.expected_namespace_uid + OR generation_row.trust_binding_digest IS DISTINCT FROM NEW.materializer_trust_binding_digest + OR generation_row.trust_config_revision IS DISTINCT FROM NEW.materializer_trust_config_revision + OR generation_row.target_generation IS DISTINCT FROM NEW.target_generation + OR generation_row.target_kid IS DISTINCT FROM NEW.target_kid + OR generation_row.expected_record_version + 1 IS DISTINCT FROM result_row.desired_state_version + OR result_row.secret_uid IS DISTINCT FROM NEW.expected_private_secret_uid + OR result_row.observed_resource_version IS DISTINCT FROM NEW.expected_private_secret_resource_version + OR result_row.receipt_digest IS DISTINCT FROM NEW.generation_receipt_digest + OR result_row.public_key_fingerprint IS DISTINCT FROM NEW.target_public_key_fingerprint THEN + RAISE EXCEPTION 'JWT promotion request does not match current Account generation evidence' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_promotion_insert_binding'; + END IF; + + SELECT validator_inventory_complete, expires_at_epoch_seconds + INTO plan_inventory_complete, plan_expires_at + FROM account_jwt_readiness_probe_plans + WHERE rotation_operation_id = NEW.generation_operation_id + AND plan_digest = NEW.readiness_plan_digest FOR SHARE; + IF plan_inventory_complete IS DISTINCT FROM TRUE + OR plan_expires_at IS NULL + OR plan_expires_at <= floor(extract(epoch FROM CURRENT_TIMESTAMP))::BIGINT THEN + RAISE EXCEPTION 'JWT promotion requires current complete validator inventory proof' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_promotion_readiness_incomplete'; + END IF; + SELECT count(*), count(*) FILTER (WHERE state = 'VERIFIED' + AND verified_at_epoch_seconds < expires_at_epoch_seconds) + INTO entry_count, verified_count + FROM account_jwt_readiness_probe_entries + WHERE rotation_operation_id = NEW.generation_operation_id + AND plan_digest = NEW.readiness_plan_digest; + IF entry_count = 0 OR verified_count <> entry_count THEN + RAISE EXCEPTION 'JWT promotion requires every exact readiness probe to be VERIFIED' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_promotion_readiness_incomplete'; + END IF; + + IF NOT EXISTS ( + SELECT 1 FROM account_jwt_jwks_prepublication_intents AS intent + JOIN account_jwt_jwks_publication_receipts AS receipt + ON receipt.operation_id = intent.operation_id + AND receipt.intent_digest = intent.intent_digest + JOIN account_jwt_jwks_mount_observations AS mount + ON mount.operation_id = intent.operation_id + WHERE intent.operation_id = NEW.generation_operation_id + AND intent.intent_digest = NEW.prepublication_intent_digest + AND receipt.receipt_digest = NEW.prepublication_receipt_digest + AND mount.observation_digest = NEW.mounted_observation_digest + AND intent.config_map_uid = NEW.expected_public_config_map_uid + AND intent.api_binding_digest = NEW.api_binding_digest + AND intent.api_config_revision = NEW.api_config_revision + AND receipt.observed_resource_version = NEW.expected_public_jwks_resource_version + AND intent.public_key_fingerprint = NEW.target_public_key_fingerprint + AND intent.jwks_json = NEW.expected_public_jwks_json) THEN + RAISE EXCEPTION 'JWT promotion request does not match exact current prepublication evidence' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_promotion_insert_binding'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER account_jwt_signer_promotion_insert_guard + BEFORE INSERT ON account_jwt_signer_promotion_operations + FOR EACH ROW EXECUTE FUNCTION account_jwt_signer_promotion_insert_guard(); + +CREATE FUNCTION account_jwt_signer_promotion_no_truncate() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'Account JWT signer promotion history cannot be truncated' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_operation_immutable'; + RETURN NULL; +END; +$$; +CREATE TRIGGER account_jwt_signer_promotion_no_truncate + BEFORE TRUNCATE ON account_jwt_signer_promotion_operations + FOR EACH STATEMENT EXECUTE FUNCTION account_jwt_signer_promotion_no_truncate(); +-- [jooq ignore stop] + diff --git a/services/account-service/src/main/resources/db/migration/V50__account_jwt_readiness_single_delivery_claims.sql b/services/account-service/src/main/resources/db/migration/V50__account_jwt_readiness_single_delivery_claims.sql new file mode 100644 index 0000000000..c2d6b68277 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V50__account_jwt_readiness_single_delivery_claims.sql @@ -0,0 +1,125 @@ +-- One durable winner may emit the exact current operation's readiness probes to its authenticated +-- harness. A claim is a one-shot concurrency fence, not delivery proof, validator evidence, or +-- signer authority; it is never cleared after an ambiguous response. +CREATE TABLE account_jwt_readiness_delivery_claims ( + rotation_operation_id UUID PRIMARY KEY, + plan_digest VARCHAR(64) NOT NULL, + expected_cluster_incarnation_uid UUID NOT NULL, + expected_namespace_uid UUID NOT NULL, + materializer_trust_binding_digest VARCHAR(64) NOT NULL, + materializer_trust_config_revision VARCHAR(128) NOT NULL, + target_generation BIGINT NOT NULL, + target_kid VARCHAR(64) NOT NULL, + expected_active_generation BIGINT, + expected_active_kid VARCHAR(64), + readiness_binding_digest VARCHAR(64) NOT NULL, + readiness_config_revision VARCHAR(128) NOT NULL, + readiness_binding_valid_until_epoch_seconds BIGINT NOT NULL, + validator_id VARCHAR(63) NOT NULL, + validator_instance_id VARCHAR(128) NOT NULL, + validator_peer_uri VARCHAR(256) NOT NULL, + validator_peer_spki_sha256 VARCHAR(64) NOT NULL, + claimed_at_epoch_seconds BIGINT NOT NULL, + expires_at_epoch_seconds BIGINT NOT NULL, + claim_digest VARCHAR(64) NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT account_jwt_readiness_delivery_claim_plan_fk + FOREIGN KEY (rotation_operation_id, plan_digest) + REFERENCES account_jwt_readiness_probe_plans(rotation_operation_id, plan_digest) + ON DELETE RESTRICT, + CONSTRAINT account_jwt_readiness_delivery_claim_shape_check + CHECK (rotation_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 expected_cluster_incarnation_uid <> '00000000-0000-0000-0000-000000000000'::UUID + AND expected_namespace_uid <> '00000000-0000-0000-0000-000000000000'::UUID + AND materializer_trust_binding_digest ~ '^[0-9a-f]{64}$' + AND materializer_trust_config_revision ~ '^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$' + AND target_generation > 0 + AND target_kid ~ '^[A-Za-z0-9_-]{1,64}$' + AND ((expected_active_generation IS NULL AND expected_active_kid IS NULL) + OR (expected_active_generation > 0 + AND expected_active_kid ~ '^[A-Za-z0-9_-]{1,64}$')) + AND target_kid <> expected_active_kid + AND readiness_binding_digest ~ '^[0-9a-f]{64}$' + AND readiness_config_revision ~ '^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$' + AND readiness_binding_valid_until_epoch_seconds > claimed_at_epoch_seconds + AND validator_id = 'account-service' + AND validator_instance_id ~ '^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$' + AND validator_peer_uri ~ '^spiffe://firemud/ns/[a-z0-9-]{1,63}/sa/account-jwt-readiness-harness$' + AND validator_peer_spki_sha256 ~ '^[0-9a-f]{64}$' + AND claimed_at_epoch_seconds > 0 + AND expires_at_epoch_seconds > claimed_at_epoch_seconds + AND claim_digest ~ '^[0-9a-f]{64}$') +); + +-- [jooq ignore start] +CREATE FUNCTION account_jwt_readiness_delivery_claim_guard() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +DECLARE + plan_row account_jwt_readiness_probe_plans%ROWTYPE; + expected_entry_count integer; + actual_entry_count integer; +BEGIN + SELECT * INTO plan_row + FROM account_jwt_readiness_probe_plans + WHERE rotation_operation_id = NEW.rotation_operation_id + AND plan_digest = NEW.plan_digest; + IF NOT FOUND + OR NEW.expected_cluster_incarnation_uid IS DISTINCT FROM plan_row.expected_cluster_incarnation_uid + OR NEW.expected_namespace_uid IS DISTINCT FROM plan_row.expected_namespace_uid + OR NEW.materializer_trust_binding_digest IS DISTINCT FROM plan_row.trust_binding_digest + OR NEW.materializer_trust_config_revision IS DISTINCT FROM plan_row.trust_config_revision + OR NEW.target_generation IS DISTINCT FROM plan_row.target_generation + OR NEW.target_kid IS DISTINCT FROM plan_row.target_kid + OR NEW.expected_active_generation IS DISTINCT FROM plan_row.expected_active_generation + OR NEW.expected_active_kid IS DISTINCT FROM plan_row.expected_active_kid + OR NEW.expires_at_epoch_seconds IS DISTINCT FROM plan_row.expires_at_epoch_seconds + OR NEW.validator_id <> 'account-service' + OR NEW.readiness_binding_valid_until_epoch_seconds <= NEW.claimed_at_epoch_seconds + OR NEW.validator_peer_uri IS DISTINCT FROM + 'spiffe://firemud/ns/' || plan_row.kubernetes_namespace || '/sa/account-jwt-readiness-harness' + OR NEW.claimed_at_epoch_seconds < plan_row.not_before_epoch_seconds + OR NEW.claimed_at_epoch_seconds >= plan_row.expires_at_epoch_seconds + OR CURRENT_TIMESTAMP < to_timestamp(plan_row.not_before_epoch_seconds) + OR CURRENT_TIMESTAMP >= to_timestamp(plan_row.expires_at_epoch_seconds) THEN + RAISE EXCEPTION 'Account readiness delivery claim differs from its current exact plan' + USING ERRCODE = '23514'; + END IF; + expected_entry_count := + 1 + jsonb_array_length(plan_row.applicability_matrix_json::jsonb #> + '{validators,0,applicableProfiles}'); + SELECT COUNT(*) INTO actual_entry_count + FROM account_jwt_readiness_probe_entries + WHERE rotation_operation_id = NEW.rotation_operation_id + AND plan_digest = NEW.plan_digest + AND state = 'PLANNED' + AND compact_token_sha256 IS NULL + AND signing_attempted_at_epoch_seconds IS NULL + AND verification_receipt_sha256 IS NULL; + IF actual_entry_count <> expected_entry_count THEN + RAISE EXCEPTION 'Account readiness delivery claim requires untouched planned entries' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER account_jwt_readiness_delivery_claim_insert_guard + BEFORE INSERT ON account_jwt_readiness_delivery_claims + FOR EACH ROW EXECUTE FUNCTION account_jwt_readiness_delivery_claim_guard(); + +CREATE FUNCTION account_jwt_readiness_delivery_claim_immutable_guard() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'Account JWT readiness delivery claims are immutable' USING ERRCODE = '23514'; +END; +$$; + +CREATE TRIGGER account_jwt_readiness_delivery_claim_immutable + BEFORE UPDATE OR DELETE ON account_jwt_readiness_delivery_claims + FOR EACH ROW EXECUTE FUNCTION account_jwt_readiness_delivery_claim_immutable_guard(); +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V52__account_jwt_validator_inventory_snapshots.sql b/services/account-service/src/main/resources/db/migration/V52__account_jwt_validator_inventory_snapshots.sql new file mode 100644 index 0000000000..4861806bc2 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V52__account_jwt_validator_inventory_snapshots.sql @@ -0,0 +1,67 @@ +-- Durable immutable owner observations are bound to a readiness plan, but remain partial +-- non-authorizing evidence. A stored Deployment/ReplicaSet/Pod inventory is not probe acceptance. +CREATE TABLE account_jwt_validator_inventory_snapshots ( + snapshot_digest VARCHAR(64) PRIMARY KEY, + environment_id VARCHAR(63) NOT NULL, + cluster_id VARCHAR(128) NOT NULL, + cluster_incarnation_uid UUID NOT NULL, + kubernetes_namespace VARCHAR(63) NOT NULL, + namespace_uid UUID NOT NULL, + api_binding_revision VARCHAR(128) NOT NULL, + api_binding_digest VARCHAR(64) NOT NULL, + inventory_binding_revision VARCHAR(128) NOT NULL, + inventory_binding_digest VARCHAR(64) NOT NULL, + observed_at VARCHAR(40) NOT NULL, + canonical_snapshot BYTEA NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT account_jwt_validator_inventory_snapshot_identity_check + CHECK (snapshot_digest ~ '^[0-9a-f]{64}$' + AND environment_id ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$' + AND cluster_id ~ '^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$' + AND kubernetes_namespace ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$' + AND cluster_incarnation_uid <> '00000000-0000-0000-0000-000000000000'::UUID + AND namespace_uid <> '00000000-0000-0000-0000-000000000000'::UUID + AND api_binding_revision ~ '^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$' + AND api_binding_digest ~ '^[0-9a-f]{64}$' + AND inventory_binding_revision ~ '^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$' + AND inventory_binding_digest ~ '^[0-9a-f]{64}$' + AND length(observed_at) BETWEEN 20 AND 40 + AND observed_at ~ '^[0-9]{4}-[0-9]{2}-[0-9]{2}T.*Z$' + AND octet_length(canonical_snapshot) BETWEEN 2 AND 4194304), + CONSTRAINT account_jwt_validator_inventory_snapshot_plan_identity_unique + UNIQUE (snapshot_digest, environment_id, cluster_id, kubernetes_namespace, + cluster_incarnation_uid, namespace_uid) +); + +-- [jooq ignore start] +CREATE FUNCTION account_jwt_validator_inventory_snapshot_immutable_guard() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'Account JWT validator inventory snapshots are immutable' + USING ERRCODE = '23514'; +END; +$$; + +CREATE TRIGGER account_jwt_validator_inventory_snapshot_immutable + BEFORE UPDATE OR DELETE ON account_jwt_validator_inventory_snapshots + FOR EACH ROW EXECUTE FUNCTION account_jwt_validator_inventory_snapshot_immutable_guard(); + +CREATE TRIGGER account_jwt_validator_inventory_snapshot_no_truncate + BEFORE TRUNCATE ON account_jwt_validator_inventory_snapshots + FOR EACH STATEMENT EXECUTE FUNCTION account_jwt_validator_inventory_snapshot_immutable_guard(); +-- [jooq ignore stop] + +ALTER TABLE account_jwt_readiness_probe_plans + ADD COLUMN inventory_snapshot_digest VARCHAR(64), + ADD CONSTRAINT account_jwt_readiness_plan_inventory_snapshot_digest_check + CHECK (inventory_snapshot_digest IS NULL + OR inventory_snapshot_digest ~ '^[0-9a-f]{64}$'), + ADD CONSTRAINT account_jwt_readiness_plan_inventory_snapshot_fk + FOREIGN KEY (inventory_snapshot_digest, environment_id, cluster_id, + kubernetes_namespace, expected_cluster_incarnation_uid, expected_namespace_uid) + REFERENCES account_jwt_validator_inventory_snapshots( + snapshot_digest, environment_id, cluster_id, kubernetes_namespace, + cluster_incarnation_uid, namespace_uid) + ON DELETE RESTRICT; diff --git a/services/account-service/src/main/resources/db/migration/V74__account_control_ui_committed_issuance.sql b/services/account-service/src/main/resources/db/migration/V74__account_control_ui_committed_issuance.sql new file mode 100644 index 0000000000..3371d9d86a --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V74__account_control_ui_committed_issuance.sql @@ -0,0 +1,119 @@ +CREATE SEQUENCE account_control_ui_source_fence START WITH 1; + +CREATE TABLE account_control_ui_issuance_operations ( + request_id UUID PRIMARY KEY, + operation_id UUID NOT NULL UNIQUE, + token_jti UUID NOT NULL UNIQUE, + account_uuid UUID NOT NULL REFERENCES accounts(account_uuid), + tenant_uuid UUID NOT NULL REFERENCES account_canonical_tenant_identity_claims(canonical_tenant_id), + caller_workload VARCHAR(256) NOT NULL, + caller_context_id UUID NOT NULL, + request_mac_key_id VARCHAR(32) NOT NULL, + request_digest VARCHAR(64) NOT NULL CHECK (request_digest ~ '^[0-9a-f]{64}$'), + claims_payload BYTEA NOT NULL CHECK (octet_length(claims_payload) BETWEEN 1 AND 16384), + source_payload BYTEA NOT NULL CHECK (octet_length(source_payload) BETWEEN 1 AND 131072), + bundle_payload BYTEA NOT NULL CHECK (octet_length(bundle_payload) BETWEEN 1 AND 131072), + signer_receipt BYTEA NOT NULL CHECK (octet_length(signer_receipt) BETWEEN 1 AND 65536), + issued_at_epoch_second BIGINT NOT NULL CHECK (issued_at_epoch_second > 0), + expires_at_epoch_second BIGINT NOT NULL, + recovery_expires_at TIMESTAMPTZ NOT NULL, + status VARCHAR(16) NOT NULL CHECK (status IN ('PREPARED', 'CANDIDATE', 'COMMITTED', 'FAILED', 'REVOKING', 'REVOKED')), + token_hash VARCHAR(64) UNIQUE CHECK (token_hash ~ '^[0-9a-f]{64}$'), + pending_registry BYTEA, + active_registry BYTEA, + pending_receipt BYTEA, + committed_at TIMESTAMPTZ, + recovery_failed_at TIMESTAMPTZ, + revocation_receipt BYTEA, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CHECK (expires_at_epoch_second > issued_at_epoch_second + AND expires_at_epoch_second <= issued_at_epoch_second + 300), + CHECK ((status IN ('PREPARED','FAILED') AND token_hash IS NULL AND pending_registry IS NULL + AND active_registry IS NULL AND pending_receipt IS NULL AND committed_at IS NULL) + OR (status = 'CANDIDATE' AND token_hash IS NOT NULL AND pending_registry IS NOT NULL + AND active_registry IS NOT NULL AND pending_receipt IS NULL AND committed_at IS NULL) + OR (status = 'COMMITTED' AND token_hash IS NOT NULL AND pending_registry IS NOT NULL + AND active_registry IS NOT NULL AND pending_receipt IS NOT NULL AND committed_at IS NOT NULL) + OR (status IN ('REVOKING','REVOKED') AND token_hash IS NOT NULL AND pending_registry IS NOT NULL + AND active_registry IS NOT NULL + AND ((pending_receipt IS NULL AND committed_at IS NULL) + OR (pending_receipt IS NOT NULL AND committed_at IS NOT NULL)))), + CHECK ((status IN ('FAILED','REVOKING','REVOKED')) = (recovery_failed_at IS NOT NULL)), + CHECK ((status = 'REVOKED') = (revocation_receipt IS NOT NULL)) +); + +CREATE TABLE account_control_ui_response_envelopes ( + operation_id UUID PRIMARY KEY REFERENCES account_control_ui_issuance_operations(operation_id), + encrypted_response BYTEA NOT NULL CHECK (octet_length(encrypted_response) BETWEEN 1 AND 65536), + owner_binding BYTEA NOT NULL CHECK (octet_length(owner_binding) BETWEEN 1 AND 8192), + recovery_expires_at TIMESTAMPTZ NOT NULL +); + +-- [jooq ignore start] +ALTER TABLE account_control_ui_issuance_operations + ADD CONSTRAINT account_control_ui_recovery_expiry_bound CHECK ( + recovery_expires_at > to_timestamp(issued_at_epoch_second) + AND recovery_expires_at <= to_timestamp(issued_at_epoch_second + 60) + AND recovery_expires_at <= to_timestamp(expires_at_epoch_second)); + +CREATE FUNCTION account_control_ui_issuance_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'Control-ui issuance evidence cannot be deleted' USING ERRCODE = '23514'; + END IF; + IF (to_jsonb(NEW) - ARRAY['status','token_hash','pending_registry','active_registry', + 'pending_receipt','committed_at','recovery_failed_at','revocation_receipt']) IS DISTINCT FROM + (to_jsonb(OLD) - ARRAY['status','token_hash','pending_registry','active_registry', + 'pending_receipt','committed_at','recovery_failed_at','revocation_receipt']) + OR NOT ((OLD.status = 'PREPARED' AND NEW.status = 'CANDIDATE') + OR (OLD.status = 'CANDIDATE' AND NEW.status = 'COMMITTED') + OR (OLD.status = 'PREPARED' AND NEW.status = 'FAILED') + OR (OLD.status IN ('CANDIDATE','COMMITTED') AND NEW.status = 'REVOKING') + OR (OLD.status = 'REVOKING' AND NEW.status = 'REVOKED')) + OR (OLD.status <> 'PREPARED' AND + (NEW.token_hash IS DISTINCT FROM OLD.token_hash + OR NEW.pending_registry IS DISTINCT FROM OLD.pending_registry + OR NEW.active_registry IS DISTINCT FROM OLD.active_registry)) + OR (NEW.status IN ('REVOKING','REVOKED') AND + (NEW.pending_receipt IS DISTINCT FROM OLD.pending_receipt + OR NEW.committed_at IS DISTINCT FROM OLD.committed_at)) + OR (OLD.status = 'REVOKING' AND NEW.recovery_failed_at IS DISTINCT FROM OLD.recovery_failed_at) THEN + RAISE EXCEPTION 'Control-ui original operation or candidate cannot change' USING ERRCODE = '23514'; + END IF; + IF NEW.status = 'COMMITTED' AND NOT EXISTS ( + SELECT 1 FROM account_control_ui_response_envelopes e + WHERE e.operation_id = NEW.operation_id AND e.recovery_expires_at = NEW.recovery_expires_at) THEN + RAISE EXCEPTION 'Protected original control-ui response is absent' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_control_ui_issuance_no_truncate() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + RAISE EXCEPTION 'Control-ui issuance evidence cannot be truncated' USING ERRCODE = '23514'; +END; +$$; + +CREATE FUNCTION account_control_ui_response_immutable_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + RAISE EXCEPTION 'Control-ui response evidence is immutable' USING ERRCODE = '23514'; +END; +$$; + +CREATE TRIGGER account_control_ui_issuance_immutable + BEFORE UPDATE OR DELETE ON account_control_ui_issuance_operations + FOR EACH ROW EXECUTE FUNCTION account_control_ui_issuance_guard(); +CREATE TRIGGER account_control_ui_issuance_no_truncate + BEFORE TRUNCATE ON account_control_ui_issuance_operations + FOR EACH STATEMENT EXECUTE FUNCTION account_control_ui_issuance_no_truncate(); +CREATE TRIGGER account_control_ui_response_immutable + BEFORE UPDATE OR DELETE ON account_control_ui_response_envelopes + FOR EACH ROW EXECUTE FUNCTION account_control_ui_response_immutable_guard(); +CREATE TRIGGER account_control_ui_response_no_truncate + BEFORE TRUNCATE ON account_control_ui_response_envelopes + FOR EACH STATEMENT EXECUTE FUNCTION account_control_ui_response_immutable_guard(); +-- [jooq ignore stop] diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountControlUiCommittedIssuanceRepositoryIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountControlUiCommittedIssuanceRepositoryIntegrationTest.java new file mode 100644 index 0000000000..970109378e --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountControlUiCommittedIssuanceRepositoryIntegrationTest.java @@ -0,0 +1,595 @@ +package integration.net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Supplier; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.repository.AccountControlUiCommittedIssuanceRepository; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.exception.DataAccessException; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Physical PostgreSQL proof for the exact, read-only committed-issuance repository. + * + *

The SQL fixture advances only the actual V74 row through its guarded storage states. Its + * opaque payloads establish neither control-ui token authority nor genuine authorization issuance, + * protected-response encryption, or registry activation. + */ +@SuppressWarnings("resource") +class AccountControlUiCommittedIssuanceRepositoryIntegrationTest { + private static final String MIGRATION_LOCATION = "classpath:db/migration"; + private static final AccountPostgresIntegrationFixture postgres = + new AccountPostgresIntegrationFixture(); + private final Set schemas = new HashSet<>(); + + @BeforeAll + static void startPostgres() { + postgres.start(); + } + + @AfterAll + static void stopPostgres() { + postgres.stop(); + } + + @AfterEach + void dropTestOwnedSchemas() { + JdbcTemplate jdbc = new JdbcTemplate(postgres.dataSource()); + for (String schema : schemas) { + if (!schema.matches("account_control_ui_committed_[a-f0-9]{32}")) { + throw new IllegalStateException("Refusing to dispose an unowned PostgreSQL schema"); + } + jdbc.execute("DROP SCHEMA IF EXISTS \"" + schema + "\" CASCADE"); + } + schemas.clear(); + } + + @Test + void readsOnlyExactCommittedEvidenceInsideTheOwnerTransaction() { + Context context = context(); + IssuanceSeed seed = context.insertCandidate(); + + assertThatThrownBy(() -> context.repository.readCommitted(seed.tokenHash())) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Committed Account issuance read requires an Account transaction"); + + assertThatThrownBy(() -> context.commitCandidate(seed)) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("Protected original control-ui response is absent"); + assertThat(context.status(seed.requestId())).isEqualTo("CANDIDATE"); + + context.insertProtectedResponse(seed); + context.commitCandidate(seed); + var evidence = + context.inTransaction( + () -> context.repository.readCommitted(seed.tokenHash()).orElseThrow()); + + assertThat(evidence.requestId()).isEqualTo(seed.requestId()); + assertThat(evidence.operationId()).isEqualTo(seed.operationId()); + assertThat(evidence.tokenJti()).isEqualTo(seed.tokenJti()); + assertThat(evidence.accountId()).isEqualTo(context.owner().accountId()); + assertThat(evidence.tenantId()).isEqualTo(context.owner().tenantId()); + assertThat(evidence.callerWorkload()).isEqualTo(seed.callerWorkload()); + assertThat(evidence.callerContextId()).isEqualTo(seed.callerContextId()); + assertThat(evidence.requestDigest()).isEqualTo(seed.requestDigest()); + assertThat(evidence.claims()).containsExactly(seed.claims()); + assertThat(evidence.source()).containsExactly(seed.source()); + assertThat(evidence.bundle()).containsExactly(seed.bundle()); + assertThat(evidence.signerReceipt()).containsExactly(seed.signerReceipt()); + assertThat(evidence.issuedAtEpochSecond()).isEqualTo(seed.issuedAtEpochSecond()); + assertThat(evidence.expiresAtEpochSecond()).isEqualTo(seed.expiresAtEpochSecond()); + assertThat(evidence.status()).isEqualTo("COMMITTED"); + assertThat(evidence.tokenHash()).isEqualTo(seed.tokenHash()); + assertThat(evidence.pendingRegistry()).containsExactly(seed.pendingRegistry()); + assertThat(evidence.activeRegistry()).containsExactly(seed.activeRegistry()); + assertThat(evidence.pendingReceipt()).containsExactly(seed.pendingReceipt()); + assertThat(evidence.committedAt()).isNotNull(); + assertThat(evidence.recoveryFailedAt()).isNull(); + assertThat( + context.inTransaction( + () -> + context + .transactionDsl + .fetchOne( + "SELECT encrypted_response FROM account_control_ui_response_envelopes " + + "WHERE operation_id = ?", + seed.operationId()) + .get(0, byte[].class))) + .containsExactly(seed.encryptedResponse()); + assertThat( + context.inTransaction( + () -> + context + .transactionDsl + .fetchOne( + "SELECT owner_binding FROM account_control_ui_response_envelopes " + + "WHERE operation_id = ?", + seed.operationId()) + .get(0, byte[].class))) + .containsExactly(seed.ownerBinding()); + + byte[] exposedClaims = evidence.claims(); + exposedClaims[0] ^= 0x7f; + assertThat( + context.inTransaction( + () -> context.repository.readCommitted(seed.tokenHash()).orElseThrow().claims())) + .containsExactly(seed.claims()); + } + + @Test + void missingCandidateAndRevokedIssuancesDoNotReadAsCommitted() { + Context context = context(); + IssuanceSeed candidate = context.insertCandidate(); + IssuanceSeed revoked = context.insertCommitted(); + context.revokeCommitted(revoked); + + assertThat(context.inTransaction(() -> context.repository.readCommitted("f".repeat(64)))) + .isEmpty(); + assertThatThrownBy( + () -> + context.inTransaction( + () -> context.repository.readCommitted(candidate.tokenHash()))) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Exact committed Account control-ui issuance evidence unavailable"); + assertThat(context.status(candidate.requestId())).isEqualTo("CANDIDATE"); + assertThat(context.status(revoked.requestId())).isEqualTo("REVOKED"); + assertThatThrownBy( + () -> + context.inTransaction(() -> context.repository.readCommitted(revoked.tokenHash()))) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Exact committed Account control-ui issuance evidence unavailable"); + } + + @Test + void importedPostgresGuardsRejectRewritingOrDeletingCommittedEvidence() { + Context context = context(); + IssuanceSeed seed = context.insertCommitted(); + + assertThatThrownBy( + () -> + context.inTransaction( + () -> + context.transactionDsl.execute( + "UPDATE account_control_ui_issuance_operations " + + "SET source_payload = ? WHERE request_id = ?", + bytes("test-only-rewritten-source"), + seed.requestId()))) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + context.inTransaction( + () -> + context.transactionDsl.execute( + "DELETE FROM account_control_ui_issuance_operations WHERE request_id = ?", + seed.requestId()))) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + context.inTransaction( + () -> + context.transactionDsl.execute( + "UPDATE account_control_ui_response_envelopes " + + "SET encrypted_response = ? WHERE operation_id = ?", + bytes("test-only-rewritten-envelope"), + seed.operationId()))) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + context.inTransaction( + () -> + context.transactionDsl.execute( + "DELETE FROM account_control_ui_response_envelopes WHERE operation_id = ?", + seed.operationId()))) + .isInstanceOf(DataAccessException.class); + + var retained = + context.inTransaction( + () -> context.repository.readCommitted(seed.tokenHash()).orElseThrow()); + assertThat(retained.source()).containsExactly(seed.source()); + assertThat( + context.inTransaction( + () -> + context + .transactionDsl + .fetchOne( + "SELECT encrypted_response FROM account_control_ui_response_envelopes " + + "WHERE operation_id = ?", + seed.operationId()) + .get(0, byte[].class))) + .containsExactly(seed.encryptedResponse()); + } + + @Test + void committedReadShareLockLinearizesBeforeConcurrentRevocation() throws Exception { + Context context = context(); + IssuanceSeed seed = context.insertCommitted(); + CountDownLatch readerHasLoadedEvidence = new CountDownLatch(1); + CountDownLatch releaseReaderTransaction = new CountDownLatch(1); + CountDownLatch revocationIsAboutToUpdate = new CountDownLatch(1); + AtomicInteger readerPid = new AtomicInteger(); + AtomicInteger revokerPid = new AtomicInteger(); + ExecutorService executor = Executors.newFixedThreadPool(2); + + Future reader = + executor.submit( + () -> + context.inTransaction( + () -> { + var evidence = + context.repository.readCommitted(seed.tokenHash()).orElseThrow(); + readerPid.set( + context + .transactionDsl + .fetchOne("SELECT pg_backend_pid()") + .get(0, Integer.class)); + readerHasLoadedEvidence.countDown(); + await(releaseReaderTransaction, "reader transaction release"); + return evidence; + })); + Future revocation; + try { + assertThat(readerHasLoadedEvidence.await(5, TimeUnit.SECONDS)).isTrue(); + revocation = + executor.submit( + () -> + context.inTransaction( + () -> { + revokerPid.set( + context + .transactionDsl + .fetchOne("SELECT pg_backend_pid()") + .get(0, Integer.class)); + revocationIsAboutToUpdate.countDown(); + context.transactionDsl.execute( + "UPDATE account_control_ui_issuance_operations " + + "SET status = 'REVOKING', recovery_failed_at = clock_timestamp() " + + "WHERE request_id = ? AND status = 'COMMITTED'", + seed.requestId()); + return null; + })); + assertThat(revocationIsAboutToUpdate.await(5, TimeUnit.SECONDS)).isTrue(); + assertThat( + waitUntilBlockedBy( + context, revokerPid.get(), readerPid.get(), TimeUnit.SECONDS.toNanos(5))) + .as("the revocation UPDATE waits on the repository's FOR SHARE row lock") + .isTrue(); + assertThat(revocation.isDone()).isFalse(); + } finally { + releaseReaderTransaction.countDown(); + executor.shutdown(); + if (!executor.awaitTermination(5, TimeUnit.SECONDS)) { + executor.shutdownNow(); + assertThat(executor.awaitTermination(5, TimeUnit.SECONDS)) + .as("reader and revocation transactions terminate after releasing the row lock") + .isTrue(); + } + } + + assertThat(reader.get(5, TimeUnit.SECONDS).status()).isEqualTo("COMMITTED"); + revocation.get(5, TimeUnit.SECONDS); + assertThat(context.status(seed.requestId())).isEqualTo("REVOKING"); + assertThatThrownBy( + () -> context.inTransaction(() -> context.repository.readCommitted(seed.tokenHash()))) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Exact committed Account control-ui issuance evidence unavailable"); + } + + private static boolean waitUntilBlockedBy( + Context context, int waitingPid, int blockingPid, long timeoutNanos) + throws InterruptedException { + long deadline = System.nanoTime() + timeoutNanos; + while (System.nanoTime() < deadline) { + Boolean blocked = + context + .adminDsl + .fetchOne( + "SELECT EXISTS (SELECT 1 FROM pg_stat_activity " + + "WHERE pid = ? AND wait_event_type = 'Lock' " + + "AND ? = ANY(pg_blocking_pids(pid)))", + waitingPid, + blockingPid) + .get(0, Boolean.class); + if (Boolean.TRUE.equals(blocked)) { + return true; + } + Thread.sleep(10L); + } + return false; + } + + private static void await(CountDownLatch latch, String purpose) { + try { + if (!latch.await(5, TimeUnit.SECONDS)) { + throw new IllegalStateException("Timed out waiting for " + purpose); + } + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("Interrupted while waiting for " + purpose, interrupted); + } + } + + private Context context() { + String schema = "account_control_ui_committed_" + UUID.randomUUID().toString().replace("-", ""); + schemas.add(schema); + DriverManagerDataSource dataSource = postgres.dataSource(schema); + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations(MIGRATION_LOCATION) + .load() + .migrate(); + DSLContext transactionDsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + DSLContext adminDsl = DSL.using(dataSource, SQLDialect.POSTGRES); + return new Context(transactionDsl, adminDsl, dataSource); + } + + private static FreshTenantCreationEvidence tenantEvidence(UUID tenantId) { + UUID requestId = UUID.randomUUID(); + UUID operationId = UUID.randomUUID(); + String tenantKey = "committed-issuance-" + requestId.toString().substring(0, 12); + String requestDigest = + GameTenantCreationDigest.requestDigest("prod", requestId, tenantKey, "test tenant", null); + long sourceGameRowId = 7001L; + String provenance = "NEW_GAME_ROW"; + return new FreshTenantCreationEvidence( + 1, + "prod", + requestId, + operationId, + requestDigest, + tenantId, + sourceGameRowId, + tenantKey, + provenance, + GameTenantCreationDigest.evidenceDigest( + "prod", + requestId, + operationId, + requestDigest, + tenantId, + sourceGameRowId, + tenantKey, + provenance)); + } + + private static String tokenHash() { + return UUID.randomUUID().toString().replace("-", "").repeat(2); + } + + private static String digest() { + return UUID.randomUUID().toString().replace("-", "").repeat(2); + } + + private static byte[] bytes(String value) { + return value.getBytes(StandardCharsets.UTF_8); + } + + private record OwnerIdentity(UUID accountId, UUID tenantId) {} + + private record IssuanceSeed( + UUID requestId, + UUID operationId, + UUID tokenJti, + String callerWorkload, + UUID callerContextId, + String requestDigest, + byte[] claims, + byte[] source, + byte[] bundle, + byte[] signerReceipt, + long issuedAtEpochSecond, + long expiresAtEpochSecond, + OffsetDateTime recoveryExpiresAt, + String tokenHash, + byte[] pendingRegistry, + byte[] activeRegistry, + byte[] pendingReceipt, + byte[] encryptedResponse, + byte[] ownerBinding) {} + + private static final class Context { + private final DSLContext transactionDsl; + private final DSLContext adminDsl; + private final TransactionTemplate transaction; + private final AccountControlUiCommittedIssuanceRepository repository; + private final OwnerIdentity owner; + + Context(DSLContext transactionDsl, DSLContext adminDsl, DriverManagerDataSource dataSource) { + this.transactionDsl = transactionDsl; + this.adminDsl = adminDsl; + transaction = new TransactionTemplate(new DataSourceTransactionManager(dataSource)); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + repository = new AccountControlUiCommittedIssuanceRepository(transactionDsl); + owner = + inTransaction( + () -> { + String suffix = UUID.randomUUID().toString(); + Account account = new Account(); + account.setUsername("control-ui-committed-" + suffix); + account.setEmail("control-ui-committed-" + suffix + "@example.test"); + account.setPasswordHash("test-only-account-password-hash"); + Account saved = new AccountRepository(transactionDsl).save(account); + UUID tenantId = UUID.randomUUID(); + new FreshTenantIdentityAssociationRepository(transactionDsl, "prod") + .importVerified(tenantEvidence(tenantId)); + return new OwnerIdentity(saved.getAccountUuid(), tenantId); + }); + } + + OwnerIdentity owner() { + return owner; + } + + T inTransaction(Supplier action) { + return transaction.execute(ignored -> action.get()); + } + + void inTransactionWithoutResult(Runnable action) { + transaction.executeWithoutResult(ignored -> action.run()); + } + + IssuanceSeed insertCandidate() { + IssuanceSeed seed = newSeed(); + inTransactionWithoutResult(() -> insertPrepared(seed)); + inTransactionWithoutResult(() -> advanceToCandidate(seed)); + return seed; + } + + IssuanceSeed insertCommitted() { + IssuanceSeed seed = insertCandidate(); + insertProtectedResponse(seed); + commitCandidate(seed); + return seed; + } + + void insertProtectedResponse(IssuanceSeed seed) { + inTransactionWithoutResult( + () -> + transactionDsl.execute( + "INSERT INTO account_control_ui_response_envelopes " + + "(operation_id, encrypted_response, owner_binding, recovery_expires_at) " + + "VALUES (?, ?, ?, ?)", + seed.operationId(), + seed.encryptedResponse(), + seed.ownerBinding(), + seed.recoveryExpiresAt())); + } + + void commitCandidate(IssuanceSeed seed) { + inTransactionWithoutResult( + () -> + transactionDsl.execute( + "UPDATE account_control_ui_issuance_operations " + + "SET status = 'COMMITTED', pending_receipt = ?, " + + "committed_at = clock_timestamp() " + + "WHERE request_id = ? AND status = 'CANDIDATE'", + seed.pendingReceipt(), + seed.requestId())); + } + + void revokeCommitted(IssuanceSeed seed) { + inTransactionWithoutResult( + () -> + transactionDsl.execute( + "UPDATE account_control_ui_issuance_operations " + + "SET status = 'REVOKING', recovery_failed_at = clock_timestamp() " + + "WHERE request_id = ? AND status = 'COMMITTED'", + seed.requestId())); + inTransactionWithoutResult( + () -> + transactionDsl.execute( + "UPDATE account_control_ui_issuance_operations " + + "SET status = 'REVOKED', revocation_receipt = ? " + + "WHERE request_id = ? AND status = 'REVOKING'", + bytes("test-only-revocation-receipt"), + seed.requestId())); + } + + String status(UUID requestId) { + return inTransaction( + () -> + transactionDsl + .fetchOne( + "SELECT status FROM account_control_ui_issuance_operations WHERE request_id = ?", + requestId) + .get(0, String.class)); + } + + private void insertPrepared(IssuanceSeed seed) { + transactionDsl.execute( + "INSERT INTO account_control_ui_issuance_operations (" + + "request_id, operation_id, token_jti, account_uuid, tenant_uuid, caller_workload, " + + "caller_context_id, request_mac_key_id, request_digest, claims_payload, " + + "source_payload, bundle_payload, signer_receipt, issued_at_epoch_second, " + + "expires_at_epoch_second, recovery_expires_at, status) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'PREPARED')", + seed.requestId(), + seed.operationId(), + seed.tokenJti(), + owner.accountId(), + owner.tenantId(), + seed.callerWorkload(), + seed.callerContextId(), + "test-mac1", + seed.requestDigest(), + seed.claims(), + seed.source(), + seed.bundle(), + seed.signerReceipt(), + seed.issuedAtEpochSecond(), + seed.expiresAtEpochSecond(), + seed.recoveryExpiresAt()); + } + + private void advanceToCandidate(IssuanceSeed seed) { + transactionDsl.execute( + "UPDATE account_control_ui_issuance_operations " + + "SET status = 'CANDIDATE', token_hash = ?, pending_registry = ?, " + + "active_registry = ? WHERE request_id = ? AND status = 'PREPARED'", + seed.tokenHash(), + seed.pendingRegistry(), + seed.activeRegistry(), + seed.requestId()); + } + + private static IssuanceSeed newSeed() { + UUID requestId = UUID.randomUUID(); + long issuedAt = Instant.now().getEpochSecond(); + return new IssuanceSeed( + requestId, + UUID.randomUUID(), + UUID.randomUUID(), + "spiffe://test-only/logging-admin", + UUID.randomUUID(), + digest(), + bytes("test-only-claims-" + requestId), + bytes("test-only-source-" + requestId), + bytes("test-only-authority-bundle-" + requestId), + bytes("test-only-signer-receipt-" + requestId), + issuedAt, + issuedAt + 300, + OffsetDateTime.ofInstant(Instant.ofEpochSecond(issuedAt + 60), ZoneOffset.UTC), + tokenHash(), + bytes("test-only-pending-registry-" + requestId), + bytes("test-only-active-registry-" + requestId), + bytes("test-only-pending-receipt-" + requestId), + bytes("opaque-test-only-encrypted-response-fixture-" + requestId), + bytes("opaque-test-only-owner-binding-" + requestId)); + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountJwtJwksApiTransportTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountJwtJwksApiTransportTest.java new file mode 100644 index 0000000000..23b8988963 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountJwtJwksApiTransportTest.java @@ -0,0 +1,772 @@ +package net.firedevops.firemud.accountservice.config; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.sun.net.httpserver.Headers; +import com.sun.net.httpserver.HttpExchange; +import com.sun.net.httpserver.HttpHandler; +import com.sun.net.httpserver.HttpsConfigurator; +import com.sun.net.httpserver.HttpsServer; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.LinkOption; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; +import java.nio.file.attribute.PosixFilePermission; +import java.nio.file.attribute.PosixFilePermissions; +import java.security.KeyStore; +import java.time.Duration; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import javax.net.ssl.KeyManagerFactory; +import javax.net.ssl.SSLContext; +import net.firedevops.firemud.accountservice.config.AccountJwtJwksApiBinding.ApiCall; +import net.firedevops.firemud.accountservice.config.AccountJwtJwksApiBinding.ApiOperation; +import net.firedevops.firemud.accountservice.config.AccountJwtJwksApiBinding.ApiResponse; +import net.firedevops.firemud.accountservice.config.AccountJwtJwksApiBinding.BindingRejectedException; +import net.firedevops.firemud.accountservice.config.AccountJwtJwksApiBinding.ParsedBinding; +import net.firedevops.firemud.accountservice.config.AccountJwtValidatorInventoryBinding.ProtectedInventory; +import net.firedevops.firemud.accountservice.config.AccountJwtValidatorInventoryBinding.ValidatorExpectation; +import net.firedevops.firemud.accountservice.service.session.AccountJwtJwksConfigMapClient; +import net.firedevops.firemud.accountservice.service.session.AccountJwtJwksConfigMapClient.ConfigMapSnapshot; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +/** Physical loopback HTTPS proof for Account's production pinned-CA JWKS API transport only. */ +class AccountJwtJwksApiTransportTest { + private static final String NAMESPACE = "firemud-prod"; + private static final String API_USERNAME = "system:serviceaccount:firemud-prod:account-service"; + private static final String KUBE_SYSTEM_UID = "11111111-1111-4111-8111-111111111111"; + private static final String NAMESPACE_UID = "22222222-2222-4222-8222-222222222222"; + private static final String CONFIG_MAP_UID = "33333333-3333-4333-8333-333333333333"; + private static final String TEST_BEARER = "test-only-loopback-bearer"; + private static final char[] KEYSTORE_PASSWORD = "firemud-test".toCharArray(); + private static final Duration NORMAL_TIMEOUT = Duration.ofSeconds(3); + private static final Duration STALL_TIMEOUT = Duration.ofMillis(350); + private static final byte[] SELF_REVIEW = + (""" + {"apiVersion":"authentication.k8s.io/v1","kind":"SelfSubjectReview", + "status":{"userInfo":{"username":"%s"}}} + """ + .formatted(API_USERNAME)) + .getBytes(StandardCharsets.UTF_8); + private static final byte[] KUBE_SYSTEM_NAMESPACE = + namespaceJson("kube-system", KUBE_SYSTEM_UID).getBytes(StandardCharsets.UTF_8); + private static final byte[] TARGET_NAMESPACE = + namespaceJson(NAMESPACE, NAMESPACE_UID).getBytes(StandardCharsets.UTF_8); + private static final byte[] CONFIG_MAP = + (""" + {"apiVersion":"v1","kind":"ConfigMap","metadata":{ + "name":"jwt-jwks","namespace":"%s","uid":"%s","resourceVersion":"7"},"data":{}} + """ + .formatted(NAMESPACE, CONFIG_MAP_UID)) + .getBytes(StandardCharsets.UTF_8); + + @TempDir private static Path temporaryDirectory; + + private static TestPki pki; + + private final List servers = new ArrayList<>(); + + @BeforeAll + static void createEphemeralPki() throws Exception { + Path trustedDirectory = Files.createDirectories(temporaryDirectory.resolve("trusted")); + TestAuthority trustedAuthority = createAuthority(trustedDirectory, "account-jwks-test-ca"); + TestServerCertificate trustedServer = + issueServerCertificate( + trustedDirectory, trustedAuthority, "account-jwks-localhost", "localhost"); + + Path untrustedDirectory = Files.createDirectories(temporaryDirectory.resolve("untrusted")); + TestAuthority untrustedAuthority = + createAuthority(untrustedDirectory, "account-jwks-untrusted-ca"); + + TestServerCertificate wrongHostnameServer = + issueServerCertificate( + trustedDirectory, trustedAuthority, "account-jwks-wrong-host", "wrong.example"); + pki = + new TestPki( + Files.readAllBytes(trustedAuthority.certificate()), + Files.readAllBytes(untrustedAuthority.certificate()), + trustedServer, + wrongHostnameServer); + } + + @AfterEach + void stopLocalServers() { + servers.forEach(server -> server.stop(0)); + } + + @Test + void pinnedCaAndHostnameReachTheFixedKubernetesPathsOverRealHttps() throws Exception { + List requests = new CopyOnWriteArrayList<>(); + AtomicInteger authorizationHeaders = new AtomicInteger(); + HttpsServer server = + startServer( + pki.trustedServer(), + exchange -> { + requests.add( + exchange.getRequestMethod() + " " + exchange.getRequestURI().getRawPath()); + if (("Bearer " + TEST_BEARER) + .equals(exchange.getRequestHeaders().getFirst("Authorization"))) { + authorizationHeaders.incrementAndGet(); + } + respondForKubernetesRequest(exchange); + }); + AccountJwtJwksConfigMapClient client = + new AccountJwtJwksConfigMapClient( + transportBinding(server, pki.trustedCa(), NORMAL_TIMEOUT)); + + ConfigMapSnapshot observed = client.observe(); + + assertThat(observed.uid()).isEqualTo(CONFIG_MAP_UID); + assertThat(observed.resourceVersion()).isEqualTo("7"); + assertThat(requests) + .containsExactly( + "POST /apis/authentication.k8s.io/v1/selfsubjectreviews", + "GET /api/v1/namespaces/kube-system", + "GET /api/v1/namespaces/" + NAMESPACE, + "GET /api/v1/namespaces/" + NAMESPACE + "/configmaps/jwt-jwks"); + assertThat(authorizationHeaders).hasValue(4); + } + + @Test + void protectedInventoryOperationsUseOnlyFixedNamespaceGetPathsOverPinnedHttps() throws Exception { + List requests = new CopyOnWriteArrayList<>(); + AtomicInteger authorizationHeaders = new AtomicInteger(); + HttpsServer server = + startServer( + pki.trustedServer(), + exchange -> { + String query = exchange.getRequestURI().getRawQuery(); + requests.add( + exchange.getRequestMethod() + + " " + + exchange.getRequestURI().getRawPath() + + (query == null ? "" : "?" + query)); + if (("Bearer " + TEST_BEARER) + .equals(exchange.getRequestHeaders().getFirst("Authorization"))) { + authorizationHeaders.incrementAndGet(); + } + respond(exchange, 200, "{}".getBytes(StandardCharsets.UTF_8)); + }); + AccountJwtJwksApiBinding client = transportBinding(server, pki.trustedCa(), NORMAL_TIMEOUT); + ProtectedInventory inventory = validatorInventoryForTransport(); + ValidatorExpectation validator = inventory.validators().get(0); + + try (ApiOperation operation = client.beginOperation()) { + ApiResponse deployment = operation.readValidatorDeployment(inventory, validator); + ApiResponse pods = operation.listValidatorPods(inventory, validator, "page/+token="); + ApiResponse replicaSet = + operation.readValidatorReplicaSet(inventory, validator, "player-service-abcde"); + assertThat(deployment.statusCode()).isEqualTo(200); + assertThat(pods.statusCode()).isEqualTo(200); + assertThat(replicaSet.statusCode()).isEqualTo(200); + } + + assertThat(requests) + .containsExactly( + "GET /apis/apps/v1/namespaces/" + NAMESPACE + "/deployments/player-service", + "GET /api/v1/namespaces/" + + NAMESPACE + + "/pods?labelSelector=app%3Dplayer-service%2Cfiremud.io%2Fcomponent%3Djwt-validator" + + "&limit=250&continue=page%2F%2Btoken%3D", + "GET /apis/apps/v1/namespaces/" + NAMESPACE + "/replicasets/player-service-abcde"); + assertThat(authorizationHeaders).hasValue(3); + } + + @Test + void replicaSetReadRejectsCallerSuppliedPathCharacters() throws Exception { + AccountJwtJwksApiBinding client = + transportBinding( + startServer(pki.trustedServer(), exchange -> respond(exchange, 200, new byte[0])), + pki.trustedCa(), + NORMAL_TIMEOUT); + ProtectedInventory inventory = validatorInventoryForTransport(); + ValidatorExpectation validator = inventory.validators().get(0); + + try (ApiOperation operation = client.beginOperation()) { + assertThatThrownBy( + () -> operation.readValidatorReplicaSet(inventory, validator, "../secrets")) + .isInstanceOf(BindingRejectedException.class) + .hasNoCause(); + } + } + + @Test + void serverCertificateFromAnUnpinnedCaIsRejectedByTheProductionTransport() throws Exception { + AtomicInteger handlerCalls = new AtomicInteger(); + HttpsServer server = + startServer( + pki.trustedServer(), + exchange -> { + handlerCalls.incrementAndGet(); + respond(exchange, 200, KUBE_SYSTEM_NAMESPACE); + }); + AccountJwtJwksApiBinding binding = transportBinding(server, pki.untrustedCa(), NORMAL_TIMEOUT); + + assertTransportFailure(binding, ApiCall.READ_KUBE_SYSTEM_NAMESPACE); + + assertThat(handlerCalls).hasValue(0); + } + + @Test + void wrongHostnameIsRejectedEvenWhenTheServingCertificateChainsToThePinnedCa() throws Exception { + AtomicInteger handlerCalls = new AtomicInteger(); + HttpsServer server = + startServer( + pki.wrongHostnameServer(), + exchange -> { + handlerCalls.incrementAndGet(); + respond(exchange, 200, KUBE_SYSTEM_NAMESPACE); + }); + AccountJwtJwksApiBinding binding = transportBinding(server, pki.trustedCa(), NORMAL_TIMEOUT); + + assertTransportFailure(binding, ApiCall.READ_KUBE_SYSTEM_NAMESPACE); + + assertThat(handlerCalls).hasValue(0); + } + + @Test + void redirectIsReturnedButNeverFollowed() throws Exception { + AtomicInteger redirectTargetCalls = new AtomicInteger(); + HttpsServer redirectTarget = + startServer( + pki.trustedServer(), + exchange -> { + redirectTargetCalls.incrementAndGet(); + respond(exchange, 200, KUBE_SYSTEM_NAMESPACE); + }); + List sourceRequests = new CopyOnWriteArrayList<>(); + HttpsServer source = + startServer( + pki.trustedServer(), + exchange -> { + sourceRequests.add(exchange.getRequestURI().getRawPath()); + Headers headers = exchange.getResponseHeaders(); + headers.set( + "Location", + "https://localhost:" + redirectTarget.getAddress().getPort() + "/target"); + respond(exchange, 302, new byte[0]); + }); + AccountJwtJwksApiBinding binding = transportBinding(source, pki.trustedCa(), NORMAL_TIMEOUT); + + ApiResponse response = send(binding, ApiCall.READ_KUBE_SYSTEM_NAMESPACE); + + assertThat(response.statusCode()).isEqualTo(302); + assertThat(sourceRequests).containsExactly("/api/v1/namespaces/kube-system"); + assertThat(redirectTargetCalls).hasValue(0); + } + + @Test + void stalledPostHeaderBodyIsBoundedByTheWholeResponseDeadline() throws Exception { + CountDownLatch bodyStarted = new CountDownLatch(1); + CountDownLatch releaseBody = new CountDownLatch(1); + HttpsServer server = + startServer( + pki.trustedServer(), + exchange -> { + exchange.getResponseHeaders().set("Content-Type", "application/json"); + exchange.sendResponseHeaders(200, 0); + try (OutputStream body = exchange.getResponseBody()) { + body.write('{'); + body.flush(); + bodyStarted.countDown(); + releaseBody.await(3, TimeUnit.SECONDS); + } catch (IOException ignored) { + // The client closes the response stream when its absolute deadline expires. + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + } + }); + AccountJwtJwksApiBinding binding = transportBinding(server, pki.trustedCa(), STALL_TIMEOUT); + long startedAt = System.nanoTime(); + + try { + assertTransportFailure(binding, ApiCall.READ_KUBE_SYSTEM_NAMESPACE); + assertThat(bodyStarted.await(1, TimeUnit.SECONDS)).isTrue(); + assertThat(Duration.ofNanos(System.nanoTime() - startedAt)).isLessThan(Duration.ofSeconds(2)); + } finally { + releaseBody.countDown(); + } + } + + @Test + void oversizedHttpsResponseIsRejectedWithoutAcceptingPartialBytes() throws Exception { + AtomicInteger handlerCalls = new AtomicInteger(); + byte[] oversized = new byte[1024 * 1024 + 1]; + HttpsServer server = + startServer( + pki.trustedServer(), + exchange -> { + handlerCalls.incrementAndGet(); + respond(exchange, 200, oversized); + }); + AccountJwtJwksApiBinding binding = transportBinding(server, pki.trustedCa(), NORMAL_TIMEOUT); + + assertTransportFailure(binding, ApiCall.READ_JWKS_CONFIG_MAP); + + assertThat(handlerCalls).hasValue(1); + } + + @Test + void rootOwnedReadOnlyProjectionAllowsRootWritableParentsAndSafeBearerRenewal() throws Exception { + assumeRootCanCreateRootOwnedFixtures(); + ProtectedFiles fixture = protectedFiles("renewal"); + AccountJwtJwksApiBinding binding = fixture.binding(); + + assertThat(binding.current().namespace()).isEqualTo(NAMESPACE); + ApiOperation inFlight = binding.beginOperation(); + fixture.projectToken("..0002", "renewed-test-bearer", "token"); + + assertThatThrownBy(() -> inFlight.send(ApiCall.READ_KUBE_SYSTEM_NAMESPACE, null)) + .isInstanceOf(AccountJwtJwksApiBinding.BindingRejectedException.class); + inFlight.close(); + assertThat(binding.current().namespace()).isEqualTo(NAMESPACE); + } + + @Test + void credentialModeAndFrozenTrustFileIdentityDriftAreRejected() throws Exception { + assumeRootCanCreateRootOwnedFixtures(); + ProtectedFiles fixture = protectedFiles("drift"); + AccountJwtJwksApiBinding binding = fixture.binding(); + binding.current(); + + Files.setPosixFilePermissions(fixture.currentToken(), Set.of(PosixFilePermission.OWNER_READ)); + assertThatThrownBy(binding::current) + .isInstanceOf(AccountJwtJwksApiBinding.BindingRejectedException.class); + + ProtectedFiles ownerFixture = protectedFiles("owner-drift"); + ownerFixture.binding().current(); + Files.setAttribute(ownerFixture.currentToken(), "unix:uid", 65534L, LinkOption.NOFOLLOW_LINKS); + assertThatThrownBy(ownerFixture.binding()::current) + .isInstanceOf(AccountJwtJwksApiBinding.BindingRejectedException.class); + + ProtectedFiles groupFixture = protectedFiles("group-drift"); + groupFixture.binding().current(); + Object gid = + Files.getAttribute(groupFixture.currentToken(), "unix:gid", LinkOption.NOFOLLOW_LINKS); + Files.setAttribute( + groupFixture.currentToken(), + "unix:gid", + ((Number) gid).longValue() == 0L ? 1L : 0L, + LinkOption.NOFOLLOW_LINKS); + assertThatThrownBy(groupFixture.binding()::current) + .isInstanceOf(AccountJwtJwksApiBinding.BindingRejectedException.class); + + ProtectedFiles trustFixture = protectedFiles("trust-drift"); + trustFixture.binding().current(); + Path replacementCa = trustFixture.caPath().resolveSibling("replacement-serving-ca.pem"); + Files.writeString(replacementCa, "test-only-public-serving-ca", StandardCharsets.UTF_8); + Files.setPosixFilePermissions( + replacementCa, Set.of(PosixFilePermission.OWNER_READ, PosixFilePermission.GROUP_READ)); + Files.move(replacementCa, trustFixture.caPath(), StandardCopyOption.REPLACE_EXISTING); + assertThatThrownBy(trustFixture.binding()::current) + .isInstanceOf(AccountJwtJwksApiBinding.BindingRejectedException.class); + + ProtectedFiles bindingFixture = protectedFiles("binding-drift"); + bindingFixture.binding().current(); + Path replacementBinding = + bindingFixture.bindingPath().resolveSibling("replacement-binding.json"); + Files.write(replacementBinding, Files.readAllBytes(bindingFixture.bindingPath())); + Files.setPosixFilePermissions(replacementBinding, PosixFilePermissions.fromString("r--r-----")); + Files.move( + replacementBinding, bindingFixture.bindingPath(), StandardCopyOption.REPLACE_EXISTING); + assertThatThrownBy(bindingFixture.binding()::current) + .isInstanceOf(AccountJwtJwksApiBinding.BindingRejectedException.class); + } + + @Test + void groupOrOtherWritableProtectedProjectionDirectoryIsRejected() throws Exception { + assumeRootCanCreateRootOwnedFixtures(); + ProtectedFiles fixture = protectedFiles("writable-directory"); + Files.setPosixFilePermissions( + fixture.trustRoot(), + Set.of( + PosixFilePermission.OWNER_READ, + PosixFilePermission.OWNER_WRITE, + PosixFilePermission.OWNER_EXECUTE, + PosixFilePermission.GROUP_READ, + PosixFilePermission.GROUP_WRITE, + PosixFilePermission.GROUP_EXECUTE, + PosixFilePermission.OTHERS_READ, + PosixFilePermission.OTHERS_EXECUTE)); + + assertThatThrownBy(fixture.binding()::current) + .isInstanceOf(AccountJwtJwksApiBinding.BindingRejectedException.class); + } + + private static void assertTransportFailure(AccountJwtJwksApiBinding binding, ApiCall call) { + assertThatThrownBy(() -> send(binding, call)) + .isInstanceOf(AccountJwtJwksApiBinding.ApiTransportException.class) + .hasMessage("Account JWT JWKS Kubernetes API request failed"); + } + + private static ApiResponse send(AccountJwtJwksApiBinding binding, ApiCall call) { + try (ApiOperation operation = binding.beginOperation()) { + return operation.send(call, null); + } + } + + private static void assumeRootCanCreateRootOwnedFixtures() throws Exception { + Object uid = Files.getAttribute(temporaryDirectory, "unix:uid", LinkOption.NOFOLLOW_LINKS); + Assumptions.assumeTrue(uid instanceof Number number && number.longValue() == 0L); + } + + private ProtectedFiles protectedFiles(String label) throws Exception { + Path root = Files.createDirectories(temporaryDirectory.resolve(label)); + Path trustRoot = Files.createDirectory(root.resolve("account-jwt-api")); + Path tokenRoot = Files.createDirectory(root.resolve("account-jwt-api-token")); + Path bindingPath = trustRoot.resolve("binding.json"); + Path caPath = trustRoot.resolve("serving-ca.pem"); + Path tokenPath = tokenRoot.resolve("token"); + byte[] caBytes = "test-only-public-serving-ca".getBytes(StandardCharsets.UTF_8); + Files.write(caPath, caBytes); + Path firstVersion = Files.createDirectory(tokenRoot.resolve("..0001")); + Path firstToken = firstVersion.resolve("token"); + Files.writeString(firstToken, "initial-test-bearer"); + Files.createSymbolicLink(tokenRoot.resolve("..data"), Path.of("..0001")); + Files.createSymbolicLink(tokenPath, Path.of("..data/token")); + applyPermissions(trustRoot, "rwxr-xr-x"); + applyPermissions(tokenRoot, "rwxr-xr-x"); + applyPermissions(firstVersion, "rwxr-xr-x"); + Files.createFile(bindingPath); + applyPermissions(bindingPath, "r--r-----"); + applyPermissions(caPath, "r--r-----"); + applyPermissions(firstToken, "r--r-----"); + writeBinding(bindingPath, caPath, tokenPath, caBytes); + return new ProtectedFiles( + bindingPath, + trustRoot, + caPath, + tokenRoot, + tokenPath, + firstToken, + AccountJwtJwksApiBinding.forProtectedFilesTest( + bindingPath, trustRoot, caPath, tokenRoot, tokenPath)); + } + + private static void writeBinding(Path bindingPath, Path caPath, Path tokenPath, byte[] caBytes) + throws Exception { + Map values = new LinkedHashMap<>(); + values.put("version", "account-jwt-jwks-api-binding/v1"); + values.put("enabled", "true"); + values.put("configRevision", "physical-file-test-1"); + values.put("environmentId", "prod"); + values.put("clusterId", "loopback-cluster"); + values.put("apiServerUrl", "https://localhost:6443"); + values.put("tlsServerName", "localhost"); + values.put("servingCaPath", caPath.toString()); + values.put("servingCaSha256", sha256(caBytes)); + values.put("bearerTokenPath", tokenPath.toString()); + values.put("namespace", NAMESPACE); + values.put("expectedClusterIncarnationUid", KUBE_SYSTEM_UID); + values.put("expectedNamespaceUid", NAMESPACE_UID); + values.put("expectedApiUsername", API_USERNAME); + values.put("bindingDigest", "0".repeat(64)); + tools.jackson.databind.json.JsonMapper mapper = + tools.jackson.databind.json.JsonMapper.builder().build(); + String placeholder = mapper.writeValueAsString(values); + tools.jackson.databind.JsonNode binding = mapper.readTree(placeholder); + values.put("bindingDigest", AccountJwtJwksApiBinding.computeBindingDigest(binding)); + Files.writeString(bindingPath, mapper.writeValueAsString(values), StandardCharsets.UTF_8); + } + + private static void applyPermissions(Path path, String mode) throws IOException { + Files.setPosixFilePermissions(path, PosixFilePermissions.fromString(mode)); + } + + private AccountJwtJwksApiBinding transportBinding( + HttpsServer server, byte[] trustedCa, Duration timeout) throws Exception { + ParsedBinding binding = + new ParsedBinding( + "transport-test-1", + "prod", + "loopback-cluster", + java.net.URI.create("https://localhost:" + server.getAddress().getPort() + "/"), + "localhost", + Path.of("/not-read-by-transport-test/trusted-ca.pem"), + sha256(trustedCa), + Path.of("/not-read-by-transport-test/bearer-token"), + NAMESPACE, + KUBE_SYSTEM_UID, + NAMESPACE_UID, + API_USERNAME, + "f".repeat(64)); + return AccountJwtJwksApiBinding.forTransportTest(binding, trustedCa, TEST_BEARER, timeout); + } + + private static ProtectedInventory validatorInventoryForTransport() throws Exception { + Map validator = new LinkedHashMap<>(); + validator.put("validatorId", "player-service"); + validator.put("deploymentName", "player-service"); + validator.put("deploymentUid", "44444444-4444-4444-8444-444444444444"); + validator.put( + "selector", Map.of("app", "player-service", "firemud.io/component", "jwt-validator")); + validator.put("replicas", 1); + validator.put("containerName", "player-service"); + validator.put("image", "registry.example/firemud/player@sha256:" + "a".repeat(64)); + validator.put("jwksUri", "https://account-api.test/.well-known/jwks.json"); + validator.put("maxCacheAgeSeconds", 60); + validator.put( + "profiles", + List.of( + Map.of( + "tokenProfile", "game-session-account-delegation", + "audience", "account-service"))); + validator.put("receiverServiceUri", "spiffe://firemud/ns/firemud-prod/sa/player-service"); + validator.put("receiverPort", 8443); + validator.put( + "receiverPods", + List.of( + Map.of( + "podUid", "55555555-5555-4555-8555-555555555555", + "podIp", "10.0.0.10", + "leafSpkiSha256", "b".repeat(64)))); + Map root = new LinkedHashMap<>(); + root.put("version", "account-jwt-validator-inventory-binding/v2"); + root.put("enabled", "true"); + root.put("configRevision", "inventory-r1"); + root.put("environmentId", "prod"); + root.put("clusterId", "loopback-cluster"); + root.put("namespace", NAMESPACE); + root.put("expectedClusterIncarnationUid", KUBE_SYSTEM_UID); + root.put("expectedNamespaceUid", NAMESPACE_UID); + root.put("apiBindingRevision", "transport-test-1"); + root.put("apiBindingDigest", "f".repeat(64)); + root.put("validators", List.of(validator)); + root.put("bindingDigest", "0".repeat(64)); + tools.jackson.databind.json.JsonMapper mapper = + tools.jackson.databind.json.JsonMapper.builder().build(); + var unsigned = mapper.readTree(mapper.writeValueAsBytes(root)); + root.put("bindingDigest", AccountJwtValidatorInventoryBinding.computeBindingDigest(unsigned)); + return AccountJwtValidatorInventoryBinding.parseProtectedBytes(mapper.writeValueAsBytes(root)); + } + + private HttpsServer startServer(TestServerCertificate certificate, HttpHandler handler) + throws Exception { + SSLContext sslContext = serverSslContext(certificate.pkcs12()); + InetAddress loopback = InetAddress.getByName("localhost"); + HttpsServer server = HttpsServer.create(new InetSocketAddress(loopback, 0), 0); + server.setHttpsConfigurator(new HttpsConfigurator(sslContext)); + server.createContext("/", handler); + server.start(); + servers.add(server); + return server; + } + + private static SSLContext serverSslContext(Path pkcs12Path) throws Exception { + KeyStore keyStore = KeyStore.getInstance("PKCS12"); + try (InputStream input = Files.newInputStream(pkcs12Path)) { + keyStore.load(input, KEYSTORE_PASSWORD); + } + KeyManagerFactory keyManagers = + KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); + keyManagers.init(keyStore, KEYSTORE_PASSWORD); + SSLContext context = SSLContext.getInstance("TLS"); + context.init(keyManagers.getKeyManagers(), null, null); + return context; + } + + private static void respondForKubernetesRequest(HttpExchange exchange) throws IOException { + String path = exchange.getRequestURI().getRawPath(); + if ("/apis/authentication.k8s.io/v1/selfsubjectreviews".equals(path)) { + exchange.getRequestBody().readAllBytes(); + respond(exchange, 201, SELF_REVIEW); + } else if ("/api/v1/namespaces/kube-system".equals(path)) { + respond(exchange, 200, KUBE_SYSTEM_NAMESPACE); + } else if (("/api/v1/namespaces/" + NAMESPACE).equals(path)) { + respond(exchange, 200, TARGET_NAMESPACE); + } else if (("/api/v1/namespaces/" + NAMESPACE + "/configmaps/jwt-jwks").equals(path)) { + respond(exchange, 200, CONFIG_MAP); + } else { + respond(exchange, 404, new byte[0]); + } + } + + private static void respond(HttpExchange exchange, int statusCode, byte[] body) + throws IOException { + exchange.getResponseHeaders().set("Content-Type", "application/json"); + if (body.length == 0) { + exchange.sendResponseHeaders(statusCode, -1); + exchange.close(); + return; + } + exchange.sendResponseHeaders(statusCode, body.length); + try (OutputStream output = exchange.getResponseBody()) { + output.write(body); + } + } + + private static TestAuthority createAuthority(Path directory, String commonName) throws Exception { + Path key = directory.resolve(commonName + ".key"); + Path certificate = directory.resolve(commonName + ".crt"); + runOpenSsl( + directory, + "req", + "-x509", + "-newkey", + "rsa:2048", + "-nodes", + "-keyout", + key.toString(), + "-out", + certificate.toString(), + "-subj", + "/CN=" + commonName, + "-days", + "2", + "-sha256", + "-addext", + "basicConstraints=critical,CA:TRUE", + "-addext", + "keyUsage=critical,keyCertSign,cRLSign"); + return new TestAuthority(key, certificate); + } + + private static TestServerCertificate issueServerCertificate( + Path directory, TestAuthority authority, String commonName, String dnsName) throws Exception { + Path key = directory.resolve(commonName + ".key"); + Path request = directory.resolve(commonName + ".csr"); + Path certificate = directory.resolve(commonName + ".crt"); + Path extensions = directory.resolve(commonName + ".ext"); + Path pkcs12 = directory.resolve(commonName + ".p12"); + Files.writeString( + extensions, + "basicConstraints=critical,CA:FALSE\n" + + "keyUsage=critical,digitalSignature,keyEncipherment\n" + + "extendedKeyUsage=serverAuth\n" + + "subjectAltName=DNS:" + + dnsName + + "\n"); + runOpenSsl( + directory, + "req", + "-new", + "-newkey", + "rsa:2048", + "-nodes", + "-keyout", + key.toString(), + "-out", + request.toString(), + "-subj", + "/CN=" + commonName); + runOpenSsl( + directory, + "x509", + "-req", + "-in", + request.toString(), + "-CA", + authority.certificate().toString(), + "-CAkey", + authority.privateKey().toString(), + "-CAcreateserial", + "-out", + certificate.toString(), + "-days", + "2", + "-sha256", + "-extfile", + extensions.toString()); + runOpenSsl( + directory, + "pkcs12", + "-export", + "-out", + pkcs12.toString(), + "-inkey", + key.toString(), + "-in", + certificate.toString(), + "-certfile", + authority.certificate().toString(), + "-passout", + "pass:firemud-test"); + return new TestServerCertificate(pkcs12); + } + + private static void runOpenSsl(Path workingDirectory, String... arguments) throws Exception { + List command = new ArrayList<>(); + command.add("openssl"); + command.addAll(List.of(arguments)); + Process process; + try { + process = + new ProcessBuilder(command) + .directory(workingDirectory.toFile()) + .redirectOutput(ProcessBuilder.Redirect.DISCARD) + .redirectError(ProcessBuilder.Redirect.DISCARD) + .start(); + } catch (IOException failure) { + throw new IllegalStateException("OpenSSL is required for this ephemeral HTTPS test", failure); + } + if (!process.waitFor(20, TimeUnit.SECONDS)) { + process.destroyForcibly(); + process.waitFor(2, TimeUnit.SECONDS); + throw new IllegalStateException("Ephemeral HTTPS certificate generation timed out"); + } + if (process.exitValue() != 0) { + throw new IllegalStateException("Ephemeral HTTPS certificate generation failed"); + } + } + + private static String namespaceJson(String name, String uid) { + return """ + {"apiVersion":"v1","kind":"Namespace","metadata":{"name":"%s","uid":"%s"}, + "status":{"phase":"Active"}} + """ + .formatted(name, uid); + } + + private static String sha256(byte[] bytes) throws Exception { + return java.util.HexFormat.of() + .formatHex(java.security.MessageDigest.getInstance("SHA-256").digest(bytes)); + } + + private record ProtectedFiles( + Path bindingPath, + Path trustRoot, + Path caPath, + Path tokenRoot, + Path tokenPath, + Path currentToken, + AccountJwtJwksApiBinding binding) { + void projectToken(String version, String value, String fileName) throws IOException { + Path versionDirectory = Files.createDirectory(tokenRoot.resolve(version)); + Path nextToken = versionDirectory.resolve(fileName); + Files.writeString(nextToken, value, StandardCharsets.UTF_8); + applyPermissions(versionDirectory, "rwxr-xr-x"); + applyPermissions(nextToken, "r--r-----"); + Path dataLink = tokenRoot.resolve("..data"); + Files.delete(dataLink); + Files.createSymbolicLink(dataLink, Path.of(version)); + } + } + + private record TestAuthority(Path privateKey, Path certificate) {} + + private record TestServerCertificate(Path pkcs12) {} + + private record TestPki( + byte[] trustedCa, + byte[] untrustedCa, + TestServerCertificate trustedServer, + TestServerCertificate wrongHostnameServer) {} +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountJwtJwksPublicationRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountJwtJwksPublicationRepositoryTest.java new file mode 100644 index 0000000000..572598164b --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountJwtJwksPublicationRepositoryTest.java @@ -0,0 +1,226 @@ +package net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.repository.AccountJwtJwksPublicationRepository.MountObservation; +import net.firedevops.firemud.accountservice.repository.AccountJwtJwksPublicationRepository.PrepublicationIntent; +import net.firedevops.firemud.accountservice.repository.AccountJwtJwksPublicationRepository.PublicationReceipt; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.ActiveSigner; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.Binding; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.CustodyMode; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.TrustFence; +import org.jooq.DSLContext; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class AccountJwtJwksPublicationRepositoryTest { + private static final Binding BINDING = + new Binding( + "prod", + "prod-cluster-1", + "firemud-prod", + CustodyMode.INTERIM_ACCOUNT_ONLY_MOUNTED_FALLBACK); + private static final TrustFence TRUST = + new TrustFence( + "11111111-1111-4111-8111-111111111111", + "22222222-2222-4222-8222-222222222222", + "a".repeat(64), + "trust-r1"); + private static final UUID OPERATION_ID = UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final String JWKS = "{\"keys\":[]}"; + private static final String MARKER = "{\"phase\":\"PREPUBLISHED\"}"; + + @AfterEach + void clearTransactionState() { + TransactionSynchronizationManager.clear(); + } + + @Test + void currentReadsRemainMandatoryAccountTransactions() throws Exception { + assertMandatory("readCurrentIntent", Binding.class, TrustFence.class); + assertMandatory("readCurrentPublication", Binding.class, TrustFence.class); + assertMandatory( + "recordPrepublicationIntent", + Binding.class, + TrustFence.class, + net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository + .GenerationResult.class, + net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository + .GenerationRequest.class, + String.class, + String.class, + String.class, + String.class, + String.class, + String.class, + String.class); + } + + @Test + void publicationRepositoryRejectsCallsOutsideAnOwningAccountTransaction() { + DSLContext dsl = mock(DSLContext.class); + AccountJwtSignerDesiredStateRepository desired = + mock(AccountJwtSignerDesiredStateRepository.class); + AccountJwtJwksPublicationRepository repository = + new AccountJwtJwksPublicationRepository(dsl, desired); + + assertThatThrownBy(() -> repository.readCurrentIntent(BINDING, TRUST)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("owning Account transaction"); + + verifyNoInteractions(dsl, desired); + } + + @Test + void snapshotAndPublicDataDigestsBindEveryObservedPublicByte() { + String first = + AccountJwtJwksPublicationRepository.snapshotDigest( + Map.of("jwks.json", JWKS, "other.txt", "preserve")); + String sameDifferentOrder = + AccountJwtJwksPublicationRepository.snapshotDigest( + Map.of("other.txt", "preserve", "jwks.json", JWKS)); + String changed = + AccountJwtJwksPublicationRepository.snapshotDigest( + Map.of("jwks.json", JWKS, "other.txt", "changed")); + + assertThat(first).hasSize(64).isEqualTo(sameDifferentOrder).isNotEqualTo(changed); + assertThat(AccountJwtJwksPublicationRepository.publicDataDigest(JWKS, MARKER)) + .isNotEqualTo(AccountJwtJwksPublicationRepository.publicDataDigest(JWKS, MARKER + " ")); + } + + @Test + void immutableEvidenceDigestsBindIntentReceiptAndMountedCorrespondence() { + PrepublicationIntent intent = intent(); + PublicationReceipt receipt = PublicationReceipt.create(intent, "42"); + MountObservation observation = MountObservation.create(intent, receipt); + + assertThat(intent.intentDigest()).isEqualTo(PrepublicationIntent.digest(intent)); + assertThat(receipt.receiptDigest()).isEqualTo(PublicationReceipt.digest(receipt)); + assertThat(observation.observationDigest()).isEqualTo(MountObservation.digest(observation)); + assertThat(observation.publicationReceiptDigest()).isEqualTo(receipt.receiptDigest()); + assertThat(intent.jwksJson()).doesNotContain("privateKey", "\"d\""); + } + + @Test + void immutableEvidenceRejectsChangedDigestAndNonAdvancingRemoteReadback() { + PrepublicationIntent intent = intent(); + + assertThatThrownBy( + () -> + new PrepublicationIntent( + intent.operationId(), + intent.binding(), + intent.operationDigest(), + intent.generationRequestDigest(), + intent.generationReceiptDigest(), + intent.desiredStateVersion(), + intent.trustFence(), + intent.apiBindingDigest(), + intent.apiConfigRevision(), + intent.configMapName(), + intent.configMapUid(), + intent.expectedResourceVersion(), + intent.expectedSnapshotDigest(), + intent.targetGeneration(), + intent.targetKid(), + intent.publicKeyFingerprint(), + intent.expectedDurableActive(), + intent.expectedPublishedActive(), + intent.jwksJson(), + intent.generationMarkerJson(), + intent.publicDataDigest(), + intent.generationMarkerDigest(), + "f".repeat(64))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("intent digest"); + + assertThatThrownBy( + () -> + new PrepublicationIntent( + intent.operationId(), + intent.binding(), + intent.operationDigest(), + intent.generationRequestDigest(), + intent.generationReceiptDigest(), + intent.desiredStateVersion(), + intent.trustFence(), + intent.apiBindingDigest(), + intent.apiConfigRevision(), + intent.configMapName(), + intent.configMapUid(), + intent.expectedResourceVersion(), + intent.expectedSnapshotDigest(), + intent.targetGeneration(), + intent.targetKid(), + intent.publicKeyFingerprint(), + intent.expectedDurableActive(), + intent.expectedPublishedActive(), + intent.jwksJson(), + intent.generationMarkerJson(), + intent.publicDataDigest(), + intent.generationMarkerDigest(), + "0".repeat(64))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("intent digest"); + + assertThatThrownBy(() -> PublicationReceipt.create(intent, intent.expectedResourceVersion())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("resourceVersion did not advance"); + } + + private static PrepublicationIntent intent() { + return PrepublicationIntent.create( + OPERATION_ID, + BINDING, + "b".repeat(64), + "c".repeat(64), + "d".repeat(64), + 2L, + TRUST, + "e".repeat(64), + "api-r1", + "jwt-jwks", + "44444444-4444-4444-8444-444444444444", + "41", + "f".repeat(64), + "1", + "jwt-1-test", + "9".repeat(64), + Optional.empty(), + Optional.empty(), + JWKS, + MARKER, + AccountJwtJwksPublicationRepository.publicDataDigest(JWKS, MARKER), + sha256(MARKER)); + } + + private static String sha256(String value) { + try { + return java.util.HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256").digest(value.getBytes(StandardCharsets.UTF_8))); + } catch (Exception ex) { + throw new IllegalStateException(ex); + } + } + + private static void assertMandatory(String method, Class... parameterTypes) throws Exception { + Transactional transactional = + AccountJwtJwksPublicationRepository.class + .getMethod(method, parameterTypes) + .getAnnotation(Transactional.class); + assertThat(transactional).isNotNull(); + assertThat(transactional.propagation()).isEqualTo(Propagation.MANDATORY); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountJwtReadinessProbeRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountJwtReadinessProbeRepositoryTest.java new file mode 100644 index 0000000000..281daec872 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountJwtReadinessProbeRepositoryTest.java @@ -0,0 +1,133 @@ +package net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; + +import java.time.Instant; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.Binding; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.CustodyMode; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.TrustFence; +import org.jooq.DSLContext; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class AccountJwtReadinessProbeRepositoryTest { + private static final Binding BINDING = + new Binding( + "staging", "cluster-a", "firemud", CustodyMode.INTERIM_ACCOUNT_ONLY_MOUNTED_FALLBACK); + private static final TrustFence TRUST = + new TrustFence( + "11111111-1111-4111-8111-111111111111", + "22222222-2222-4222-8222-222222222222", + "a".repeat(64), + "trust-r1"); + + @Test + void requiresAnOwningAccountTransactionBeforeReadingOtherAuthorities() { + DSLContext dsl = mock(DSLContext.class); + AccountJwtSignerDesiredStateRepository desired = + mock(AccountJwtSignerDesiredStateRepository.class); + AccountJwtJwksPublicationRepository publication = + mock(AccountJwtJwksPublicationRepository.class); + AccountJwtReadinessProbeRepository repository = + new AccountJwtReadinessProbeRepository(dsl, desired, publication); + + assertThatThrownBy(() -> repository.planCurrent(BINDING, TRUST, Instant.ofEpochSecond(10_000))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("owning Account transaction"); + + verifyNoInteractions(dsl, desired, publication); + } + + @Test + void promotionProofReadsRequireWritableOwnerTransactionForLockedEvidence() { + DSLContext dsl = mock(DSLContext.class); + AccountJwtSignerDesiredStateRepository desired = + mock(AccountJwtSignerDesiredStateRepository.class); + AccountJwtJwksPublicationRepository publication = + mock(AccountJwtJwksPublicationRepository.class); + AccountJwtReadinessProbeRepository repository = + new AccountJwtReadinessProbeRepository(dsl, desired, publication); + UUID operationId = UUID.randomUUID(); + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(true); + try { + assertThatThrownBy( + () -> repository.readCurrentPromotionPrerequisites(BINDING, TRUST, operationId)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("A writable Account transaction is required"); + assertThatThrownBy(() -> repository.readPromotionProof(BINDING, TRUST, operationId)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("A writable Account transaction is required"); + } finally { + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + TransactionSynchronizationManager.setActualTransactionActive(false); + } + + verifyNoInteractions(dsl, desired, publication); + } + + @Test + void matrixIsCanonicalExplicitAndStillMarkedIncomplete() { + String matrix = AccountJwtReadinessProbeRepository.applicabilityMatrixJson(); + + assertThat(matrix) + .isEqualTo( + "{\"inventoryStatus\":\"PARTIAL_UNCONFIRMED\",\"schemaVersion\":1," + + "\"validators\":[{\"applicableProfiles\":[{\"audience\":\"control-ui\"," + + "\"tokenProfile\":\"control-ui\"},{\"audience\":\"player-bootstrap\"," + + "\"tokenProfile\":\"player-bootstrap\"},{\"audience\":\"account-service\"," + + "\"tokenProfile\":\"game-session-account-delegation\"}]," + + "\"validatorId\":\"account-service\"}]}"); + assertThat(matrix).doesNotContain("credential-authenticate-account"); + } + + @Test + void firstInstallFenceHasExactAbsentActiveAndPublishedPair() { + AccountJwtReadinessProbeRepository.SignerFence fence = + new AccountJwtReadinessProbeRepository.SignerFence(Optional.empty(), Optional.empty()); + + assertThat(fence.durableActive()).isEmpty(); + assertThat(fence.publishedActive()).isEmpty(); + assertThatThrownBy( + () -> + new AccountJwtReadinessProbeRepository.SignerFence( + Optional.empty(), + Optional.of( + new AccountJwtSignerDesiredStateRepository.ActiveSigner("1", "old-key")))) + .isInstanceOf(AccountJwtReadinessProbeRepository.QuarantinedStateException.class); + } + + @Test + void plannedFirstInstallEntryCarriesAnAbsentPreviousActiveFence() { + var entry = + new AccountJwtReadinessProbeRepository.ProbeEntry( + UUID.randomUUID(), + "a".repeat(64), + "account-service", + "game-session-account-delegation", + "account-service", + net.firedevops.firemud.accountservice.service.session.AccountMountedJwtSignerBundle + .ProbeKind.REPRESENTATIVE, + UUID.randomUUID(), + "1", + "first-key", + Optional.empty(), + 1, + 1, + 20_000, + 20_300, + AccountJwtReadinessProbeRepository.ProbeState.PLANNED, + Optional.empty(), + Optional.empty(), + Optional.empty(), + Optional.empty()); + + assertThat(entry.expectedActive()).isEmpty(); + assertThat(entry.state()).isEqualTo(AccountJwtReadinessProbeRepository.ProbeState.PLANNED); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountJwtSignerDesiredStateRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountJwtSignerDesiredStateRepositoryTest.java new file mode 100644 index 0000000000..cddf5dd5c5 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountJwtSignerDesiredStateRepositoryTest.java @@ -0,0 +1,748 @@ +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.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.security.KeyPairGenerator; +import java.security.MessageDigest; +import java.security.interfaces.RSAPublicKey; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HexFormat; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository.ReadinessPromotionProof; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.Binding; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.CustodyMode; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.EnrollmentIdentity; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.GenerationPhase; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.GenerationRequest; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.GenerationResult; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.PromotionPreparation; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.TrustFence; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.databind.json.JsonMapper; + +class AccountJwtSignerDesiredStateRepositoryTest { + private static final Binding BINDING = + new Binding( + "prod", + "prod-cluster-1", + "firemud-prod", + CustodyMode.INTERIM_ACCOUNT_ONLY_MOUNTED_FALLBACK); + private static final TrustFence TRUST = + new TrustFence( + "11111111-1111-4111-8111-111111111111", + "22222222-2222-4222-8222-222222222222", + "a".repeat(64), + "binding-r1"); + private static final UUID SECRET_UID = UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final EnrollmentIdentity ENROLLMENT = + new EnrollmentIdentity( + TRUST.expectedClusterIncarnationUid(), + TRUST.expectedNamespaceUid(), + TRUST.bindingDigest(), + TRUST.configRevision(), + "b".repeat(64), + "api-r1", + "44444444-4444-4444-8444-444444444444", + "12", + "c".repeat(64)); + + @AfterEach + void clearTransactionState() { + TransactionSynchronizationManager.clear(); + } + + @Test + void durableGenerationEntryPointsRequireAnAccountTransaction() throws Exception { + assertMandatory("initialize", Binding.class, EnrollmentIdentity.class); + assertMandatory("read", Binding.class); + assertMandatory("ensureCurrentGenerationRequest", Binding.class, TrustFence.class); + assertMandatory("readCurrentGenerationRequest", Binding.class, TrustFence.class); + assertMandatory( + "recordSecretObservation", + Binding.class, + TrustFence.class, + UUID.class, + String.class, + String.class, + String.class); + assertMandatory( + "recordGenerationResult", + Binding.class, + TrustFence.class, + UUID.class, + String.class, + String.class, + String.class, + String.class, + String.class); + assertMandatoryWritable("readPreparedGenerationForRecovery", Binding.class, TrustFence.class); + assertMandatoryWritable( + "readAndMarkPreparedPromotionDispatched", Binding.class, TrustFence.class); + assertMandatoryWritable( + "readCurrentCommittedSigner", Binding.class, TrustFence.class, String.class, String.class); + assertMandatoryWritable( + "commitPreparedPromotion", + Binding.class, + TrustFence.class, + UUID.class, + ReadinessPromotionProof.class); + assertMandatoryWritable( + "prepareCurrentGeneration", + Binding.class, + TrustFence.class, + PromotionPreparation.class, + ReadinessPromotionProof.class); + } + + @Test + void promotionCommitRequiresOwnerCreatedReadinessProofBeforeSql() { + DSLContext dsl = mock(DSLContext.class); + AccountJwtSignerDesiredStateRepository repository = + new AccountJwtSignerDesiredStateRepository(dsl); + + assertThatThrownBy( + () -> + inWritableTransaction( + () -> + repository.commitPreparedPromotion( + BINDING, + TRUST, + UUID.fromString("44444444-4444-4444-8444-444444444444"), + null))) + .isInstanceOf(NullPointerException.class) + .hasMessageContaining("readiness proof"); + verifyNoInteractions(dsl); + } + + @Test + void lockedPromotionReadsRejectReadOnlyTransactionsBeforeSql() { + DSLContext dsl = mock(DSLContext.class); + AccountJwtSignerDesiredStateRepository repository = + new AccountJwtSignerDesiredStateRepository(dsl); + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(true); + try { + assertThatThrownBy(() -> repository.readPreparedGenerationForRecovery(BINDING, TRUST)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Writable Account transaction"); + assertThatThrownBy(() -> repository.readAndMarkPreparedPromotionDispatched(BINDING, TRUST)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Writable Account transaction"); + verifyNoInteractions(dsl); + } finally { + TransactionSynchronizationManager.clear(); + } + } + + @Test + void accountCreatesAndReplaysOnlyItsOwnBoundGenerationRequest() { + Conversation conversation = new Conversation(); + + GenerationRequest first = inWritableTransaction(conversation::ensureRequest); + GenerationRequest retry = inWritableTransaction(conversation::ensureRequest); + + assertThat(first).isEqualTo(retry); + assertThat(first.phase()).isEqualTo(GenerationPhase.OBSERVE_PRIVATE_SECRET); + assertThat(first.operationId().version()).isEqualTo(4); + assertThat(first.operationDigest()).hasSize(64); + assertThat(first.desiredStateVersion()).isEqualTo(2); + assertThat(first.targetGeneration()).isEqualTo("1"); + assertThat(first.targetKid()).startsWith("jwt-1-"); + assertThat(first.expectedActive()).isEmpty(); + assertThat(first.expectedPublishedActive()).isEmpty(); + assertThat(first.privateSecretName()).isEqualTo("jwt-signing-keys"); + assertThat(first.expectedSecretResourceVersion()).isEmpty(); + assertThat(first.publicKeyFingerprint()).isEmpty(); + assertThat(first.publicJwkJson()).isEmpty(); + assertThat(conversation.operationInsert).isNotNull(); + assertThat(conversation.executedStatements) + .anyMatch(sql -> sql.contains("account_jwt_signer_generation_operations")) + .anyMatch(sql -> sql.contains("generation_operation_id")) + .noneMatch(sql -> sql.contains("target_public_key_fingerprint")); + verify(conversation.dsl, times(2)).execute(anyString(), any(Object[].class)); + } + + @Test + void generationRequestDefensivelyCopiesItsValidatedPrivateSlots() { + Conversation conversation = new Conversation(); + GenerationRequest source = inWritableTransaction(conversation::ensureRequest); + List suppliedSlots = new ArrayList<>(source.allowedPrivateSlots()); + + GenerationRequest copied = + new GenerationRequest( + source.phase(), + source.operationId(), + source.operationDigest(), + source.generationRequestDigest(), + source.desiredStateVersion(), + source.binding(), + source.trustFence(), + source.privateSecretName(), + source.targetGeneration(), + source.targetKid(), + source.targetAlgorithm(), + source.operationAction(), + suppliedSlots, + source.expectedActive(), + source.expectedPublishedActive(), + source.secretUid(), + source.expectedSecretResourceVersion(), + source.generationReceiptDigest(), + source.publicKeyFingerprint(), + source.publicJwkJson(), + source.observedSecretResourceVersion()); + + suppliedSlots.clear(); + + assertThat(copied.allowedPrivateSlots()).containsExactly("pending"); + assertThatThrownBy(() -> copied.allowedPrivateSlots().add("current")) + .isInstanceOf(UnsupportedOperationException.class); + } + + @Test + void committedActiveSignerNeedsAnExplicitDurableRotationRequest() { + DSLContext dsl = mock(DSLContext.class); + AccountJwtSignerDesiredStateRepository repository = + new AccountJwtSignerDesiredStateRepository(dsl); + Map values = new HashMap<>(); + values.put("environment_id", BINDING.environmentId()); + values.put("cluster_id", BINDING.clusterId()); + values.put("kubernetes_namespace", BINDING.namespace()); + values.put("custody_mode", BINDING.mode().value()); + values.put("private_secret_name", AccountJwtSignerDesiredStateRepository.PRIVATE_SECRET_NAME); + values.put( + "public_jwks_config_map_name", + AccountJwtSignerDesiredStateRepository.PUBLIC_JWKS_CONFIG_MAP_NAME); + values.put("record_version", 8L); + values.put("durable_active_generation", 4L); + values.put("durable_active_kid", "jwt-4-active"); + values.put("published_active_generation", 4L); + values.put("published_active_kid", "jwt-4-active"); + values.put("generation_operation_id", null); + values.put("prepared_operation_id", null); + values.put( + "enrollment_cluster_incarnation_uid", + UUID.fromString(TRUST.expectedClusterIncarnationUid())); + values.put("enrollment_namespace_uid", UUID.fromString(TRUST.expectedNamespaceUid())); + values.put("enrollment_materializer_binding_digest", TRUST.bindingDigest()); + values.put("enrollment_materializer_config_revision", TRUST.configRevision()); + values.put("enrollment_api_binding_digest", "b".repeat(64)); + values.put("enrollment_api_config_revision", "api-r1"); + values.put( + "enrollment_public_config_map_uid", + UUID.fromString("33333333-3333-4333-8333-333333333333")); + values.put("enrollment_public_config_map_resource_version", "12"); + values.put("enrollment_public_config_map_snapshot_digest", "c".repeat(64)); + Record activeState = record(values); + when(dsl.fetchOne(anyString(), any(Object[].class))).thenReturn(activeState); + + assertThatThrownBy( + () -> + inWritableTransaction( + () -> repository.ensureCurrentGenerationRequest(BINDING, TRUST))) + .isInstanceOf( + AccountJwtSignerDesiredStateRepository.MissingGenerationOperationException.class) + .hasMessageContaining("durable rotation request"); + verify(dsl, never()).execute(anyString(), any(Object[].class)); + } + + @Test + void secretObservationUnlocksOnlyTheExactGenerationFenceAndChangedReplayConflicts() { + Conversation conversation = new Conversation(); + GenerationRequest operation = inWritableTransaction(conversation::ensureRequest); + + GenerationRequest pending = + inWritableTransaction( + () -> + conversation.repository.recordSecretObservation( + BINDING, + TRUST, + operation.operationId(), + operation.operationDigest(), + SECRET_UID.toString(), + "12")); + GenerationRequest replay = + inWritableTransaction( + () -> + conversation.repository.recordSecretObservation( + BINDING, + TRUST, + operation.operationId(), + operation.operationDigest(), + SECRET_UID.toString(), + "12")); + + assertThat(pending.phase()).isEqualTo(GenerationPhase.GENERATE_PENDING); + assertThat(pending.generationRequestDigest()).hasSize(64); + assertThat(pending.secretUid()).isEqualTo(SECRET_UID.toString()); + assertThat(pending.expectedSecretResourceVersion()).isEqualTo("12"); + assertThat(pending.publicKeyFingerprint()).isEmpty(); + assertThat(replay).isEqualTo(pending); + int executedBeforeConflict = conversation.executedStatements.size(); + + assertThatThrownBy( + () -> + inWritableTransaction( + () -> + conversation.repository.recordSecretObservation( + BINDING, + TRUST, + operation.operationId(), + operation.operationDigest(), + SECRET_UID.toString(), + "changed-rv"))) + .isInstanceOf(AccountJwtSignerDesiredStateRepository.IdempotencyConflictException.class); + assertThat(conversation.executedStatements).hasSize(executedBeforeConflict); + } + + @Test + void generationReceiptDerivesCanonicalRsaFingerprintAndRemainsNonPromoting() throws Exception { + Conversation conversation = new Conversation(); + GenerationRequest operation = inWritableTransaction(conversation::ensureRequest); + GenerationRequest pending = + inWritableTransaction( + () -> + conversation.repository.recordSecretObservation( + BINDING, + TRUST, + operation.operationId(), + operation.operationDigest(), + SECRET_UID.toString(), + "12")); + PublicJwk jwk = publicJwk(operation.targetKid()); + + GenerationResult result = + inWritableTransaction( + () -> + conversation.repository.recordGenerationResult( + BINDING, + TRUST, + operation.operationId(), + pending.generationRequestDigest(), + SECRET_UID.toString(), + "12", + "13", + jwk.json())); + GenerationResult replay = + inWritableTransaction( + () -> + conversation.repository.recordGenerationResult( + BINDING, + TRUST, + operation.operationId(), + pending.generationRequestDigest(), + SECRET_UID.toString(), + "12", + "13", + jwk.json())); + + assertThat(result).isEqualTo(replay); + assertThat(result.publicKeyFingerprint()).isEqualTo(jwk.fingerprint()); + assertThat(result.expectedPriorResourceVersion()).isEqualTo("12"); + assertThat(result.observedResourceVersion()).isEqualTo("13"); + assertThat(result.publicJwkJson()).doesNotContain("\"d\""); + int executedBeforePromotionAttempt = conversation.executedStatements.size(); + PromotionPreparation callerSuppliedPreparation = + new PromotionPreparation( + result.operationId(), + result, + ENROLLMENT, + "b".repeat(64), + "api-r1", + "44444444-4444-4444-8444-444444444444", + "14", + "d".repeat(64), + "e".repeat(64), + "f".repeat(64), + "1".repeat(64), + "2".repeat(64), + "{\"keys\":[" + result.publicJwkJson() + "]}"); + assertThatThrownBy( + () -> + inWritableTransaction( + () -> + conversation.repository.prepareCurrentGeneration( + BINDING, TRUST, callerSuppliedPreparation, null))) + .isInstanceOf(NullPointerException.class) + .hasMessageContaining("Account-verified readiness proof is required"); + assertThat(conversation.executedStatements).hasSize(executedBeforePromotionAttempt); + } + + @Test + void absentOperationAndWrongCurrentOperationFailBeforeAnyMutation() { + DSLContext emptyDsl = mock(DSLContext.class); + AccountJwtSignerDesiredStateRepository emptyRepository = + new AccountJwtSignerDesiredStateRepository(emptyDsl); + Record emptyState = stateRow(BINDING, 1, null, null, null, null, null); + when(emptyDsl.fetchOne(anyString(), any(Object[].class))).thenReturn(emptyState); + assertThatThrownBy( + () -> + inWritableTransaction( + () -> emptyRepository.readCurrentGenerationRequest(BINDING, TRUST))) + .isInstanceOf( + AccountJwtSignerDesiredStateRepository.MissingGenerationOperationException.class); + verify(emptyDsl, never()).execute(anyString(), any(Object[].class)); + + Conversation conversation = new Conversation(); + GenerationRequest operation = inWritableTransaction(conversation::ensureRequest); + UUID wrongOperation = UUID.fromString("55555555-5555-4555-8555-555555555555"); + int executedBeforeStaleCall = conversation.executedStatements.size(); + assertThatThrownBy( + () -> + inWritableTransaction( + () -> + conversation.repository.recordSecretObservation( + BINDING, + TRUST, + wrongOperation, + operation.operationDigest(), + SECRET_UID.toString(), + "12"))) + .isInstanceOf( + AccountJwtSignerDesiredStateRepository.StaleGenerationOperationException.class); + assertThat(conversation.executedStatements).hasSize(executedBeforeStaleCall); + } + + @Test + void privateOrMalformedPublicJwkIsRejectedBeforeStorageAccess() { + DSLContext dsl = mock(DSLContext.class); + AccountJwtSignerDesiredStateRepository repository = + new AccountJwtSignerDesiredStateRepository(dsl); + + assertThatThrownBy( + () -> + inWritableTransaction( + () -> + repository.recordGenerationResult( + BINDING, + TRUST, + UUID.fromString("22222222-2222-4222-8222-222222222222"), + "a".repeat(64), + SECRET_UID.toString(), + "12", + "13", + "{\"d\":\"private\"}"))) + .isInstanceOf(IllegalArgumentException.class); + verify(dsl, never()).fetchOne(anyString(), any(Object[].class)); + verify(dsl, never()).execute(anyString(), any(Object[].class)); + } + + @Test + void initializationStaysExplicitAndNonAuthorizing() { + DSLContext dsl = mock(DSLContext.class); + AccountJwtSignerDesiredStateRepository repository = + new AccountJwtSignerDesiredStateRepository(dsl); + Record initializedState = stateRow(BINDING, 1, null, null, null, null, null); + when(dsl.execute(anyString(), any(Object[].class))).thenReturn(1); + when(dsl.fetchOne(anyString(), any(Object[].class))).thenReturn(initializedState); + + var state = inWritableTransaction(() -> repository.initialize(BINDING, ENROLLMENT)); + + assertThat(state.recordVersion()).isEqualTo(1); + assertThat(state.durableActive()).isEmpty(); + assertThat(state.publishedActive()).isEmpty(); + assertThat(state.generationOperationId()).isEmpty(); + assertThat(state.preparedOperationId()).isEmpty(); + ArgumentCaptor sql = ArgumentCaptor.forClass(String.class); + ArgumentCaptor bindings = ArgumentCaptor.forClass(Object[].class); + verify(dsl).execute(sql.capture(), bindings.capture()); + assertThat(sql.getValue()) + .contains("generation_operation_id") + .contains("prepared_operation_id"); + Object[] values = bindings.getValue(); + assertThat(values[4]) + .isInstanceOf(UUID.class) + .isEqualTo(UUID.fromString(ENROLLMENT.expectedClusterIncarnationUid())); + assertThat(values[5]) + .isInstanceOf(UUID.class) + .isEqualTo(UUID.fromString(ENROLLMENT.expectedNamespaceUid())); + assertThat(values[10]) + .isInstanceOf(UUID.class) + .isEqualTo(UUID.fromString(ENROLLMENT.publicConfigMapUid())); + } + + private void assertMandatory(String methodName, Class... parameterTypes) + throws ReflectiveOperationException { + Transactional transactional = + AccountJwtSignerDesiredStateRepository.class + .getMethod(methodName, parameterTypes) + .getAnnotation(Transactional.class); + assertThat(transactional).isNotNull(); + assertThat(transactional.propagation()).isEqualTo(Propagation.MANDATORY); + } + + private void assertMandatoryWritable(String methodName, Class... parameterTypes) + throws ReflectiveOperationException { + Transactional transactional = + AccountJwtSignerDesiredStateRepository.class + .getMethod(methodName, parameterTypes) + .getAnnotation(Transactional.class); + assertThat(transactional).isNotNull(); + assertThat(transactional.propagation()).isEqualTo(Propagation.MANDATORY); + assertThat(transactional.readOnly()).isFalse(); + } + + private static Record stateRow( + Binding binding, + long version, + Long durableGeneration, + String durableKid, + Long publishedGeneration, + String publishedKid, + UUID generationOperationId) { + Map values = new HashMap<>(); + values.put("environment_id", binding.environmentId()); + values.put("cluster_id", binding.clusterId()); + values.put("kubernetes_namespace", binding.namespace()); + values.put("custody_mode", binding.mode().value()); + values.put("private_secret_name", AccountJwtSignerDesiredStateRepository.PRIVATE_SECRET_NAME); + values.put( + "public_jwks_config_map_name", + AccountJwtSignerDesiredStateRepository.PUBLIC_JWKS_CONFIG_MAP_NAME); + values.put("record_version", version); + values.put("durable_active_generation", durableGeneration); + values.put("durable_active_kid", durableKid); + values.put("published_active_generation", publishedGeneration); + values.put("published_active_kid", publishedKid); + values.put("generation_operation_id", generationOperationId); + values.put("prepared_operation_id", null); + values.put( + "enrollment_cluster_incarnation_uid", + UUID.fromString(ENROLLMENT.expectedClusterIncarnationUid())); + values.put("enrollment_namespace_uid", UUID.fromString(ENROLLMENT.expectedNamespaceUid())); + values.put( + "enrollment_materializer_binding_digest", ENROLLMENT.materializerTrustBindingDigest()); + values.put( + "enrollment_materializer_config_revision", ENROLLMENT.materializerTrustConfigRevision()); + values.put("enrollment_api_binding_digest", ENROLLMENT.apiBindingDigest()); + values.put("enrollment_api_config_revision", ENROLLMENT.apiConfigRevision()); + values.put( + "enrollment_public_config_map_uid", UUID.fromString(ENROLLMENT.publicConfigMapUid())); + values.put( + "enrollment_public_config_map_resource_version", + ENROLLMENT.publicConfigMapResourceVersion()); + values.put( + "enrollment_public_config_map_snapshot_digest", ENROLLMENT.publicConfigMapSnapshotDigest()); + return record(values); + } + + private static Record generationOperationRow(Object[] parameters) { + Map values = new HashMap<>(); + values.put("operation_id", parameters[0]); + values.put("environment_id", parameters[1]); + values.put("cluster_id", parameters[2]); + values.put("kubernetes_namespace", parameters[3]); + values.put("custody_mode", parameters[4]); + values.put("operation_digest_version", 1); + values.put("operation_digest", parameters[5]); + values.put("expected_record_version", parameters[6]); + values.put("expected_previous_generation", parameters[7]); + values.put("expected_previous_kid", parameters[8]); + values.put("expected_published_generation", parameters[9]); + values.put("expected_published_kid", parameters[10]); + values.put("target_generation", parameters[11]); + values.put("target_kid", parameters[12]); + values.put("target_algorithm", parameters[13]); + values.put("expected_cluster_incarnation_uid", parameters[14]); + values.put("expected_namespace_uid", parameters[15]); + values.put("trust_binding_digest", parameters[16]); + values.put("trust_config_revision", parameters[17]); + values.put("operation_action", "MATERIALIZE_PENDING"); + values.put("allowed_private_slots_canonical_bytes", parameters[18]); + return record(values); + } + + private static Record secretObservationRow(Object[] parameters) { + Map values = new HashMap<>(); + values.put("operation_id", parameters[0]); + values.put("environment_id", parameters[1]); + values.put("cluster_id", parameters[2]); + values.put("kubernetes_namespace", parameters[3]); + values.put("custody_mode", parameters[4]); + values.put("operation_digest", parameters[5]); + values.put("expected_record_version", parameters[6]); + values.put("expected_cluster_incarnation_uid", parameters[7]); + values.put("expected_namespace_uid", parameters[8]); + values.put("trust_binding_digest", parameters[9]); + values.put("trust_config_revision", parameters[10]); + values.put("private_secret_name", AccountJwtSignerDesiredStateRepository.PRIVATE_SECRET_NAME); + values.put("secret_uid", parameters[11]); + values.put("observed_resource_version", parameters[12]); + values.put("observation_digest", parameters[13]); + values.put("generation_request_digest", parameters[14]); + return record(values); + } + + private static Record generationResultRow(Object[] parameters) { + Map values = new HashMap<>(); + values.put("operation_id", parameters[0]); + values.put("environment_id", parameters[1]); + values.put("cluster_id", parameters[2]); + values.put("kubernetes_namespace", parameters[3]); + values.put("custody_mode", parameters[4]); + values.put("operation_digest", parameters[5]); + values.put("generation_request_digest", parameters[6]); + values.put("desired_state_version", parameters[7]); + values.put("expected_cluster_incarnation_uid", parameters[8]); + values.put("expected_namespace_uid", parameters[9]); + values.put("trust_binding_digest", parameters[10]); + values.put("trust_config_revision", parameters[11]); + values.put("private_secret_name", AccountJwtSignerDesiredStateRepository.PRIVATE_SECRET_NAME); + values.put("secret_uid", parameters[12]); + values.put("expected_prior_resource_version", parameters[13]); + values.put("observed_resource_version", parameters[14]); + values.put("target_generation", parameters[15]); + values.put("target_kid", parameters[16]); + values.put("target_algorithm", "RS256"); + values.put("public_key_fingerprint", parameters[17]); + values.put("public_jwk_json", parameters[18]); + values.put("receipt_digest", parameters[19]); + return record(values); + } + + private static PublicJwk publicJwk(String kid) throws Exception { + KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); + generator.initialize(3072); + RSAPublicKey key = (RSAPublicKey) generator.generateKeyPair().getPublic(); + String modulus = encodeUnsigned(key.getModulus()); + String exponent = encodeUnsigned(key.getPublicExponent()); + Map jwk = new java.util.TreeMap<>(); + jwk.put("alg", "RS256"); + jwk.put("e", exponent); + jwk.put("key_ops", List.of("verify")); + jwk.put("kid", kid); + jwk.put("kty", "RSA"); + jwk.put("n", modulus); + jwk.put("use", "sig"); + String json = + new String( + Rfc8785CanonicalJson.canonicalizeUtf8( + JsonMapper.builder().build().writeValueAsString(jwk)), + StandardCharsets.UTF_8); + String fingerprint = + HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256") + .digest( + Rfc8785CanonicalJson.canonicalizeUtf8( + JsonMapper.builder() + .build() + .writeValueAsString( + Map.of("e", exponent, "kty", "RSA", "n", modulus))))); + return new PublicJwk(json, fingerprint); + } + + private static String encodeUnsigned(BigInteger value) { + byte[] bytes = value.toByteArray(); + int offset = bytes.length > 1 && bytes[0] == 0 ? 1 : 0; + return java.util.Base64.getUrlEncoder() + .withoutPadding() + .encodeToString(java.util.Arrays.copyOfRange(bytes, offset, bytes.length)); + } + + @SuppressWarnings({"rawtypes", "unchecked"}) + private static Record record(Map values) { + Record row = mock(Record.class); + when(row.get(anyString(), any(Class.class))) + .thenAnswer(invocation -> values.get(invocation.getArgument(0))); + return row; + } + + private static T inWritableTransaction(java.util.function.Supplier operation) { + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + try { + return operation.get(); + } finally { + TransactionSynchronizationManager.clear(); + } + } + + private record PublicJwk(String json, String fingerprint) {} + + private final class Conversation { + private final DSLContext dsl = mock(DSLContext.class); + private final AccountJwtSignerDesiredStateRepository repository = + new AccountJwtSignerDesiredStateRepository(dsl); + private final List executedStatements = new java.util.ArrayList<>(); + private Object[] operationInsert; + private Object[] observationInsert; + private Object[] resultInsert; + private int stateReadCount; + + private Conversation() { + when(dsl.execute(anyString(), any(Object[].class))) + .thenAnswer( + invocation -> { + String sql = invocation.getArgument(0); + Object[] arguments = invocation.getArguments(); + Object[] parameters = + arguments.length == 2 && arguments[1] instanceof Object[] bindings + ? bindings + : java.util.Arrays.copyOfRange(arguments, 1, arguments.length); + executedStatements.add(sql); + if (sql.contains("account_jwt_signer_generation_operations")) { + operationInsert = parameters.clone(); + } else if (sql.contains("account_jwt_signer_secret_observations")) { + observationInsert = parameters.clone(); + } else if (sql.contains("account_jwt_signer_generation_results")) { + resultInsert = parameters.clone(); + } + return 1; + }); + when(dsl.fetchOne(anyString(), any(Object[].class))) + .thenAnswer( + invocation -> { + String sql = invocation.getArgument(0); + if (sql.contains("account_jwt_signer_desired_states")) { + return stateReadCount++ == 0 + ? stateRow(BINDING, 1, null, null, null, null, null) + : stateRow( + BINDING, + 2, + null, + null, + null, + null, + operationInsert == null ? null : (UUID) operationInsert[0]); + } + if (sql.contains("account_jwt_signer_generation_operations")) { + return operationInsert == null ? null : generationOperationRow(operationInsert); + } + if (sql.contains("account_jwt_signer_generation_results")) { + return resultInsert == null ? null : generationResultRow(resultInsert); + } + if (sql.contains("account_jwt_signer_secret_observations")) { + return observationInsert == null ? null : secretObservationRow(observationInsert); + } + return null; + }); + } + + private GenerationRequest ensureRequest() { + return repository.ensureCurrentGenerationRequest(BINDING, TRUST); + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiCurrentActorVerifierTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiCurrentActorVerifierTest.java new file mode 100644 index 0000000000..a2729f4554 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiCurrentActorVerifierTest.java @@ -0,0 +1,890 @@ +package unit.net.firedevops.firemud.accountservice.service.session; + +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.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import io.lettuce.core.ClientOptions; +import io.lettuce.core.api.StatefulRedisConnection; +import io.lettuce.core.api.sync.RedisCommands; +import java.net.URI; +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.security.interfaces.RSAPublicKey; +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneId; +import java.util.Base64; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.config.AccountJwtJwksApiBinding; +import net.firedevops.firemud.accountservice.config.AccountJwtJwksApiBinding.ParsedBinding; +import net.firedevops.firemud.accountservice.config.AccountJwtSignerMaterializerTrustBinding; +import net.firedevops.firemud.accountservice.config.AccountJwtSignerMaterializerTrustBinding.Binding; +import net.firedevops.firemud.accountservice.dto.TenantAuthorityEventV1Codec; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; +import net.firedevops.firemud.accountservice.entity.AccountTenantMembership; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.CompositeSnapshot; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.IssuanceFence; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeState; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository.CurrentSourceEvidence; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository.IssuerAccountSourceSnapshot; +import net.firedevops.firemud.accountservice.repository.AccountControlUiCommittedIssuanceRepository; +import net.firedevops.firemud.accountservice.repository.AccountControlUiCommittedIssuanceRepository.CommittedIssuance; +import net.firedevops.firemud.accountservice.repository.AccountJwtJwksPublicationRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.ActiveJwksPromotionReceipt; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.CustodyMode; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.GenerationResult; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.OriginalCommittedSignerEvidence; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.PrivatePromotionReceipt; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.PromotionOperationEvidence; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.TrustFence; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.PairAuthority; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.TenantProvenanceKind; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.VerifiedTenantProvenance; +import net.firedevops.firemud.accountservice.repository.AccountTenantAuthorityEventRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository.RoleSnapshot; +import net.firedevops.firemud.accountservice.service.session.AccountControlUiCurrentActorVerifier; +import net.firedevops.firemud.accountservice.service.session.AccountControlUiRegistryReader; +import net.firedevops.firemud.accountservice.service.session.AccountJwtJwksTrustedSource; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.MembershipEvent; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.security.AccountAsymmetricJwtVerifier; +import net.firedevops.firemud.common.security.AccountPublicJwksCache.PublicJwksSnapshot; +import net.firedevops.firemud.common.security.AccountPublicJwksCache.SourceIdentity; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.SimpleTransactionStatus; +import tools.jackson.databind.json.JsonMapper; + +/** + * Full verifier unit proof. Owner repositories and protected signer/JWKS bindings are mocked at + * their public seams; this does not claim physical PostgreSQL, Redis, or Kubernetes integration + * authority. + */ +class AccountControlUiCurrentActorVerifierTest { + private static final JsonMapper JSON = JsonMapper.builder().build(); + private static final String ISSUER = "firemud-account-service"; + private static final String KID = "control-ui-key"; + private static final String ENVIRONMENT = "test"; + private static final String CLUSTER = "cluster-test"; + private static final String NAMESPACE = "firemud-test"; + private static final String CLUSTER_UID = "11111111-1111-4111-8111-111111111111"; + private static final String NAMESPACE_UID = "22222222-2222-4222-8222-222222222222"; + private static final String CONFIG_MAP_UID = "33333333-3333-4333-8333-333333333333"; + private static final UUID ACCOUNT_ID = UUID.fromString("10000000-0000-4000-8000-000000000001"); + private static final UUID OTHER_ACCOUNT_ID = + UUID.fromString("10000000-0000-4000-8000-000000000009"); + private static final UUID TENANT_ID = UUID.fromString("20000000-0000-4000-8000-000000000002"); + private static final UUID OTHER_TENANT_ID = + UUID.fromString("20000000-0000-4000-8000-000000000009"); + private static final UUID TOKEN_ID = UUID.fromString("30000000-0000-4000-8000-000000000003"); + private static final UUID OPERATION_ID = UUID.fromString("40000000-0000-4000-8000-000000000004"); + private static final UUID REQUEST_ID = UUID.fromString("50000000-0000-4000-8000-000000000005"); + private static final UUID CALLER_CONTEXT_ID = + UUID.fromString("60000000-0000-4000-8000-000000000006"); + private static final UUID PROMOTION_OPERATION_ID = + UUID.fromString("70000000-0000-4000-8000-000000000007"); + private static final UUID GENERATION_OPERATION_ID = + UUID.fromString("80000000-0000-4000-8000-000000000008"); + private static final UUID MEMBERSHIP_EVENT_ID = + UUID.fromString("90000000-0000-4000-8000-000000000009"); + private static final String REQUEST_DIGEST = "a".repeat(64); + private static final String PROMOTION_REQUEST_DIGEST = "b".repeat(64); + private static final String PRIVATE_RECEIPT_DIGEST = "c".repeat(64); + private static final String PUBLIC_RECEIPT_DIGEST = "d".repeat(64); + private static final String API_BINDING_DIGEST = "e".repeat(64); + private static final String API_CA_DIGEST = "f".repeat(64); + private static final Instant NOW = Instant.parse("2035-04-05T06:07:08Z"); + private static final long NOW_SECONDS = NOW.getEpochSecond(); + private static final long EXPIRY_SECONDS = NOW_SECONDS + 300L; + private static KeyPair signingKey; + + @BeforeAll + static void generateSigningKey() throws Exception { + KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); + generator.initialize(3072); + signingKey = generator.generateKeyPair(); + } + + @Test + void verifiesARealSignedTokenAgainstExactCommittedRegistrySignerAndCurrentTenantEvidence() + throws Exception { + Fixture fixture = new Fixture(ACCOUNT_ID, null, 1, 1, List.of("tenantAdmin"), 1, false); + + AccountControlUiCurrentActorVerifier.CurrentActor actor = + fixture.verifier.verify(fixture.compactJwt, TENANT_ID); + + assertThat(actor.accountId()).isEqualTo(ACCOUNT_ID); + assertThat(actor.tenantId()).isEqualTo(TENANT_ID); + assertThat(actor.issuanceOperationId()).isEqualTo(OPERATION_ID); + assertThat(actor.tokenHash()).isEqualTo(fixture.tokenHash); + assertThat(actor.currentTenantRoles()).containsExactly("tenantAdmin"); + assertThat(actor.issuerGeneration()).isEqualTo(1L); + assertThat(actor.accountGeneration()).isEqualTo(1L); + assertThat(actor.tenantGeneration()).isEqualTo(1L); + assertThat(actor.membershipGeneration()).isEqualTo(1L); + assertThat(actor.membershipVersion()).isEqualTo(1L); + assertThat(actor.issuanceFence()).isEqualTo(1L); + verify(fixture.signerStates) + .readOriginalCommittedSigner( + eq(fixture.signerBinding), + eq(fixture.trustFence), + eq(API_BINDING_DIGEST), + eq("api-r1"), + eq(PROMOTION_OPERATION_ID), + eq(GENERATION_OPERATION_ID)); + } + + @Test + void rejectsAChangedActorEvenWhenThePresentedCompactTokenIsValidlySigned() throws Exception { + Fixture fixture = new Fixture(OTHER_ACCOUNT_ID, null, 1, 1, List.of("tenantAdmin"), 1, false); + + assertDenied(() -> fixture.verifier.verify(fixture.compactJwt, TENANT_ID)); + + verify(fixture.issuances).readCommitted(fixture.tokenHash); + verify(fixture.membershipPairs, never()).readPositive(OTHER_ACCOUNT_ID, TENANT_ID); + } + + @Test + void rejectsASelectedTenantOutsideTheExactSignedTenantScope() throws Exception { + Fixture fixture = new Fixture(ACCOUNT_ID, null, 1, 1, List.of("tenantAdmin"), 1, false); + + assertDenied(() -> fixture.verifier.verify(fixture.compactJwt, OTHER_TENANT_ID)); + + verify(fixture.issuances, never()).readCommitted(any()); + } + + @Test + void rejectsStaleTenantGenerationEvenWhenTheCurrentTenantEventAgreesWithTheOwnerSnapshot() + throws Exception { + Fixture fixture = new Fixture(ACCOUNT_ID, null, 2, 1, List.of("tenantAdmin"), 1, false); + + assertDenied(() -> fixture.verifier.verify(fixture.compactJwt, TENANT_ID)); + } + + @Test + void rejectsStaleMembershipGenerationAgainstTheCurrentPositivePairAndEvent() throws Exception { + Fixture fixture = new Fixture(ACCOUNT_ID, null, 1, 2, List.of("tenantAdmin"), 1, false); + + assertDenied(() -> fixture.verifier.verify(fixture.compactJwt, TENANT_ID)); + } + + @Test + void rejectsRoleSnapshotThatDiffersFromTheCurrentMembershipEvent() throws Exception { + Fixture fixture = new Fixture(ACCOUNT_ID, null, 1, 1, List.of("moderator"), 1, false); + + assertDenied(() -> fixture.verifier.verify(fixture.compactJwt, TENANT_ID)); + } + + @Test + void rejectsARevokedIssuanceWhenNoCommittedIssuanceCanBeRead() throws Exception { + Fixture fixture = new Fixture(ACCOUNT_ID, null, 1, 1, List.of("tenantAdmin"), 1, false); + when(fixture.issuances.readCommitted(fixture.tokenHash)).thenReturn(Optional.empty()); + + assertDenied(() -> fixture.verifier.verify(fixture.compactJwt, TENANT_ID)); + + verify(fixture.sourceEvidence, never()).readCurrentIssuerAccountSources(ISSUER, ACCOUNT_ID); + } + + @Test + void rejectsACommitRecordWithAnInvalidCoordinationReadbackReceipt() throws Exception { + Fixture fixture = new Fixture(ACCOUNT_ID, null, 1, 1, List.of("tenantAdmin"), 0, false); + + assertDenied(() -> fixture.verifier.verify(fixture.compactJwt, TENANT_ID)); + } + + @Test + void rejectsACommittedSignerReceiptThatDoesNotMatchProtectedOriginalReadback() throws Exception { + Fixture fixture = new Fixture(ACCOUNT_ID, null, 1, 1, List.of("tenantAdmin"), 1, true); + + assertDenied(() -> fixture.verifier.verify(fixture.compactJwt, TENANT_ID)); + } + + @Test + void rejectsGlobalRoleClaimsInsteadOfTreatingThemAsTenantOperatorAuthority() throws Exception { + Fixture fixture = + new Fixture(ACCOUNT_ID, List.of("platformAdmin"), 1, 1, List.of("tenantAdmin"), 1, false); + + assertThatThrownBy(() -> fixture.verifier.verify(fixture.compactJwt, TENANT_ID)) + .isInstanceOf(AccountAsymmetricJwtVerifier.VerificationException.class); + + verify(fixture.issuances, never()).readCommitted(any()); + } + + private static void assertDenied(Runnable action) { + assertThatThrownBy(action::run).isInstanceOf(IllegalStateException.class); + } + + private static final class Fixture { + private final UUID issuanceAccountId = ACCOUNT_ID; + private final String compactJwt; + private final String tokenHash; + private final AccountJwtSignerDesiredStateRepository.Binding signerBinding; + private final TrustFence trustFence; + private final AccountControlUiCurrentActorVerifier verifier; + private final AccountControlUiCommittedIssuanceRepository issuances = + mock(AccountControlUiCommittedIssuanceRepository.class); + private final AccountAuthoritySourceEvidenceRepository sourceEvidence = + mock(AccountAuthoritySourceEvidenceRepository.class); + private final AccountAuthorityGenerationRepository generations = + mock(AccountAuthorityGenerationRepository.class); + private final AccountTenantAuthorityEventRepository tenantEvents = + mock(AccountTenantAuthorityEventRepository.class); + private final AccountTenantMembershipRepository memberships = + mock(AccountTenantMembershipRepository.class); + private final AccountMembershipPairAuthorityRepository membershipPairs = + mock(AccountMembershipPairAuthorityRepository.class); + private final AccountTenantMembershipRoleSnapshotRepository roleSnapshots = + mock(AccountTenantMembershipRoleSnapshotRepository.class); + private final AccountAuthorityOutboxRepository outbox = + mock(AccountAuthorityOutboxRepository.class); + private final AccountJwtSignerDesiredStateRepository signerStates = + mock(AccountJwtSignerDesiredStateRepository.class); + + private Fixture( + UUID tokenAccountId, + List globalRoles, + long currentTenantGeneration, + long currentMembershipGeneration, + List roleSnapshot, + int localAofCount, + boolean mismatchPublicReceipt) + throws Exception { + Map claims = claims(tokenAccountId, globalRoles); + compactJwt = sign(claims, signingKey); + tokenHash = sha256(compactJwt.getBytes(StandardCharsets.US_ASCII)); + + String jwksJson = jwks((RSAPublicKey) signingKey.getPublic()); + byte[] jwksBytes = jwksJson.getBytes(StandardCharsets.UTF_8); + SourceIdentity sourceIdentity = sourceIdentity(); + PublicJwksSnapshot jwksSnapshot = new PublicJwksSnapshot(sourceIdentity, jwksBytes); + AccountJwtJwksTrustedSource publicJwks = mock(AccountJwtJwksTrustedSource.class); + when(publicJwks.sourceIdentity()).thenReturn(sourceIdentity); + when(publicJwks.load()).thenReturn(jwksSnapshot); + + String trustBindingDigest = + AccountJwtSignerMaterializerTrustBinding.computeBindingDigest( + "trust-r1", + ENVIRONMENT, + CLUSTER, + NAMESPACE, + CLUSTER_UID, + NAMESPACE_UID, + "spiffe://firemud/ns/" + NAMESPACE + "/sa/account-jwt-materializer", + List.of("1".repeat(64))); + Binding materializerBinding = + new Binding( + ENVIRONMENT, + CLUSTER, + NAMESPACE, + CLUSTER_UID, + NAMESPACE_UID, + "spiffe://firemud/ns/" + NAMESPACE + "/sa/account-jwt-materializer", + List.of("1".repeat(64)), + "trust-r1", + trustBindingDigest); + when(materializerTrust.current()).thenReturn(Optional.of(materializerBinding)); + + ParsedBinding apiParsedBinding = + new ParsedBinding( + "api-r1", + ENVIRONMENT, + CLUSTER, + URI.create("https://kubernetes.test:6443"), + "kubernetes.test", + Path.of("/test/serving-ca.pem"), + API_CA_DIGEST, + Path.of("/test/token"), + NAMESPACE, + CLUSTER_UID, + NAMESPACE_UID, + "system:serviceaccount:" + NAMESPACE + ":account-service", + API_BINDING_DIGEST); + when(apiBinding.current()).thenReturn(apiParsedBinding); + + AccountJwtSignerDesiredStateRepository.CustodyMode custodyMode = + CustodyMode.INTERIM_ACCOUNT_ONLY_MOUNTED_FALLBACK; + signerBinding = + new AccountJwtSignerDesiredStateRepository.Binding( + ENVIRONMENT, CLUSTER, NAMESPACE, custodyMode); + trustFence = new TrustFence(CLUSTER_UID, NAMESPACE_UID, trustBindingDigest, "trust-r1"); + + byte[] sourceBytes = + canonicalBytes( + Map.of( + "schemaVersion", 1, + "issuer", ISSUER, + "accountId", issuanceAccountId.toString(), + "tenantId", TENANT_ID.toString(), + "sources", List.of())); + String sourceHash = sha256(sourceBytes); + Map bundleRef = + Map.of( + "bundleVersion", "1", + "sourceVersion", "1", + "sourceFence", "1", + "linearization", "1"); + Map operation = + Map.of( + "operationId", OPERATION_ID.toString(), + "requestId", REQUEST_ID.toString(), + "requestDigest", REQUEST_DIGEST, + "callerWorkload", "logging-admin-service", + "callerContextId", CALLER_CONTEXT_ID.toString(), + "accountId", issuanceAccountId.toString()); + Map sourceVersions = sourceVersions(); + Map roleEvidence = + Map.of("scopedRoles", claims.get("scopedRoles"), "freshnessSource", sourceHash); + Map bundle = + new LinkedHashMap<>( + Map.ofEntries( + Map.entry("schema", "account-auth-evidence-bundle/v1"), + Map.entry("bundleRef", bundleRef), + Map.entry("snapshotIdentity", sourceHash), + Map.entry("issuer", ISSUER), + Map.entry("profile", "control-ui"), + Map.entry("audience", "control-ui"), + Map.entry( + "scope", + Map.of( + "kind", "TENANT", + "accountId", issuanceAccountId.toString(), + "tenantIds", List.of(TENANT_ID.toString()))), + Map.entry("operation", operation), + Map.entry("tokenIdentity", tokenIdentity(claims)), + Map.entry("authorityTuple", claims.get("authorityTuple")), + Map.entry("membershipVersion", claims.get("membershipVersion")), + Map.entry("issuanceFence", claims.get("issuanceFence")), + Map.entry("authoritySourceVersions", sourceVersions), + Map.entry( + "accountIdentitySource", + Map.of( + "accountId", + issuanceAccountId.toString(), + "source", + "account_repository_insert", + "sourceVersion", + 1)), + Map.entry( + "outboxCheckpoints", + Map.of( + "issuer", 0, + "account", 0, + "tenant", 0, + "membership", 1)), + Map.entry("roleEvidence", roleEvidence))); + Map evaluation = + Map.of( + "operation", operation, + "claims", claims, + "bundleRef", bundleRef, + "snapshotIdentity", sourceHash); + bundle.put("evaluationIdentity", sha256(canonicalBytes(evaluation))); + byte[] bundleBytes = canonicalBytes(bundle); + + String fingerprint = publicKeyFingerprint((RSAPublicKey) signingKey.getPublic()); + String publicDataDigest = + AccountJwtJwksPublicationRepository.publicDataDigest( + jwksJson, "{\"generation\":\"1\",\"kid\":\"" + KID + "\"}"); + byte[] signerReceipt = + canonicalBytes( + Map.ofEntries( + Map.entry("schema", "account-control-ui-committed-signer/v1"), + Map.entry("environmentId", ENVIRONMENT), + Map.entry("clusterId", CLUSTER), + Map.entry("namespace", NAMESPACE), + Map.entry("clusterIncarnationUid", CLUSTER_UID), + Map.entry("namespaceUid", NAMESPACE_UID), + Map.entry("trustBindingDigest", trustBindingDigest), + Map.entry("trustConfigRevision", "trust-r1"), + Map.entry("apiBindingDigest", API_BINDING_DIGEST), + Map.entry("apiConfigRevision", "api-r1"), + Map.entry("promotionOperationId", PROMOTION_OPERATION_ID.toString()), + Map.entry("promotionRequestDigest", PROMOTION_REQUEST_DIGEST), + Map.entry("generationOperationId", GENERATION_OPERATION_ID.toString()), + Map.entry("signerGeneration", "1"), + Map.entry("kid", KID), + Map.entry("algorithm", "RS256"), + Map.entry("publicKeyFingerprint", fingerprint), + Map.entry("privateReceiptDigest", PRIVATE_RECEIPT_DIGEST), + Map.entry("privateResourceVersion", "22"), + Map.entry("publicReceiptDigest", PUBLIC_RECEIPT_DIGEST), + Map.entry("publicResourceVersion", "23"), + Map.entry("publicConfigMapUid", CONFIG_MAP_UID), + Map.entry("publicDataDigest", publicDataDigest))); + + Map authBundleReference = new LinkedHashMap<>(bundleRef); + authBundleReference.put("canonicalSha256", sha256(bundleBytes)); + Map activeRegistryRecord = + new LinkedHashMap<>( + Map.ofEntries( + Map.entry("schemaVersion", 1), + Map.entry("registryVersion", 2), + Map.entry("tokenHash", tokenHash), + Map.entry("kid", KID), + Map.entry("signerGeneration", "1"), + Map.entry("issuer", ISSUER), + Map.entry("profile", "control-ui"), + Map.entry("type", "control-ui"), + Map.entry("audience", "control-ui"), + Map.entry("accountId", issuanceAccountId.toString()), + Map.entry("jti", TOKEN_ID.toString()), + Map.entry("iat", NOW_SECONDS), + Map.entry("nbf", NOW_SECONDS), + Map.entry("exp", EXPIRY_SECONDS), + Map.entry("tokenGeneration", 1), + Map.entry("authorityTuple", claims.get("authorityTuple")), + Map.entry("membershipVersion", claims.get("membershipVersion")), + Map.entry("issuanceFence", 1), + Map.entry("operationId", OPERATION_ID.toString()), + Map.entry("requestId", REQUEST_ID.toString()), + Map.entry("requestDigest", REQUEST_DIGEST), + Map.entry("state", "active"), + Map.entry("authoritySourceVersions", sourceVersions), + Map.entry("authEvidenceBundle", authBundleReference), + Map.entry("originalSignerReceiptDigest", sha256(signerReceipt)))); + byte[] activeRegistry = canonicalBytes(activeRegistryRecord); + Map pendingRegistryRecord = new LinkedHashMap<>(activeRegistryRecord); + pendingRegistryRecord.put("state", "pending"); + pendingRegistryRecord.put("registryVersion", 1); + byte[] pendingRegistry = canonicalBytes(pendingRegistryRecord); + byte[] pendingReceipt = + canonicalBytes( + Map.of( + "schema", + "account-control-ui-pending-readback/v1", + "tokenHash", + tokenHash, + "recordDigest", + sha256(pendingRegistry), + "expiryMillis", + Math.multiplyExact(EXPIRY_SECONDS, 1000L), + "aclIdentity", + "account_coord_app", + "localAofCount", + localAofCount, + "replicaAofCount", + 1)); + + var committedIssuance = mock(CommittedIssuance.class); + when(committedIssuance.requestId()).thenReturn(REQUEST_ID); + when(committedIssuance.operationId()).thenReturn(OPERATION_ID); + when(committedIssuance.tokenJti()).thenReturn(TOKEN_ID); + when(committedIssuance.accountId()).thenReturn(issuanceAccountId); + when(committedIssuance.tenantId()).thenReturn(TENANT_ID); + when(committedIssuance.callerWorkload()).thenReturn("logging-admin-service"); + when(committedIssuance.callerContextId()).thenReturn(CALLER_CONTEXT_ID); + when(committedIssuance.requestDigest()).thenReturn(REQUEST_DIGEST); + when(committedIssuance.claims()).thenReturn(canonicalBytes(claims)); + when(committedIssuance.source()).thenReturn(sourceBytes); + when(committedIssuance.bundle()).thenReturn(bundleBytes); + when(committedIssuance.signerReceipt()).thenReturn(signerReceipt); + when(committedIssuance.issuedAtEpochSecond()).thenReturn(NOW_SECONDS); + when(committedIssuance.expiresAtEpochSecond()).thenReturn(EXPIRY_SECONDS); + when(committedIssuance.expiryMillis()).thenReturn(Math.multiplyExact(EXPIRY_SECONDS, 1000L)); + when(committedIssuance.status()).thenReturn("COMMITTED"); + when(committedIssuance.tokenHash()).thenReturn(tokenHash); + when(committedIssuance.pendingRegistry()).thenReturn(pendingRegistry); + when(committedIssuance.activeRegistry()).thenReturn(activeRegistry); + when(committedIssuance.pendingReceipt()).thenReturn(pendingReceipt); + when(issuances.readCommitted(tokenHash)).thenReturn(Optional.of(committedIssuance)); + + configureSignerReadback(mismatchPublicReceipt ? "0".repeat(64) : publicDataDigest); + configureRegistry(activeRegistry); + configureCurrentSources(currentTenantGeneration, currentMembershipGeneration, roleSnapshot); + + PlatformTransactionManager transactionManager = mock(PlatformTransactionManager.class); + when(transactionManager.getTransaction(any(TransactionDefinition.class))) + .thenReturn(new SimpleTransactionStatus()); + verifier = + new AccountControlUiCurrentActorVerifier( + publicJwks, + signerStates, + materializerTrust, + apiBinding, + registry, + issuances, + sourceEvidence, + generations, + tenantEvents, + memberships, + membershipPairs, + roleSnapshots, + outbox, + transactionManager, + Clock.fixed(NOW, ZoneId.of("UTC"))); + } + + private final AccountJwtSignerMaterializerTrustBinding materializerTrust = + mock(AccountJwtSignerMaterializerTrustBinding.class); + private final AccountJwtJwksApiBinding apiBinding = mock(AccountJwtJwksApiBinding.class); + private AccountControlUiRegistryReader registry; + + private void configureSignerReadback(String originalPublicDataDigest) throws Exception { + var original = mock(OriginalCommittedSignerEvidence.class); + var promotion = mock(PromotionOperationEvidence.class); + var generation = mock(GenerationResult.class); + var privateReceipt = mock(PrivatePromotionReceipt.class); + var publicReceipt = mock(ActiveJwksPromotionReceipt.class); + when(original.promotion()).thenReturn(promotion); + when(original.generationResult()).thenReturn(generation); + when(original.privateReceipt()).thenReturn(privateReceipt); + when(original.publicReceipt()).thenReturn(publicReceipt); + when(promotion.status()).thenReturn("COMMITTED"); + when(promotion.operationId()).thenReturn(PROMOTION_OPERATION_ID); + when(promotion.requestDigest()).thenReturn(PROMOTION_REQUEST_DIGEST); + when(promotion.generationOperationId()).thenReturn(GENERATION_OPERATION_ID); + when(generation.operationId()).thenReturn(GENERATION_OPERATION_ID); + when(generation.targetKid()).thenReturn(KID); + when(generation.targetGeneration()).thenReturn("1"); + when(generation.targetAlgorithm()).thenReturn("RS256"); + when(generation.publicKeyFingerprint()) + .thenReturn(publicKeyFingerprint((RSAPublicKey) signingKey.getPublic())); + when(privateReceipt.receiptDigest()).thenReturn(PRIVATE_RECEIPT_DIGEST); + when(privateReceipt.observedResourceVersion()).thenReturn("22"); + when(publicReceipt.receiptDigest()).thenReturn(PUBLIC_RECEIPT_DIGEST); + when(publicReceipt.observedResourceVersion()).thenReturn("23"); + when(publicReceipt.configMapUid()).thenReturn(CONFIG_MAP_UID); + when(publicReceipt.publicDataDigest()).thenReturn(originalPublicDataDigest); + when(signerStates.readOriginalCommittedSigner( + any(), + any(), + eq(API_BINDING_DIGEST), + eq("api-r1"), + eq(PROMOTION_OPERATION_ID), + eq(GENERATION_OPERATION_ID))) + .thenReturn(Optional.of(original)); + } + + private void configureRegistry(byte[] activeRegistry) { + StatefulRedisConnection connection = mock(StatefulRedisConnection.class); + ClientOptions options = mock(ClientOptions.class); + @SuppressWarnings("unchecked") + RedisCommands commands = mock(RedisCommands.class); + when(connection.isOpen()).thenReturn(true); + when(connection.getOptions()).thenReturn(options); + when(options.isAutoReconnect()).thenReturn(false); + when(connection.sync()).thenReturn(commands); + when(commands.aclWhoami()).thenReturn(AccountControlUiRegistryReader.REQUIRED_ACL_IDENTITY); + when(commands.get(any(byte[].class))).thenReturn(activeRegistry); + when(commands.pexpiretime(any(byte[].class))) + .thenReturn(Math.multiplyExact(EXPIRY_SECONDS, 1000L)); + registry = new AccountControlUiRegistryReader(() -> connection); + } + + private void configureCurrentSources( + long currentTenantGeneration, + long currentMembershipGeneration, + List currentRoleSnapshot) { + IssuanceFence fence = new IssuanceFence(ACCOUNT_ID, 1L, 1L); + String issuerStream = "account:auth-authority:v1:issuer/" + ISSUER; + String accountStream = "account:auth-authority:v1:account/" + ACCOUNT_ID; + CurrentSourceEvidence issuerSource = + new CurrentSourceEvidence( + AuthorityScope.issuer(ISSUER), + 1L, + 1L, + null, + new AccountAuthoritySourceEvidenceRepository.SourceCheckpoint( + issuerStream, 0L, Optional.empty(), Optional.empty()), + Optional.empty(), + "ISSUER_SCOPE_INSERT", + null, + null, + 1L, + null); + CurrentSourceEvidence accountSource = + new CurrentSourceEvidence( + AuthorityScope.account(ACCOUNT_ID), + 1L, + 1L, + fence, + new AccountAuthoritySourceEvidenceRepository.SourceCheckpoint( + accountStream, 0L, Optional.empty(), Optional.empty()), + Optional.empty(), + "ACCOUNT_REPOSITORY_INSERT", + 77L, + AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT.name(), + 77L, + 77L); + IssuerAccountSourceSnapshot sourceSnapshot = + new IssuerAccountSourceSnapshot(issuerSource, accountSource, fence); + when(sourceEvidence.readCurrentIssuerAccountSources(ISSUER, ACCOUNT_ID)) + .thenReturn(sourceSnapshot); + + ScopeState issuerState = new ScopeState(AuthorityScope.issuer(ISSUER), 1L, 1L, null); + ScopeState accountState = new ScopeState(AuthorityScope.account(ACCOUNT_ID), 1L, 1L, fence); + ScopeState tenantState = + new ScopeState( + AuthorityScope.tenant(TENANT_ID), + currentTenantGeneration, + currentTenantGeneration, + null); + ScopeState membershipState = + new ScopeState( + AuthorityScope.membership(ACCOUNT_ID, TENANT_ID), + currentMembershipGeneration, + currentMembershipGeneration, + fence); + CompositeSnapshot composite = + new CompositeSnapshot( + issuerState, accountState, List.of(tenantState), List.of(membershipState), fence); + when(generations.readCompositeSnapshot( + eq(ISSUER), eq(ACCOUNT_ID), eq(List.of(TENANT_ID)), eq(List.of(TENANT_ID)))) + .thenReturn(composite); + + TenantAuthorityEventV1Codec.Event tenantEvent = mock(TenantAuthorityEventV1Codec.Event.class); + when(tenantEvent.tenantId()).thenReturn(TENANT_ID); + when(tenantEvent.tenantAuthorityGeneration()).thenReturn(currentTenantGeneration); + when(tenantEvent.tenantAuthoritySourceVersion()).thenReturn(currentTenantGeneration); + when(tenantEvents.readCurrentByTenant(TENANT_ID)).thenReturn(tenantEvent); + + VerifiedTenantProvenance provenance = + new VerifiedTenantProvenance( + null, + TenantProvenanceKind.FRESH_GAME_DESIGN, + UUID.fromString("a0000000-0000-4000-8000-00000000000a"), + "sha256:" + "9".repeat(64)); + MembershipEvent membershipEvent = + MembershipAuthorityEventV1Codec.seal( + membershipEventPreimage( + currentTenantGeneration, currentMembershipGeneration, List.of("tenantAdmin"))); + PairAuthority pair = + new PairAuthority( + ACCOUNT_ID, + TENANT_ID, + provenance, + true, + 1L, + currentMembershipGeneration, + 1L, + membershipEvent.eventId(), + membershipEvent.eventDigest(), + false); + when(membershipPairs.readPositive(ACCOUNT_ID, TENANT_ID)).thenReturn(Optional.of(pair)); + + Account account = new Account(); + account.setId(101L); + account.setAccountUuid(ACCOUNT_ID); + AccountTenantMembership membership = new AccountTenantMembership(); + membership.setId(202L); + membership.setAccount(account); + membership.setTenantUuid(TENANT_ID); + membership.setLifecycleState("ACTIVE"); + membership.setMembershipVersion(1L); + membership.setMembershipAuthorityGeneration(currentMembershipGeneration); + when(memberships.findFreshMembership(ACCOUNT_ID, TENANT_ID)) + .thenReturn(Optional.of(membership)); + RoleSnapshot roles = + new RoleSnapshot( + 101L, null, 202L, 1L, currentRoleSnapshot, ACCOUNT_ID, TENANT_ID, provenance); + when(roleSnapshots.findForCanonicalUpdate(ACCOUNT_ID, TENANT_ID, provenance, 202L, 1L)) + .thenReturn(Optional.of(roles)); + + String streamKey = + MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX + + "membership/" + + ACCOUNT_ID + + "/" + + TENANT_ID; + AccountAuthorityOutboxRepository.Event membershipOutboxEvent = + new AccountAuthorityOutboxRepository.Event( + streamKey, + membershipEvent.requestId(), + 1L, + membershipEvent.eventId(), + membershipEvent.eventDigest(), + membershipEvent.canonicalJson().getBytes(StandardCharsets.UTF_8)); + when(outbox.findEvent(streamKey, 1L)).thenReturn(Optional.of(membershipOutboxEvent)); + } + } + + private static Map claims(UUID accountId, List globalRoles) { + Map authorityTuple = + new LinkedHashMap<>( + Map.of( + "issuerAuthGeneration", 1, + "accountAuthorityGeneration", 1, + "tenantAuthorityGeneration", Map.of(TENANT_ID.toString(), 1), + "membershipAuthorityGeneration", Map.of(TENANT_ID.toString(), 1), + "privateRealmGrantVersions", List.of())); + Map claims = + new LinkedHashMap<>( + Map.ofEntries( + Map.entry("iss", ISSUER), + Map.entry("sub", accountId.toString()), + Map.entry("jti", TOKEN_ID.toString()), + Map.entry("accountId", accountId.toString()), + Map.entry("aud", "control-ui"), + Map.entry("iat", NOW_SECONDS), + Map.entry("nbf", NOW_SECONDS), + Map.entry("exp", EXPIRY_SECONDS), + Map.entry("tokenGeneration", 1), + Map.entry("authorityTuple", authorityTuple), + Map.entry("membershipVersion", Map.of(TENANT_ID.toString(), 1)), + Map.entry("issuanceFence", 1), + Map.entry("scopedRoles", Map.of(TENANT_ID.toString(), List.of("tenantAdmin"))))); + if (globalRoles != null) { + claims.put("globalRoles", globalRoles); + } + return claims; + } + + private static Map membershipEventPreimage( + long tenantGeneration, long membershipGeneration, List roles) { + String sourceScope = "membership/" + ACCOUNT_ID + "/" + TENANT_ID; + String streamKey = MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX + sourceScope; + Map tuple = + Map.of( + "issuerAuthGeneration", "1", + "accountAuthorityGeneration", "1", + "tenantAuthorityGeneration", + Map.of(TENANT_ID.toString(), Long.toString(tenantGeneration)), + "membershipAuthorityGeneration", + Map.of(TENANT_ID.toString(), Long.toString(membershipGeneration)), + "privateRealmGrantVersions", List.of()); + return Map.ofEntries( + Map.entry("schemaVersion", MembershipAuthorityEventV1Codec.SCHEMA_VERSION), + Map.entry("eventType", MembershipAuthorityEventV1Codec.EVENT_TYPE), + Map.entry("eventId", MEMBERSHIP_EVENT_ID.toString()), + Map.entry("requestId", MEMBERSHIP_EVENT_ID.toString()), + Map.entry("outboxStreamKey", streamKey), + Map.entry("outboxSequence", "1"), + Map.entry("sourceScope", sourceScope), + Map.entry("accountId", ACCOUNT_ID.toString()), + Map.entry("tenantId", TENANT_ID.toString()), + Map.entry("membershipExists", true), + Map.entry("membershipLifecycleState", "ACTIVE"), + Map.entry("membershipVersion", Map.of(TENANT_ID.toString(), "1")), + Map.entry("membershipAuthorityGeneration", Long.toString(membershipGeneration)), + Map.entry("authorityTuple", tuple), + Map.entry("issuanceFence", "1"), + Map.entry("roles", roles), + Map.entry("gameplayAdmissionAllowed", true), + Map.entry("callerBoundAuthorityInvalidated", false)); + } + + private static Map tokenIdentity(Map claims) { + return Map.of( + "jti", claims.get("jti"), + "tokenGeneration", claims.get("tokenGeneration"), + "iat", claims.get("iat"), + "nbf", claims.get("nbf"), + "exp", claims.get("exp")); + } + + private static Map sourceVersions() { + return Map.of( + "ISSUER:" + ISSUER, 1, + "ACCOUNT:" + ACCOUNT_ID, 1, + "TENANT:" + TENANT_ID, 1, + "MEMBERSHIP:" + ACCOUNT_ID + ":" + TENANT_ID, 1); + } + + private static SourceIdentity sourceIdentity() { + return new SourceIdentity( + ENVIRONMENT, + CLUSTER, + CLUSTER_UID, + NAMESPACE, + NAMESPACE_UID, + CONFIG_MAP_UID, + "api-r1", + "https://kubernetes.test:6443", + API_CA_DIGEST); + } + + private static String jwks(RSAPublicKey key) throws Exception { + String modulus = + Base64.getUrlEncoder() + .withoutPadding() + .encodeToString(unsigned(key.getModulus().toByteArray())); + String exponent = + Base64.getUrlEncoder() + .withoutPadding() + .encodeToString(unsigned(key.getPublicExponent().toByteArray())); + return JSON.writeValueAsString( + Map.of( + "keys", + List.of( + Map.of( + "kty", + "RSA", + "use", + "sig", + "alg", + "RS256", + "kid", + KID, + "key_ops", + List.of("verify"), + "n", + modulus, + "e", + exponent)))); + } + + private static String publicKeyFingerprint(RSAPublicKey key) throws Exception { + String modulus = + Base64.getUrlEncoder() + .withoutPadding() + .encodeToString(unsigned(key.getModulus().toByteArray())); + String exponent = + Base64.getUrlEncoder() + .withoutPadding() + .encodeToString(unsigned(key.getPublicExponent().toByteArray())); + byte[] canonical = canonicalBytes(Map.of("e", exponent, "kty", "RSA", "n", modulus)); + return sha256(canonical); + } + + private static byte[] unsigned(byte[] value) { + return value.length > 1 && value[0] == 0 + ? java.util.Arrays.copyOfRange(value, 1, value.length) + : value; + } + + private static String sign(Map claims, KeyPair keyPair) throws Exception { + byte[] header = canonicalBytes(Map.of("alg", "RS256", "kid", KID, "typ", "JWT")); + byte[] payload = canonicalBytes(claims); + Base64.Encoder encoder = Base64.getUrlEncoder().withoutPadding(); + String signingInput = encoder.encodeToString(header) + "." + encoder.encodeToString(payload); + Signature signature = Signature.getInstance("SHA256withRSA"); + signature.initSign(keyPair.getPrivate()); + signature.update(signingInput.getBytes(StandardCharsets.US_ASCII)); + return signingInput + "." + encoder.encodeToString(signature.sign()); + } + + private static byte[] canonicalBytes(Object value) throws Exception { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } + + private static String sha256(byte[] bytes) throws Exception { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiRegistryReaderTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiRegistryReaderTest.java new file mode 100644 index 0000000000..6216b465c2 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiRegistryReaderTest.java @@ -0,0 +1,160 @@ +package net.firedevops.firemud.accountservice.service.session; + +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.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import io.lettuce.core.ClientOptions; +import io.lettuce.core.api.StatefulRedisConnection; +import io.lettuce.core.api.sync.RedisCommands; +import java.nio.charset.StandardCharsets; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import org.junit.jupiter.api.Test; +import tools.jackson.databind.json.JsonMapper; + +class AccountControlUiRegistryReaderTest { + private static final JsonMapper JSON = JsonMapper.builder().build(); + private static final String TOKEN_HASH = "a".repeat(64); + + @Test + void acceptsOnlyTheExactCanonicalActiveProfileRecord() throws Exception { + byte[] bytes = canonicalRecord(); + + var parsed = AccountControlUiRegistryReader.parseActiveRecord(bytes, TOKEN_HASH); + + assertThat(parsed).containsEntry("tokenHash", TOKEN_HASH).containsEntry("state", "active"); + } + + @Test + void rejectsUnknownFieldsAndNonCanonicalBytes() throws Exception { + Map extended = new LinkedHashMap<>(record()); + extended.put("unexpected", true); + byte[] withUnknown = canonicalBytes(extended); + + assertThatThrownBy( + () -> AccountControlUiRegistryReader.parseActiveRecord(withUnknown, TOKEN_HASH)) + .isInstanceOf(IllegalStateException.class); + + String canonical = new String(canonicalRecord(), StandardCharsets.UTF_8); + byte[] nonCanonical = (" " + canonical).getBytes(StandardCharsets.UTF_8); + assertThatThrownBy( + () -> AccountControlUiRegistryReader.parseActiveRecord(nonCanonical, TOKEN_HASH)) + .isInstanceOf(IllegalStateException.class); + } + + @Test + void readsOnlyAfterLiveAclIdentityAndExactExpiryReadback() throws Exception { + byte[] active = canonicalRecord(); + long deadline = 1_800_000_000_000L; + StatefulRedisConnection connection = mock(StatefulRedisConnection.class); + ClientOptions options = mock(ClientOptions.class); + @SuppressWarnings("unchecked") + RedisCommands commands = mock(RedisCommands.class); + when(connection.isOpen()).thenReturn(true); + when(connection.getOptions()).thenReturn(options); + when(options.isAutoReconnect()).thenReturn(false); + when(connection.sync()).thenReturn(commands); + when(commands.aclWhoami()).thenReturn(AccountControlUiRegistryReader.REQUIRED_ACL_IDENTITY); + when(commands.get(any(byte[].class))).thenReturn(active); + when(commands.pexpiretime(any(byte[].class))).thenReturn(deadline); + + AccountCoordinationPinnedConnectionProvider provider = () -> connection; + byte[] observed = new AccountControlUiRegistryReader(provider).readActive(TOKEN_HASH); + + assertThat(observed).isEqualTo(active).isNotSameAs(active); + verify(commands).aclWhoami(); + verify(commands).pexpiretime(any(byte[].class)); + } + + @Test + void deniesWhenPhysicalExpiryDiffersFromExactTokenExpiry() throws Exception { + StatefulRedisConnection connection = mock(StatefulRedisConnection.class); + ClientOptions options = mock(ClientOptions.class); + @SuppressWarnings("unchecked") + RedisCommands commands = mock(RedisCommands.class); + when(connection.isOpen()).thenReturn(true); + when(connection.getOptions()).thenReturn(options); + when(options.isAutoReconnect()).thenReturn(false); + when(connection.sync()).thenReturn(commands); + when(commands.aclWhoami()).thenReturn(AccountControlUiRegistryReader.REQUIRED_ACL_IDENTITY); + when(commands.get(any(byte[].class))).thenReturn(canonicalRecord()); + when(commands.pexpiretime(any(byte[].class))).thenReturn(1_800_000_300_000L); + + AccountControlUiRegistryReader reader = new AccountControlUiRegistryReader(() -> connection); + + assertThatThrownBy(() -> reader.readActive(TOKEN_HASH)) + .isInstanceOf(IllegalStateException.class); + } + + @Test + void computesExactTokenExpiryWithCheckedArithmetic() { + assertThat(AccountControlUiRegistryReader.checkedExpiryMillis(1_800_000_000L)) + .isEqualTo(1_800_000_000_000L); + assertThatThrownBy(() -> AccountControlUiRegistryReader.checkedExpiryMillis(Long.MAX_VALUE)) + .isInstanceOf(IllegalStateException.class); + } + + private static Map record() { + Map tuple = + Map.of( + "issuerAuthGeneration", 1, + "accountAuthorityGeneration", 1, + "tenantAuthorityGeneration", Map.of("20000000-0000-4000-8000-000000000002", 1), + "membershipAuthorityGeneration", Map.of("20000000-0000-4000-8000-000000000002", 1), + "privateRealmGrantVersions", List.of()); + return Map.ofEntries( + Map.entry("schemaVersion", 1), + Map.entry("registryVersion", 2), + Map.entry("tokenHash", TOKEN_HASH), + Map.entry("kid", "key-1"), + Map.entry("signerGeneration", "1"), + Map.entry("issuer", "firemud-account-service"), + Map.entry("profile", "control-ui"), + Map.entry("type", "control-ui"), + Map.entry("audience", "control-ui"), + Map.entry("accountId", "10000000-0000-4000-8000-000000000001"), + Map.entry("jti", UUID.fromString("30000000-0000-4000-8000-000000000003").toString()), + Map.entry("iat", 1_799_999_700), + Map.entry("nbf", 1_799_999_700), + Map.entry("exp", 1_800_000_000), + Map.entry("tokenGeneration", 1), + Map.entry("authorityTuple", tuple), + Map.entry("membershipVersion", Map.of("20000000-0000-4000-8000-000000000002", 1)), + Map.entry("issuanceFence", 1), + Map.entry("operationId", "40000000-0000-4000-8000-000000000004"), + Map.entry("requestId", "50000000-0000-4000-8000-000000000005"), + Map.entry("requestDigest", "b".repeat(64)), + Map.entry("state", "active"), + Map.entry( + "authoritySourceVersions", Map.of("ACCOUNT:10000000-0000-4000-8000-000000000001", 1)), + Map.entry( + "authEvidenceBundle", + Map.of( + "bundleVersion", + "1", + "sourceVersion", + "1", + "sourceFence", + "1", + "linearization", + "1", + "canonicalSha256", + "c".repeat(64))), + Map.entry("originalSignerReceiptDigest", "d".repeat(64))); + } + + private static byte[] canonicalRecord() throws Exception { + return canonicalBytes(record()); + } + + private static byte[] canonicalBytes(Object value) throws Exception { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksConfigMapClientTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksConfigMapClientTest.java new file mode 100644 index 0000000000..c38bb11fe1 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksConfigMapClientTest.java @@ -0,0 +1,591 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import net.firedevops.firemud.accountservice.config.AccountJwtJwksApiBinding; +import net.firedevops.firemud.accountservice.config.AccountJwtJwksApiBinding.ApiCall; +import net.firedevops.firemud.accountservice.config.AccountJwtJwksApiBinding.ApiResponse; +import net.firedevops.firemud.accountservice.config.AccountJwtJwksApiBinding.ParsedBinding; +import net.firedevops.firemud.accountservice.service.session.AccountJwtJwksConfigMapClient.ApiSession; +import net.firedevops.firemud.accountservice.service.session.AccountJwtJwksConfigMapClient.CasConflictException; +import net.firedevops.firemud.accountservice.service.session.AccountJwtJwksConfigMapClient.CasObservation; +import net.firedevops.firemud.accountservice.service.session.AccountJwtJwksConfigMapClient.ConfigMapSnapshot; +import net.firedevops.firemud.accountservice.service.session.AccountJwtJwksConfigMapClient.Outcome; +import net.firedevops.firemud.accountservice.service.session.AccountJwtJwksConfigMapClient.ResourceMissingException; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; + +class AccountJwtJwksConfigMapClientTest { + private static final String NAMESPACE = "firemud-prod"; + private static final String KUBE_SYSTEM_UID = "11111111-1111-4111-8111-111111111111"; + private static final String TARGET_NAMESPACE_UID = "22222222-2222-4222-8222-222222222222"; + private static final String CONFIG_MAP_UID = "33333333-3333-4333-8333-333333333333"; + private static final String API_USERNAME = "system:serviceaccount:firemud-prod:account-service"; + private static final String JWKS_OLD = "{\"keys\":[{\"kty\":\"RSA\",\"kid\":\"old\"}]}"; + private static final String JWKS_NEW = "{\"keys\":[{\"kty\":\"RSA\",\"kid\":\"new\"}]}"; + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + @org.junit.jupiter.api.Test + void observesOnlyFixedConfigMapAfterPrincipalAndNamespaceChecks() { + FakeKubernetesApi api = new FakeKubernetesApi(); + AccountJwtJwksConfigMapClient client = client(api); + + ConfigMapSnapshot observed = client.observe(); + + assertThat(observed.uid()).isEqualTo(CONFIG_MAP_UID); + assertThat(observed.resourceVersion()).isEqualTo("41"); + assertThat(observed.data()).containsEntry("unrelated.txt", "retain"); + assertThat(api.calls) + .containsExactly( + ApiCall.REVIEW_AUTHENTICATED_PRINCIPAL, + ApiCall.READ_KUBE_SYSTEM_NAMESPACE, + ApiCall.READ_TARGET_NAMESPACE, + ApiCall.READ_JWKS_CONFIG_MAP); + assertThat(api.calls) + .allMatch( + call -> + Set.of( + ApiCall.REVIEW_AUTHENTICATED_PRINCIPAL, + ApiCall.READ_KUBE_SYSTEM_NAMESPACE, + ApiCall.READ_TARGET_NAMESPACE, + ApiCall.READ_JWKS_CONFIG_MAP, + ApiCall.PATCH_JWKS_CONFIG_MAP) + .contains(call)); + } + + @org.junit.jupiter.api.Test + void absentPrecreatedConfigMapFailsWithoutCreateOrWrite() { + FakeKubernetesApi api = new FakeKubernetesApi(); + api.resourceExists = false; + AccountJwtJwksConfigMapClient client = client(api); + + assertThatThrownBy(client::observe).isInstanceOf(ResourceMissingException.class); + + assertThat(api.calls) + .containsExactly( + ApiCall.REVIEW_AUTHENTICATED_PRINCIPAL, + ApiCall.READ_KUBE_SYSTEM_NAMESPACE, + ApiCall.READ_TARGET_NAMESPACE, + ApiCall.READ_JWKS_CONFIG_MAP); + assertThat(api.patchCount).isZero(); + } + + @org.junit.jupiter.api.Test + void oversizedConfigMapResponseIsRejectedAtTheBound() { + FakeKubernetesApi api = new FakeKubernetesApi(); + api.oversizedConfigMapResponse = true; + + assertThatThrownBy(() -> client(api).observe()) + .isInstanceOf(AccountJwtJwksConfigMapClient.ApiFailureException.class); + + assertThat(api.patchCount).isZero(); + } + + @org.junit.jupiter.api.Test + void rejectsWrongAccountPrincipalAndEitherNamespaceIncarnationBeforeConfigMapRead() { + FakeKubernetesApi wrongPrincipal = new FakeKubernetesApi(); + wrongPrincipal.authenticatedUsername = "system:serviceaccount:firemud-prod:firemud-app"; + assertThatThrownBy(() -> client(wrongPrincipal).observe()) + .isInstanceOf(AccountJwtJwksConfigMapClient.BindingRejectedException.class); + assertThat(wrongPrincipal.calls).containsExactly(ApiCall.REVIEW_AUTHENTICATED_PRINCIPAL); + + FakeKubernetesApi wrongCluster = new FakeKubernetesApi(); + wrongCluster.kubeSystemUid = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"; + assertThatThrownBy(() -> client(wrongCluster).observe()) + .isInstanceOf(AccountJwtJwksConfigMapClient.BindingRejectedException.class); + assertThat(wrongCluster.calls) + .containsExactly( + ApiCall.REVIEW_AUTHENTICATED_PRINCIPAL, ApiCall.READ_KUBE_SYSTEM_NAMESPACE); + + FakeKubernetesApi wrongNamespace = new FakeKubernetesApi(); + wrongNamespace.targetNamespaceUid = "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"; + assertThatThrownBy(() -> client(wrongNamespace).observe()) + .isInstanceOf(AccountJwtJwksConfigMapClient.BindingRejectedException.class); + assertThat(wrongNamespace.calls) + .containsExactly( + ApiCall.REVIEW_AUTHENTICATED_PRINCIPAL, + ApiCall.READ_KUBE_SYSTEM_NAMESPACE, + ApiCall.READ_TARGET_NAMESPACE); + } + + @org.junit.jupiter.api.Test + void rejectsChangedProtectedTrustBeforeWrite() { + FakeKubernetesApi api = new FakeKubernetesApi(); + ConfigMapSnapshot expected = client(api).observe(); + api.rejectPatchForChangedTrust = true; + + assertThatThrownBy(() -> client(api).publish(expected, desired("op-7"))) + .isInstanceOf(AccountJwtJwksConfigMapClient.BindingRejectedException.class); + + assertThat(api.patchCount).isZero(); + assertThat(api.data.get(AccountJwtJwksConfigMapClient.JWKS_DATA_KEY)).isEqualTo(JWKS_OLD); + } + + @org.junit.jupiter.api.Test + void bearerRenewalIsAcceptedOnlyBeforeACompleteOperationAndModeOrOwnerDriftIsRejected() { + FakeKubernetesApi api = new FakeKubernetesApi(); + AccountJwtJwksConfigMapClient client = client(api); + + client.observe(); + api.bearerToken = "rotated-token"; + api.bearerFileKey = "rotated-inode"; + assertThat(client.observe().uid()).isEqualTo(CONFIG_MAP_UID); + + api.calls.clear(); + api.bearerMode = "0444"; + assertThatThrownBy(client::observe) + .isInstanceOf(AccountJwtJwksConfigMapClient.BindingRejectedException.class); + assertThat(api.calls).isEmpty(); + + api.bearerMode = "0440"; + api.bearerOwnerUid = 1001; + assertThatThrownBy(client::observe) + .isInstanceOf(AccountJwtJwksConfigMapClient.BindingRejectedException.class); + assertThat(api.calls).isEmpty(); + } + + @org.junit.jupiter.api.Test + void bearerRotationMidVerificationCannotSplitSelfReviewFromConfigMapRead() { + FakeKubernetesApi api = new FakeKubernetesApi(); + AccountJwtJwksConfigMapClient client = client(api); + api.rotateBearerAfterSelfReview = true; + + assertThatThrownBy(client::observe) + .isInstanceOf(AccountJwtJwksConfigMapClient.BindingRejectedException.class); + assertThat(api.calls).containsExactly(ApiCall.REVIEW_AUTHENTICATED_PRINCIPAL); + + api.calls.clear(); + assertThat(client.observe().uid()).isEqualTo(CONFIG_MAP_UID); + assertThat(api.calls) + .containsExactly( + ApiCall.REVIEW_AUTHENTICATED_PRINCIPAL, + ApiCall.READ_KUBE_SYSTEM_NAMESPACE, + ApiCall.READ_TARGET_NAMESPACE, + ApiCall.READ_JWKS_CONFIG_MAP); + } + + @org.junit.jupiter.api.Test + void compareAndSetConflictNeverOverwritesChangedResourceVersion() { + FakeKubernetesApi api = new FakeKubernetesApi(); + AccountJwtJwksConfigMapClient client = client(api); + ConfigMapSnapshot expected = client.observe(); + api.resourceVersion = "42"; + api.data.put("another-writer", "preserved"); + + assertThatThrownBy(() -> client.publish(expected, desired("op-8"))) + .isInstanceOf(CasConflictException.class); + + assertThat(api.patchCount).isZero(); + assertThat(api.data).containsEntry("another-writer", "preserved"); + } + + @org.junit.jupiter.api.Test + void resourceReplacementAndApiConflictAreBothFenced() { + FakeKubernetesApi replacement = new FakeKubernetesApi(); + AccountJwtJwksConfigMapClient replacementClient = client(replacement); + ConfigMapSnapshot expected = replacementClient.observe(); + replacement.configMapUid = "44444444-4444-4444-8444-444444444444"; + + assertThatThrownBy(() -> replacementClient.publish(expected, desired("op-replaced"))) + .isInstanceOf(CasConflictException.class); + assertThat(replacement.patchCount).isZero(); + + FakeKubernetesApi inFlightConflict = new FakeKubernetesApi(); + AccountJwtJwksConfigMapClient inFlightClient = client(inFlightConflict); + ConfigMapSnapshot beforePatch = inFlightClient.observe(); + inFlightConflict.conflictNextPatch = true; + + assertThatThrownBy(() -> inFlightClient.publish(beforePatch, desired("op-conflict"))) + .isInstanceOf(CasConflictException.class); + assertThat(inFlightConflict.patchCount).isEqualTo(1); + assertThat(inFlightConflict.data.get(AccountJwtJwksConfigMapClient.JWKS_DATA_KEY)) + .isEqualTo(JWKS_OLD); + } + + @org.junit.jupiter.api.Test + void rejectsPrivateJwkMaterialBeforeAnyApiCall() { + FakeKubernetesApi api = new FakeKubernetesApi(); + Map privateJwks = + Map.of( + AccountJwtJwksConfigMapClient.JWKS_DATA_KEY, + "{\"keys\":[{\"kty\":\"RSA\",\"d\":\"private\"}]}", + AccountJwtJwksConfigMapClient.GENERATION_DATA_KEY, + marker("op-private")); + + assertThatThrownBy( + () -> + client(api) + .publish(new ConfigMapSnapshot(CONFIG_MAP_UID, "41", Map.of()), privateJwks)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Account public JWKS contains private material"); + + assertThat(api.calls).isEmpty(); + } + + @org.junit.jupiter.api.Test + void lostPatchAcknowledgementSucceedsOnlyAfterExactSameUidContentReadback() { + FakeKubernetesApi api = new FakeKubernetesApi(); + AccountJwtJwksConfigMapClient client = client(api); + ConfigMapSnapshot expected = client.observe(); + Map desired = desired("durable-operation-9"); + api.loseNextPatchAcknowledgement = true; + + CasObservation result = client.publish(expected, desired); + + assertThat(result.outcome()).isEqualTo(Outcome.EXACT_REPLAY); + assertThat(result.uid()).isEqualTo(CONFIG_MAP_UID); + assertThat(result.priorResourceVersion()).isEqualTo("41"); + assertThat(result.resourceVersion()).isEqualTo("42"); + assertThat(result.publishedData()).isEqualTo(desired); + assertThat(api.patchCount).isEqualTo(1); + } + + @org.junit.jupiter.api.Test + void exactDataAtTheUnchangedExpectedVersionIsNotReportedAsCasSuccess() { + FakeKubernetesApi api = new FakeKubernetesApi(); + Map desired = desired("already-present-operation"); + api.data.putAll(desired); + AccountJwtJwksConfigMapClient client = client(api); + ConfigMapSnapshot expected = client.observe(); + + assertThatThrownBy(() -> client.publish(expected, desired)) + .isInstanceOf(CasConflictException.class) + .hasMessage("Account public JWKS ConfigMap compare-and-set conflict"); + + assertThat(api.patchCount).isZero(); + assertThat(api.resourceVersion).isEqualTo(expected.resourceVersion()); + } + + @org.junit.jupiter.api.Test + void updatePreservesUnrelatedDataAndPatchContainsOnlyOwnedPublicEntries() throws Exception { + FakeKubernetesApi api = new FakeKubernetesApi(); + AccountJwtJwksConfigMapClient client = client(api); + ConfigMapSnapshot expected = client.observe(); + Map desired = desired("durable-operation-10"); + + CasObservation result = client.publish(expected, desired); + + assertThat(result.outcome()).isEqualTo(Outcome.APPLIED); + assertThat(result.resourceVersion()).isEqualTo("42"); + assertThat(result.publishedData()).isEqualTo(desired); + assertThat(api.data) + .containsEntry("unrelated.txt", "retain") + .containsEntry(AccountJwtJwksConfigMapClient.JWKS_DATA_KEY, JWKS_NEW) + .containsEntry( + AccountJwtJwksConfigMapClient.GENERATION_DATA_KEY, marker("durable-operation-10")); + JsonNode patch = JSON.readTree(api.lastPatch); + assertThat(patch.get("metadata").size()).isEqualTo(2); + assertThat(patch.get("metadata").get("uid").asText()).isEqualTo(CONFIG_MAP_UID); + assertThat(patch.get("metadata").get("resourceVersion").asText()).isEqualTo("41"); + assertThat(patch.get("data").size()).isEqualTo(2); + assertThat(patch.get("data").has("unrelated.txt")).isFalse(); + } + + @org.junit.jupiter.api.Test + void activeMarkerCasUsesFreshSnapshotAndPreservesUnrelatedEntries() { + FakeKubernetesApi api = new FakeKubernetesApi(); + AccountJwtJwksConfigMapClient client = client(api); + ConfigMapSnapshot observed = client.observe(); + Map desired = + Map.of( + AccountJwtJwksConfigMapClient.JWKS_DATA_KEY, + JWKS_OLD, + AccountJwtJwksConfigMapClient.GENERATION_DATA_KEY, + marker("active-operation")); + + CasObservation result = client.publishActiveProjection(observed, "41", desired); + + assertThat(result.outcome()).isEqualTo(Outcome.APPLIED); + assertThat(result.priorResourceVersion()).isEqualTo("41"); + assertThat(result.resourceVersion()).isEqualTo("42"); + assertThat(result.readbackData()).containsEntry("unrelated.txt", "retain"); + assertThat(api.patchCount).isEqualTo(1); + } + + @org.junit.jupiter.api.Test + void activeMarkerLostAcknowledgementReplayRequiresAdvancedResourceVersion() { + FakeKubernetesApi api = new FakeKubernetesApi(); + AccountJwtJwksConfigMapClient client = client(api); + ConfigMapSnapshot observed = client.observe(); + Map desired = + Map.of( + AccountJwtJwksConfigMapClient.JWKS_DATA_KEY, + JWKS_OLD, + AccountJwtJwksConfigMapClient.GENERATION_DATA_KEY, + marker("active-operation")); + api.loseNextPatchAcknowledgement = true; + + CasObservation applied = client.publishActiveProjection(observed, "41", desired); + + assertThat(applied.outcome()).isEqualTo(Outcome.EXACT_REPLAY); + assertThat(applied.priorResourceVersion()).isEqualTo("41"); + assertThat(applied.resourceVersion()).isEqualTo("42"); + int writes = api.patchCount; + CasObservation replay = client.publishActiveProjection(client.observe(), "41", desired); + + assertThat(replay.outcome()).isEqualTo(Outcome.EXACT_REPLAY); + assertThat(replay.priorResourceVersion()).isEqualTo("41"); + assertThat(replay.resourceVersion()).isEqualTo("42"); + assertThat(api.patchCount).isEqualTo(writes); + assertThat(api.data).containsEntry("unrelated.txt", "retain"); + } + + @org.junit.jupiter.api.Test + void activeMarkerDoesNotTreatExactDataAtUnchangedPriorVersionAsSuccessfulCas() { + FakeKubernetesApi api = new FakeKubernetesApi(); + AccountJwtJwksConfigMapClient client = client(api); + Map desired = + Map.of( + AccountJwtJwksConfigMapClient.JWKS_DATA_KEY, + JWKS_OLD, + AccountJwtJwksConfigMapClient.GENERATION_DATA_KEY, + marker("active-operation")); + api.data.putAll(desired); + ConfigMapSnapshot observed = client.observe(); + + assertThatThrownBy(() -> client.publishActiveProjection(observed, "41", desired)) + .isInstanceOf(CasConflictException.class); + assertThat(api.patchCount).isZero(); + assertThat(api.resourceVersion).isEqualTo("41"); + } + + @org.junit.jupiter.api.Test + void jwksConfigMapAccessHasNoSecretListCreateOrDeleteCapability() { + assertThat(ApiCall.values()) + .noneMatch( + call -> + call.name().contains("SECRET") + || call.name().contains("CREATE") + || call.name().contains("DELETE")); + assertThat(ApiCall.values()) + .filteredOn(call -> call.name().contains("JWKS_CONFIG_MAP")) + .containsExactly(ApiCall.READ_JWKS_CONFIG_MAP, ApiCall.PATCH_JWKS_CONFIG_MAP); + assertThat(ApiCall.values()) + .filteredOn(call -> call.name().contains("LIST")) + .containsExactly(ApiCall.LIST_VALIDATOR_PODS); + } + + private static AccountJwtJwksConfigMapClient client(FakeKubernetesApi api) { + return new AccountJwtJwksConfigMapClient(api::beginOperation); + } + + private static ParsedBinding parsedBinding() { + return new ParsedBinding( + "revision-1", + "prod", + "prod-cluster-1", + URI.create("https://kubernetes.example:6443/"), + "kubernetes.example", + java.nio.file.Path.of("/etc/firemud/kubernetes-ca.pem"), + "a".repeat(64), + java.nio.file.Path.of("/var/run/secrets/firemud/kubernetes/token"), + NAMESPACE, + KUBE_SYSTEM_UID, + TARGET_NAMESPACE_UID, + API_USERNAME, + "b".repeat(64)); + } + + private static Map desired(String operation) { + return Map.of( + AccountJwtJwksConfigMapClient.JWKS_DATA_KEY, + JWKS_NEW, + AccountJwtJwksConfigMapClient.GENERATION_DATA_KEY, + marker(operation)); + } + + private static String marker(String operation) { + return "{\"ownerOperation\":\"" + operation + "\"}"; + } + + private static String namespaceJson(String name, String uid) { + return "{\"apiVersion\":\"v1\",\"kind\":\"Namespace\",\"metadata\":{\"name\":\"" + + name + + "\",\"uid\":\"" + + uid + + "\"},\"status\":{\"phase\":\"Active\"}}"; + } + + private static final class FakeKubernetesApi { + private final List calls = new ArrayList<>(); + private final Map data = + new LinkedHashMap<>( + Map.of( + AccountJwtJwksConfigMapClient.JWKS_DATA_KEY, + JWKS_OLD, + AccountJwtJwksConfigMapClient.GENERATION_DATA_KEY, + "{\"ownerOperation\":\"old\"}", + "unrelated.txt", + "retain")); + private String authenticatedUsername = API_USERNAME; + private String kubeSystemUid = KUBE_SYSTEM_UID; + private String targetNamespaceUid = TARGET_NAMESPACE_UID; + private String configMapUid = CONFIG_MAP_UID; + private String resourceVersion = "41"; + private String bearerToken = "initial-token"; + private String bearerFileKey = "initial-inode"; + private long bearerOwnerUid; + private long bearerGroupId = 2000; + private String bearerMode = "0440"; + private boolean resourceExists = true; + private boolean oversizedConfigMapResponse; + private boolean rejectPatchForChangedTrust; + private boolean conflictNextPatch; + private boolean loseNextPatchAcknowledgement; + private boolean rotateBearerAfterSelfReview; + private int patchCount; + private String lastPatch; + private Long acceptedBearerOwnerUid; + private Long acceptedBearerGroupId; + private String acceptedBearerMode; + + private ApiSession beginOperation() { + if (acceptedBearerOwnerUid == null) { + acceptedBearerOwnerUid = bearerOwnerUid; + acceptedBearerGroupId = bearerGroupId; + acceptedBearerMode = bearerMode; + } + if (acceptedBearerOwnerUid != bearerOwnerUid + || acceptedBearerGroupId != bearerGroupId + || !acceptedBearerMode.equals(bearerMode)) { + throw new AccountJwtJwksApiBinding.BindingRejectedException(); + } + return new FakeApiSession(this, bearerToken, bearerFileKey); + } + + private ApiResponse send(ApiCall call, byte[] body) { + calls.add(call); + ApiResponse response = + switch (call) { + case REVIEW_AUTHENTICATED_PRINCIPAL -> + response( + 201, + "{\"apiVersion\":\"authentication.k8s.io/v1\",\"kind\":\"SelfSubjectReview\"," + + "\"status\":{\"userInfo\":{\"username\":\"" + + authenticatedUsername + + "\"}}}"); + case READ_KUBE_SYSTEM_NAMESPACE -> + response(200, namespaceJson("kube-system", kubeSystemUid)); + case READ_TARGET_NAMESPACE -> + response(200, namespaceJson(NAMESPACE, targetNamespaceUid)); + case READ_JWKS_CONFIG_MAP -> + !resourceExists + ? response(404, "{}") + : oversizedConfigMapResponse + ? response(200, " ".repeat(1024 * 1024 + 1)) + : response(200, configMapJson()); + case PATCH_JWKS_CONFIG_MAP -> patch(body); + case READ_VALIDATOR_DEPLOYMENT, LIST_VALIDATOR_PODS, READ_VALIDATOR_REPLICA_SET -> + throw new AssertionError("Unexpected validator call in ConfigMap client test"); + }; + if (call == ApiCall.REVIEW_AUTHENTICATED_PRINCIPAL && rotateBearerAfterSelfReview) { + rotateBearerAfterSelfReview = false; + bearerToken = "rotated-during-operation"; + bearerFileKey = "rotated-during-operation-inode"; + } + return response; + } + + private ApiResponse patch(byte[] body) { + if (rejectPatchForChangedTrust) { + throw new AccountJwtJwksApiBinding.BindingRejectedException(); + } + patchCount++; + lastPatch = new String(body, StandardCharsets.UTF_8); + if (conflictNextPatch) { + conflictNextPatch = false; + return response(409, "{}"); + } + JsonNode patch; + try { + patch = JSON.readTree(lastPatch); + } catch (Exception ex) { + throw new AssertionError(ex); + } + JsonNode metadata = patch.get("metadata"); + if (!CONFIG_MAP_UID.equals(metadata.get("uid").asText()) + || !resourceVersion.equals(metadata.get("resourceVersion").asText())) { + return response(409, "{}"); + } + JsonNode patchData = patch.get("data"); + patchData.properties().forEach(entry -> data.put(entry.getKey(), entry.getValue().asText())); + resourceVersion = Long.toString(Long.parseLong(resourceVersion) + 1); + if (loseNextPatchAcknowledgement) { + loseNextPatchAcknowledgement = false; + throw new AccountJwtJwksApiBinding.ApiTransportException(); + } + return response(200, configMapJson()); + } + + private String configMapJson() { + try { + Map metadata = + Map.of( + "name", AccountJwtJwksConfigMapClient.CONFIG_MAP_NAME, + "namespace", NAMESPACE, + "uid", configMapUid, + "resourceVersion", resourceVersion); + Map object = + Map.of("apiVersion", "v1", "kind", "ConfigMap", "metadata", metadata, "data", data); + return JSON.writeValueAsString(object); + } catch (Exception ex) { + throw new AssertionError(ex); + } + } + + private static ApiResponse response(int status, String body) { + return new ApiResponse(status, body.getBytes(StandardCharsets.UTF_8)); + } + } + + private static final class FakeApiSession implements ApiSession { + private final FakeKubernetesApi api; + private final ParsedBinding binding = parsedBinding(); + private String bearerTokenSnapshot; + private String bearerFileKeySnapshot; + + private FakeApiSession(FakeKubernetesApi api, String token, String fileKey) { + this.api = api; + this.bearerTokenSnapshot = token; + this.bearerFileKeySnapshot = fileKey; + } + + @Override + public ParsedBinding binding() { + return binding; + } + + @Override + public ApiResponse send(ApiCall call, byte[] body) { + if (bearerTokenSnapshot == null + || !bearerTokenSnapshot.equals(api.bearerToken) + || !bearerFileKeySnapshot.equals(api.bearerFileKey) + || api.acceptedBearerOwnerUid != api.bearerOwnerUid + || api.acceptedBearerGroupId != api.bearerGroupId + || !api.acceptedBearerMode.equals(api.bearerMode)) { + throw new AccountJwtJwksApiBinding.BindingRejectedException(); + } + return api.send(call, body); + } + + @Override + public void close() { + bearerTokenSnapshot = null; + bearerFileKeySnapshot = null; + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksTrustedSourceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksTrustedSourceTest.java new file mode 100644 index 0000000000..ab0d7af8f8 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksTrustedSourceTest.java @@ -0,0 +1,677 @@ +package unit.net.firedevops.firemud.accountservice.service.session; + +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.anyMap; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.config.AccountJwtSignerMaterializerTrustBinding; +import net.firedevops.firemud.accountservice.config.AccountJwtSignerMaterializerTrustBinding.Binding; +import net.firedevops.firemud.accountservice.repository.AccountJwtJwksPublicationRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtJwksPublicationRepository.PrepublicationIntent; +import net.firedevops.firemud.accountservice.repository.AccountJwtJwksPublicationRepository.PublicationEvidence; +import net.firedevops.firemud.accountservice.repository.AccountJwtJwksPublicationRepository.PublicationReceipt; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.ActiveSigner; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.CommittedSignerEvidence; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.DesiredState; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.EnrollmentIdentity; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.GenerationPhase; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.GenerationRequest; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.GenerationResult; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.PromotionOperationEvidence; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.TrustFence; +import net.firedevops.firemud.accountservice.service.session.AccountJwtJwksConfigMapClient; +import net.firedevops.firemud.accountservice.service.session.AccountJwtJwksConfigMapClient.BindingIdentity; +import net.firedevops.firemud.accountservice.service.session.AccountJwtJwksConfigMapClient.ConfigMapSnapshot; +import net.firedevops.firemud.accountservice.service.session.AccountJwtJwksTrustedSource; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.security.AccountPublicJwksCache.PublicJwksSnapshot; +import net.firedevops.firemud.common.security.AccountPublicJwksCache.SourceIdentity; +import net.firedevops.firemud.common.security.AccountPublicJwksCache.SourceUnavailableException; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.SimpleTransactionStatus; + +class AccountJwtJwksTrustedSourceTest { + private static final String ENVIRONMENT = "test"; + private static final String CLUSTER = "cluster-test"; + private static final String NAMESPACE = "firemud-test"; + private static final String CLUSTER_UID = "11111111-1111-4111-8111-111111111111"; + private static final String NAMESPACE_UID = "22222222-2222-4222-8222-222222222222"; + private static final String CONFIG_MAP_UID = "33333333-3333-4333-8333-333333333333"; + private static final String API_BINDING_DIGEST = "a".repeat(64); + private static final String API_CA_DIGEST = "b".repeat(64); + private static final UUID INITIAL_OPERATION_ID = + UUID.fromString("55555555-5555-4555-8555-000000000001"); + private static final UUID NEXT_OPERATION_ID = + UUID.fromString("55555555-5555-4555-8555-000000000002"); + private static final String GENERATION_OPERATION_DIGEST = "1".repeat(64); + private static final String GENERATION_REQUEST_DIGEST = "2".repeat(64); + private static final String GENERATION_RECEIPT_DIGEST = "3".repeat(64); + private static final String JWK_1 = + "{\"alg\":\"RS256\",\"e\":\"AQAB\",\"key_ops\":[\"verify\"],\"kid\":\"key_1\",\"kty\":\"RSA\",\"n\":\"AQID\",\"use\":\"sig\"}"; + private static final String JWK_2 = + "{\"alg\":\"RS256\",\"e\":\"AQAB\",\"key_ops\":[\"verify\"],\"kid\":\"key_2\",\"kty\":\"RSA\",\"n\":\"BAUG\",\"use\":\"sig\"}"; + private static final String JWKS_1 = "{\"keys\":[" + JWK_1 + "]}"; + private static final String JWKS_1_AND_2 = "{\"keys\":[" + JWK_1 + "," + JWK_2 + "]}"; + + @Test + void derivesPinAndReturnsOnlyExactReceiptBackedPublicBytes() { + Fixture fixture = new Fixture(); + + SourceIdentity identity = fixture.source.sourceIdentity(); + PublicJwksSnapshot snapshot = fixture.source.load(); + + assertThat(identity.environmentId()).isEqualTo(ENVIRONMENT); + assertThat(identity.clusterId()).isEqualTo(CLUSTER); + assertThat(identity.clusterIncarnationUid()).isEqualTo(CLUSTER_UID); + assertThat(identity.namespace()).isEqualTo(NAMESPACE); + assertThat(identity.namespaceUid()).isEqualTo(NAMESPACE_UID); + assertThat(identity.configMapUid()).isEqualTo(CONFIG_MAP_UID); + assertThat(identity.bindingRevision()).isEqualTo("api-r1"); + assertThat(identity.apiServerOrigin()).isEqualTo("https://kubernetes.test:6443"); + assertThat(identity.servingCaSha256()).isEqualTo(API_CA_DIGEST); + assertThat(snapshot.sourceIdentity()).isEqualTo(identity); + assertThat(snapshot.jwksBytes()) + .containsExactly(fixture.publicJwks.getBytes(StandardCharsets.UTF_8)); + verify(fixture.desiredStateRepository, never()) + .readCurrentCommittedSigner(any(), any(), any(), any()); + verify(fixture.configMapClient, never()).publish(any(), anyMap()); + } + + @Test + void allowsNewAccountPublicationAtSamePinnedResourceWithoutChangingSourceIdentity() { + Fixture fixture = new Fixture(); + fixture.useCommittedState(); + SourceIdentity identity = fixture.source.sourceIdentity(); + String nextJwks = JWKS_1_AND_2; + String nextMarker = + fixture.marker( + NEXT_OPERATION_ID, + "2", + "key_2", + fingerprint(JWK_2), + Optional.of(new ActiveSigner("1", "key_1"))); + PublicationEvidence nextPublication = + fixture.publication( + nextJwks, + nextMarker, + "42", + "43", + "2", + "key_2", + Optional.of(new ActiveSigner("1", "key_1"))); + Map nextData = + Map.of( + AccountJwtJwksPublicationRepository.JWKS_DATA_KEY, + nextJwks, + AccountJwtJwksPublicationRepository.GENERATION_MARKER_DATA_KEY, + nextMarker, + "operator.note", + "preserved"); + when(fixture.publicationRepository.readCurrentPublication( + eq(fixture.binding.accountBinding()), eq(fixture.trustFence))) + .thenReturn(Optional.of(nextPublication), Optional.of(nextPublication)); + when(fixture.configMapClient.observe()) + .thenReturn(new ConfigMapSnapshot(CONFIG_MAP_UID, "43", nextData)); + + PublicJwksSnapshot snapshot = fixture.source.load(); + + assertThat(snapshot.sourceIdentity()).isEqualTo(identity); + assertThat(snapshot.jwksBytes()).containsExactly(nextJwks.getBytes(StandardCharsets.UTF_8)); + assertThat(new String(snapshot.jwksBytes(), StandardCharsets.UTF_8)).contains(JWK_1, JWK_2); + } + + @Test + void historicalKeyFingerprintRequiresTheCurrentOwnerProvedSetToRetainItsExactIdentity() { + Fixture missingKey = new Fixture(); + missingKey.useCommittedState(); + missingKey.replaceNextJwks("{\"keys\":[" + JWK_2 + "]}"); + assertThatThrownBy(missingKey.source::load) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Account trusted public JWKS source was rejected"); + + Fixture substitutedKey = new Fixture(); + substitutedKey.useCommittedState(); + String substitutedJwk = JWK_1.replace("\"n\":\"AQID\"", "\"n\":\"BAUG\""); + substitutedKey.replaceNextJwks("{\"keys\":[" + substitutedJwk + "," + JWK_2 + "]}"); + assertThatThrownBy(substitutedKey.source::load) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Account trusted public JWKS source was rejected"); + } + + @Test + void deniesSameNamedDestinationWithDifferentClusterIncarnation() { + Fixture fixture = new Fixture(); + Binding wrongIncarnation = binding("44444444-4444-4444-8444-444444444444", NAMESPACE_UID); + when(fixture.materializerTrust.current()).thenReturn(Optional.of(wrongIncarnation)); + + assertThatThrownBy(fixture.source::sourceIdentity) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Account trusted public JWKS source was rejected"); + verify(fixture.configMapClient, never()).observe(); + } + + @Test + void deniesUnexpectedAuthenticatedApiPrincipal() { + Fixture fixture = new Fixture(); + BindingIdentity wrongPrincipal = + new BindingIdentity( + fixture.apiIdentity.bindingDigest(), + fixture.apiIdentity.configRevision(), + fixture.apiIdentity.environmentId(), + fixture.apiIdentity.clusterId(), + fixture.apiIdentity.namespace(), + fixture.apiIdentity.expectedClusterIncarnationUid(), + fixture.apiIdentity.expectedNamespaceUid(), + fixture.apiIdentity.apiServerUrl(), + fixture.apiIdentity.tlsServerName(), + fixture.apiIdentity.servingCaSha256(), + "system:serviceaccount:" + NAMESPACE + ":another-service"); + when(fixture.configMapClient.identity()).thenReturn(wrongPrincipal); + + assertThatThrownBy(fixture.source::sourceIdentity) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Account trusted public JWKS source was rejected"); + verify(fixture.publicationRepository, never()).readCurrentPublication(any(), any()); + verify(fixture.configMapClient, never()).observe(); + } + + @Test + void rejectsRecreatedSameNameConfigMapEvenWithMatchingPublicData() { + Fixture fixture = new Fixture(); + when(fixture.configMapClient.observe()) + .thenReturn( + new ConfigMapSnapshot( + "44444444-4444-4444-8444-444444444444", "42", fixture.snapshot.data())); + + assertThatThrownBy(fixture.source::sourceIdentity) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Account trusted public JWKS source was rejected"); + } + + @Test + void treatsUnreceiptedOrAmbiguousOwnerPublicationAsUnavailableNotAsAKeySet() { + Fixture fixture = new Fixture(); + PublicationEvidence unreceipted = + new PublicationEvidence(fixture.publication.intent(), Optional.empty(), Optional.empty()); + when(fixture.publicationRepository.readCurrentPublication( + eq(fixture.binding.accountBinding()), eq(fixture.trustFence))) + .thenReturn(Optional.of(unreceipted)); + + assertThatThrownBy(fixture.source::sourceIdentity) + .isInstanceOf(SourceUnavailableException.class) + .hasNoCause(); + verify(fixture.configMapClient, never()).observe(); + } + + @Test + void rejectsTrustChangeAcrossTheAuthenticatedRead() { + Fixture fixture = new Fixture(); + Binding changedBinding = binding(CLUSTER_UID, NAMESPACE_UID, "materializer-r2"); + when(fixture.materializerTrust.current()) + .thenReturn(Optional.of(fixture.binding), Optional.of(changedBinding)); + + assertThatThrownBy(fixture.source::sourceIdentity) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Account trusted public JWKS source was rejected"); + } + + @Test + void rejectsReadbackThatDoesNotMatchReceiptResourceVersionOrMarker() { + Fixture fixture = new Fixture(); + Map changedData = + Map.of( + AccountJwtJwksPublicationRepository.JWKS_DATA_KEY, + fixture.publicJwks, + AccountJwtJwksPublicationRepository.GENERATION_MARKER_DATA_KEY, + "{\"phase\":\"OTHER\"}"); + when(fixture.configMapClient.observe()) + .thenReturn(new ConfigMapSnapshot(CONFIG_MAP_UID, "43", changedData)); + + assertThatThrownBy(fixture.source::sourceIdentity) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Account trusted public JWKS source was rejected"); + } + + @Test + void ownerPublicationChangingDuringReadProducesNoSnapshot() { + Fixture fixture = new Fixture(); + when(fixture.publicationRepository.readCurrentPublication( + eq(fixture.binding.accountBinding()), eq(fixture.trustFence))) + .thenReturn(Optional.of(fixture.publication), Optional.empty()); + + assertThatThrownBy(fixture.source::sourceIdentity) + .isInstanceOf(SourceUnavailableException.class) + .hasNoCause(); + } + + @Test + void deniesInitialPrepublicationWhenPublicMarkerClaimsAnActiveFence() { + Fixture fixture = new Fixture(); + String activeMarker = + fixture.marker( + INITIAL_OPERATION_ID, + "1", + "key_1", + fingerprint(JWK_1), + Optional.of(new ActiveSigner("1", "key_1"))); + PublicationEvidence conflicting = + fixture.publication( + fixture.publicJwks, activeMarker, "41", "42", "1", "key_1", Optional.empty()); + when(fixture.publicationRepository.readCurrentPublication( + eq(fixture.binding.accountBinding()), eq(fixture.trustFence))) + .thenReturn(Optional.of(conflicting)); + + assertThatThrownBy(fixture.source::sourceIdentity) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Account trusted public JWKS source was rejected"); + verify(fixture.configMapClient, never()).observe(); + } + + @Test + void deniesInitialPrepublicationWhenConfigMapResourceVersionIsStale() { + Fixture fixture = new Fixture(); + when(fixture.configMapClient.observe()) + .thenReturn(new ConfigMapSnapshot(CONFIG_MAP_UID, "43", fixture.snapshot.data())); + + assertThatThrownBy(fixture.source::sourceIdentity) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Account trusted public JWKS source was rejected"); + } + + private static Binding binding(String clusterUid, String namespaceUid) { + return binding(clusterUid, namespaceUid, "materializer-r1"); + } + + private static Binding binding(String clusterUid, String namespaceUid, String revision) { + String expectedPeer = "spiffe://firemud/ns/" + NAMESPACE + "/sa/jwt-signer-materializer"; + List pins = List.of("c".repeat(64)); + String bindingDigest = + AccountJwtSignerMaterializerTrustBinding.computeBindingDigest( + revision, + ENVIRONMENT, + CLUSTER, + NAMESPACE, + clusterUid, + namespaceUid, + expectedPeer, + pins); + return new Binding( + ENVIRONMENT, + CLUSTER, + NAMESPACE, + clusterUid, + namespaceUid, + expectedPeer, + pins, + revision, + bindingDigest); + } + + private static String sha256(String value) { + try { + return java.util.HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256").digest(value.getBytes(StandardCharsets.UTF_8))); + } catch (Exception unavailable) { + throw new AssertionError(unavailable); + } + } + + private static final class Fixture { + private final AccountJwtJwksConfigMapClient configMapClient = + mock(AccountJwtJwksConfigMapClient.class); + private final AccountJwtSignerMaterializerTrustBinding materializerTrust = + mock(AccountJwtSignerMaterializerTrustBinding.class); + private final AccountJwtSignerDesiredStateRepository desiredStateRepository = + mock(AccountJwtSignerDesiredStateRepository.class); + private final AccountJwtJwksPublicationRepository publicationRepository = + mock(AccountJwtJwksPublicationRepository.class); + private final PlatformTransactionManager transactionManager = + mock(PlatformTransactionManager.class); + private final Binding binding = binding(CLUSTER_UID, NAMESPACE_UID); + private final TrustFence trustFence = + new TrustFence( + CLUSTER_UID, NAMESPACE_UID, binding.bindingDigest(), binding.configRevision()); + private final AccountJwtSignerDesiredStateRepository.Binding accountBinding = + binding.accountBinding(); + private final BindingIdentity apiIdentity = + new BindingIdentity( + API_BINDING_DIGEST, + "api-r1", + ENVIRONMENT, + CLUSTER, + NAMESPACE, + CLUSTER_UID, + NAMESPACE_UID, + "https://kubernetes.test:6443", + "kubernetes.test", + API_CA_DIGEST, + "system:serviceaccount:" + NAMESPACE + ":account-service"); + private final String publicFingerprint = fingerprint(JWK_1); + private final String publicJwks = JWKS_1; + private final EnrollmentIdentity enrollmentIdentity; + private final GenerationRequest initialRequest; + private final GenerationResult initialResult; + private final DesiredState initialDesiredState; + private final String initialMarker; + private final PublicationEvidence publication; + private final ConfigMapSnapshot snapshot; + private final AccountJwtJwksTrustedSource source; + + private Fixture() { + enrollmentIdentity = + new EnrollmentIdentity( + CLUSTER_UID, + NAMESPACE_UID, + binding.bindingDigest(), + binding.configRevision(), + API_BINDING_DIGEST, + "api-r1", + CONFIG_MAP_UID, + "40", + "6".repeat(64)); + initialMarker = + marker(INITIAL_OPERATION_ID, "1", "key_1", publicFingerprint, Optional.empty()); + initialRequest = mock(GenerationRequest.class); + when(initialRequest.phase()).thenReturn(GenerationPhase.GENERATION_RECORDED); + when(initialRequest.operationId()).thenReturn(INITIAL_OPERATION_ID); + when(initialRequest.operationDigest()).thenReturn(GENERATION_OPERATION_DIGEST); + when(initialRequest.generationRequestDigest()).thenReturn(GENERATION_REQUEST_DIGEST); + when(initialRequest.generationReceiptDigest()).thenReturn(GENERATION_RECEIPT_DIGEST); + when(initialRequest.desiredStateVersion()).thenReturn(2L); + when(initialRequest.binding()).thenReturn(accountBinding); + when(initialRequest.trustFence()).thenReturn(trustFence); + when(initialRequest.targetGeneration()).thenReturn("1"); + when(initialRequest.targetKid()).thenReturn("key_1"); + when(initialRequest.publicKeyFingerprint()).thenReturn(publicFingerprint); + when(initialRequest.publicJwkJson()).thenReturn(JWK_1); + when(initialRequest.expectedActive()).thenReturn(Optional.empty()); + when(initialRequest.expectedPublishedActive()).thenReturn(Optional.empty()); + + initialResult = mock(GenerationResult.class); + when(initialResult.operationId()).thenReturn(INITIAL_OPERATION_ID); + when(initialResult.binding()).thenReturn(accountBinding); + when(initialResult.operationDigest()).thenReturn(GENERATION_OPERATION_DIGEST); + when(initialResult.generationRequestDigest()).thenReturn(GENERATION_REQUEST_DIGEST); + when(initialResult.desiredStateVersion()).thenReturn(2L); + when(initialResult.trustFence()).thenReturn(trustFence); + when(initialResult.targetGeneration()).thenReturn("1"); + when(initialResult.targetKid()).thenReturn("key_1"); + when(initialResult.targetAlgorithm()).thenReturn("RS256"); + when(initialResult.publicKeyFingerprint()).thenReturn(publicFingerprint); + when(initialResult.publicJwkJson()).thenReturn(JWK_1); + when(initialResult.receiptDigest()).thenReturn(GENERATION_RECEIPT_DIGEST); + + initialDesiredState = + new DesiredState( + accountBinding, + 2, + Optional.empty(), + Optional.empty(), + Optional.of(INITIAL_OPERATION_ID), + Optional.empty(), + Optional.of(enrollmentIdentity)); + publication = + publication(publicJwks, initialMarker, "41", "42", "1", "key_1", Optional.empty()); + snapshot = + new ConfigMapSnapshot( + CONFIG_MAP_UID, + "42", + Map.of( + AccountJwtJwksPublicationRepository.JWKS_DATA_KEY, + publicJwks, + AccountJwtJwksPublicationRepository.GENERATION_MARKER_DATA_KEY, + initialMarker, + "operator.note", + "retained")); + + when(transactionManager.getTransaction(any())).thenReturn(new SimpleTransactionStatus()); + when(materializerTrust.current()).thenReturn(Optional.of(binding)); + when(configMapClient.identity()).thenReturn(apiIdentity); + when(configMapClient.observe()).thenReturn(snapshot); + when(desiredStateRepository.readEnrollmentState(eq(accountBinding))) + .thenReturn(Optional.of(initialDesiredState)); + when(desiredStateRepository.readCurrentGenerationRequest(eq(accountBinding), eq(trustFence))) + .thenReturn(initialRequest); + when(desiredStateRepository.readCurrentGenerationResult(eq(accountBinding), eq(trustFence))) + .thenReturn(initialResult); + when(publicationRepository.readCurrentPublication(eq(accountBinding), eq(trustFence))) + .thenReturn(Optional.of(publication)); + source = + new AccountJwtJwksTrustedSource( + configMapClient, + materializerTrust, + desiredStateRepository, + publicationRepository, + transactionManager); + } + + private void useCommittedState() { + ActiveSigner active = new ActiveSigner("1", "key_1"); + DesiredState committedState = + new DesiredState( + accountBinding, + 3, + Optional.of(active), + Optional.of(active), + Optional.of(NEXT_OPERATION_ID), + Optional.empty(), + Optional.of(enrollmentIdentity)); + CommittedSignerEvidence committed = mock(CommittedSignerEvidence.class); + PromotionOperationEvidence promotion = mock(PromotionOperationEvidence.class); + AccountJwtSignerDesiredStateRepository.ActiveJwksPromotionReceipt receipt = + mock(AccountJwtSignerDesiredStateRepository.ActiveJwksPromotionReceipt.class); + String activeMarker = activeMarker(active); + String activeDigest = + AccountJwtJwksPublicationRepository.publicDataDigest(publicJwks, activeMarker); + when(committed.promotion()).thenReturn(promotion); + when(committed.desiredState()).thenReturn(committedState); + when(committed.publicReceipt()).thenReturn(receipt); + when(promotion.targetGeneration()).thenReturn("1"); + when(promotion.targetKid()).thenReturn("key_1"); + when(promotion.targetPublicKeyFingerprint()).thenReturn(publicFingerprint); + when(promotion.publicConfigMapUid()).thenReturn(CONFIG_MAP_UID); + when(promotion.expectedPublicJwksJson()).thenReturn(publicJwks); + when(promotion.expectedActiveMarkerJson()).thenReturn(activeMarker); + when(promotion.activeJwksObservedResourceVersion()).thenReturn(Optional.of("42")); + when(promotion.activeJwksPublicDataDigest()).thenReturn(Optional.of(activeDigest)); + when(receipt.configMapUid()).thenReturn(CONFIG_MAP_UID); + when(receipt.observedResourceVersion()).thenReturn("42"); + when(receipt.publicDataDigest()).thenReturn(activeDigest); + when(desiredStateRepository.readEnrollmentState(eq(accountBinding))) + .thenReturn(Optional.of(committedState)); + when(desiredStateRepository.readCurrentCommittedSigner( + eq(accountBinding), eq(trustFence), eq(API_BINDING_DIGEST), eq("api-r1"))) + .thenReturn(Optional.of(committed)); + + GenerationRequest nextRequest = mock(GenerationRequest.class); + when(nextRequest.phase()).thenReturn(GenerationPhase.GENERATION_RECORDED); + when(nextRequest.operationId()).thenReturn(NEXT_OPERATION_ID); + when(nextRequest.operationDigest()).thenReturn(GENERATION_OPERATION_DIGEST); + when(nextRequest.generationRequestDigest()).thenReturn(GENERATION_REQUEST_DIGEST); + when(nextRequest.generationReceiptDigest()).thenReturn(GENERATION_RECEIPT_DIGEST); + when(nextRequest.desiredStateVersion()).thenReturn(2L); + when(nextRequest.targetGeneration()).thenReturn("2"); + when(nextRequest.targetKid()).thenReturn("key_2"); + when(nextRequest.publicKeyFingerprint()).thenReturn(fingerprint(JWK_2)); + when(nextRequest.expectedActive()).thenReturn(Optional.of(active)); + when(nextRequest.expectedPublishedActive()).thenReturn(Optional.of(active)); + when(desiredStateRepository.readCurrentGenerationRequest(eq(accountBinding), eq(trustFence))) + .thenReturn(nextRequest); + + String nextMarker = + marker(NEXT_OPERATION_ID, "2", "key_2", fingerprint(JWK_2), Optional.of(active)); + PublicationEvidence nextPublication = + publication(JWKS_1_AND_2, nextMarker, "42", "43", "2", "key_2", Optional.of(active)); + when(publicationRepository.readCurrentPublication(eq(accountBinding), eq(trustFence))) + .thenReturn(Optional.of(nextPublication)); + when(configMapClient.observe()) + .thenReturn( + new ConfigMapSnapshot( + CONFIG_MAP_UID, + "43", + Map.of( + AccountJwtJwksPublicationRepository.JWKS_DATA_KEY, + JWKS_1_AND_2, + AccountJwtJwksPublicationRepository.GENERATION_MARKER_DATA_KEY, + nextMarker, + "operator.note", + "preserved"))); + } + + private void replaceNextJwks(String jwks) { + String nextMarker = + marker( + NEXT_OPERATION_ID, + "2", + "key_2", + fingerprint(JWK_2), + Optional.of(new ActiveSigner("1", "key_1"))); + PublicationEvidence nextPublication = + publication( + jwks, + nextMarker, + "42", + "43", + "2", + "key_2", + Optional.of(new ActiveSigner("1", "key_1"))); + when(publicationRepository.readCurrentPublication(eq(accountBinding), eq(trustFence))) + .thenReturn(Optional.of(nextPublication)); + when(configMapClient.observe()) + .thenReturn( + new ConfigMapSnapshot( + CONFIG_MAP_UID, + "43", + Map.of( + AccountJwtJwksPublicationRepository.JWKS_DATA_KEY, + jwks, + AccountJwtJwksPublicationRepository.GENERATION_MARKER_DATA_KEY, + nextMarker, + "operator.note", + "preserved"))); + } + + private PublicationEvidence publication( + String jwks, + String marker, + String expectedResourceVersion, + String observedResourceVersion, + String generation, + String kid, + Optional expectedActive) { + String publicDataDigest = AccountJwtJwksPublicationRepository.publicDataDigest(jwks, marker); + String keyFingerprint = "key_1".equals(kid) ? fingerprint(JWK_1) : fingerprint(JWK_2); + UUID operationId = "1".equals(generation) ? INITIAL_OPERATION_ID : NEXT_OPERATION_ID; + PrepublicationIntent intent = + PrepublicationIntent.create( + operationId, + accountBinding, + GENERATION_OPERATION_DIGEST, + GENERATION_REQUEST_DIGEST, + GENERATION_RECEIPT_DIGEST, + 2L, + trustFence, + API_BINDING_DIGEST, + "api-r1", + AccountJwtJwksPublicationRepository.PUBLIC_JWKS_NAME, + CONFIG_MAP_UID, + expectedResourceVersion, + "4".repeat(64), + generation, + kid, + keyFingerprint, + expectedActive, + expectedActive, + jwks, + marker, + publicDataDigest, + sha256(marker)); + PublicationReceipt receipt = PublicationReceipt.create(intent, observedResourceVersion); + return new PublicationEvidence(intent, Optional.of(receipt), Optional.empty()); + } + + private String marker( + UUID operationId, + String generation, + String kid, + String keyFingerprint, + Optional active) { + String activeJson = activeMarker(active); + return "{\"schemaVersion\":1,\"phase\":\"PREPUBLISHED\",\"operationId\":\"" + + operationId + + "\",\"operationDigest\":\"" + + GENERATION_OPERATION_DIGEST + + "\",\"generationRequestDigest\":\"" + + GENERATION_REQUEST_DIGEST + + "\",\"generationReceiptDigest\":\"" + + GENERATION_RECEIPT_DIGEST + + "\",\"binding\":{\"environmentId\":\"" + + ENVIRONMENT + + "\",\"clusterId\":\"" + + CLUSTER + + "\",\"namespace\":\"" + + NAMESPACE + + "\",\"expectedClusterIncarnationUid\":\"" + + CLUSTER_UID + + "\",\"expectedNamespaceUid\":\"" + + NAMESPACE_UID + + "\",\"trustBindingDigest\":\"" + + binding.bindingDigest() + + "\",\"trustConfigRevision\":\"" + + binding.configRevision() + + "\",\"apiBindingDigest\":\"" + + API_BINDING_DIGEST + + "\",\"apiConfigRevision\":\"api-r1\"},\"publicConfigMap\":{\"name\":\"jwt-jwks\"},\"expectedDurableActive\":" + + activeJson + + ",\"expectedPublishedActive\":" + + activeJson + + ",\"pending\":{\"generation\":\"" + + generation + + "\",\"kid\":\"" + + kid + + "\",\"algorithm\":\"RS256\",\"publicKeyFingerprint\":\"" + + keyFingerprint + + "\"}}"; + } + } + + private static String activeMarker(ActiveSigner active) { + return "{\"generation\":\"" + + active.generation() + + "\",\"kid\":\"" + + active.kid() + + "\",\"present\":true}"; + } + + private static String activeMarker(Optional active) { + return active.map(AccountJwtJwksTrustedSourceTest::activeMarker).orElse("{\"present\":false}"); + } + + private static String fingerprint(String jwk) { + String modulus = jwk.contains("key_1") ? "AQID" : "BAUG"; + String preimage = "{\"e\":\"AQAB\",\"kty\":\"RSA\",\"n\":\"" + modulus + "\"}"; + try { + return java.util.HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256") + .digest(Rfc8785CanonicalJson.canonicalizeUtf8(preimage))); + } catch (Exception unavailable) { + throw new AssertionError(unavailable); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/StartSessionPreAuthorizationReservationTuple.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/StartSessionPreAuthorizationReservationTuple.java new file mode 100644 index 0000000000..aec108b44d --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/StartSessionPreAuthorizationReservationTuple.java @@ -0,0 +1,381 @@ +package net.firedevops.firemud.common.operator; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.text.Normalizer; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import tools.jackson.databind.json.JsonMapper; + +/** + * Immutable shared value and canonical codec for ADR 0048's StartSession {@code + * preAuthorizationReservationTuple/v1}. + * + *

This value describes tuple contents only. Constructing or rehydrating it does not establish + * authenticated actor authority, reservation ownership, a claim, or permission to dispatch. + */ +public final class StartSessionPreAuthorizationReservationTuple { + public static final String TUPLE_SCHEMA_ID = "preAuthorizationReservationTuple"; + public static final String TUPLE_SCHEMA_VERSION = "1"; + public static final int MAX_CONTROL_PLANE_REQUEST_ID_UTF8_BYTES = 128; + private static final int MAX_CANONICAL_TUPLE_UTF8_BYTES = 8 * 1_024; + private static final JsonMapper JSON = JsonMapper.builder().build(); + private static final Set ROOT_FIELDS = + Set.of( + "tupleSchemaId", + "tupleSchemaVersion", + "actionFamilyRequestIdentity", + "actor", + "automationPolicy", + "actionFamily", + "actionFamilySchemaId", + "actionFamilySchemaVersion", + "scope", + "target", + "targetOwner", + "expectedVersion", + "mutation", + "auditReason"); + + private final String controlPlaneRequestId; + private final HumanActor actor; + private final StartSessionOperatorAction action; + + private StartSessionPreAuthorizationReservationTuple( + String controlPlaneRequestId, HumanActor actor, StartSessionOperatorAction action) { + this.controlPlaneRequestId = requireCanonicalControlPlaneRequestId(controlPlaneRequestId); + this.actor = Objects.requireNonNull(actor, "actor is required"); + this.action = Objects.requireNonNull(action, "action is required"); + } + + /** Creates tuple contents from typed values; the actor argument is not authenticated evidence. */ + public static StartSessionPreAuthorizationReservationTuple createHuman( + String controlPlaneRequestId, UUID actorAccountId, StartSessionOperatorAction action) { + return new StartSessionPreAuthorizationReservationTuple( + controlPlaneRequestId, new HumanActor(actorAccountId), action); + } + + /** Rehydrates the exact canonical ADR 0048 tuple value. This does not establish authority. */ + public static StartSessionPreAuthorizationReservationTuple fromCanonicalJson(String json) { + Objects.requireNonNull(json, "tuple JSON is required"); + if (json.getBytes(StandardCharsets.UTF_8).length > MAX_CANONICAL_TUPLE_UTF8_BYTES) { + throw new IllegalArgumentException("pre-authorization tuple exceeds its byte limit"); + } + try { + String canonical = + new String(Rfc8785CanonicalJson.canonicalizeUtf8(json), StandardCharsets.UTF_8); + if (!canonical.equals(json)) { + throw new IllegalArgumentException("pre-authorization tuple is not canonical JSON"); + } + Object decoded = JSON.readValue(json, Map.class); + Map root = requireObject(decoded, "tuple"); + requireExactFields(root, ROOT_FIELDS, "tuple"); + if (!TUPLE_SCHEMA_ID.equals(requireString(root.get("tupleSchemaId"), "tupleSchemaId")) + || !TUPLE_SCHEMA_VERSION.equals( + requireString(root.get("tupleSchemaVersion"), "tupleSchemaVersion"))) { + throw new IllegalArgumentException("unsupported pre-authorization tuple schema"); + } + + Map identity = + requireObject(root.get("actionFamilyRequestIdentity"), "actionFamilyRequestIdentity"); + requireExactFields( + identity, Set.of("requestIdentityKind", "requestId"), "actionFamilyRequestIdentity"); + if (!"controlPlaneRequestId" + .equals(requireString(identity.get("requestIdentityKind"), "requestIdentityKind"))) { + throw new IllegalArgumentException( + "StartSession request identity must be controlPlaneRequestId"); + } + String controlPlaneRequestId = requireString(identity.get("requestId"), "requestId"); + + Map actorObject = requireObject(root.get("actor"), "actor"); + requireExactFields(actorObject, Set.of("kind", "accountId"), "actor"); + if (!"HUMAN".equals(requireString(actorObject.get("kind"), "actor.kind"))) { + throw new IllegalArgumentException("StartSession reservation actor must be human"); + } + HumanActor actor = + new HumanActor(requireCanonicalUuid(actorObject.get("accountId"), "actor.accountId")); + + Map automation = + requireObject(root.get("automationPolicy"), "automationPolicy"); + requireExactFields(automation, Set.of("presence"), "automationPolicy"); + if (!"ABSENT" + .equals(requireString(automation.get("presence"), "automationPolicy.presence"))) { + throw new IllegalArgumentException( + "human StartSession tuple must explicitly omit automation policy"); + } + + String actionFamily = requireString(root.get("actionFamily"), "actionFamily"); + String schemaId = requireString(root.get("actionFamilySchemaId"), "actionFamilySchemaId"); + String schemaVersion = + requireString(root.get("actionFamilySchemaVersion"), "actionFamilySchemaVersion"); + if (!StartSessionOperatorAction.ACTION_FAMILY.equals(actionFamily) + || !StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID.equals(schemaId) + || !StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION.equals(schemaVersion)) { + throw new IllegalArgumentException("unsupported StartSession action-family schema"); + } + + Map scopeObject = requireObject(root.get("scope"), "scope"); + requireExactFields(scopeObject, Set.of("tenantId", "targetNamespace"), "scope"); + StartSessionOperatorAction.Scope scope = + new StartSessionOperatorAction.Scope( + requireCanonicalUuid(scopeObject.get("tenantId"), "scope.tenantId"), + requireString(scopeObject.get("targetNamespace"), "scope.targetNamespace")); + + Map targetObject = requireObject(root.get("target"), "target"); + requireExactFields(targetObject, Set.of("gameTemplateId", "ownerAccountId"), "target"); + StartSessionOperatorAction.Target target = + new StartSessionOperatorAction.Target( + requirePositiveCanonicalLong(targetObject.get("gameTemplateId")), + requireCanonicalUuid(targetObject.get("ownerAccountId"), "target.ownerAccountId")); + + Map ownerObject = requireObject(root.get("targetOwner"), "targetOwner"); + requireExactFields(ownerObject, Set.of("ownerService"), "targetOwner"); + if (!StartSessionOperatorAction.OWNER_SERVICE.equals( + requireString(ownerObject.get("ownerService"), "targetOwner.ownerService"))) { + throw new IllegalArgumentException("StartSession targetOwner is immutable and unsupported"); + } + + Map expectedVersion = + requireObject(root.get("expectedVersion"), "expectedVersion"); + requireExactFields(expectedVersion, Set.of("presence"), "expectedVersion"); + if (!"ABSENT" + .equals(requireString(expectedVersion.get("presence"), "expectedVersion.presence"))) { + throw new IllegalArgumentException( + "StartSession expectedVersion must be explicitly absent"); + } + + Map mutationObject = requireObject(root.get("mutation"), "mutation"); + requireExactFields(mutationObject, Set.of("clientIp"), "mutation"); + Map clientIpObject = + requireObject(mutationObject.get("clientIp"), "mutation.clientIp"); + String clientIpPresence = + requireString(clientIpObject.get("presence"), "mutation.clientIp.presence"); + StartSessionOperatorAction.ClientIp clientIp; + if ("ABSENT".equals(clientIpPresence)) { + requireExactFields(clientIpObject, Set.of("presence"), "mutation.clientIp"); + clientIp = StartSessionOperatorAction.ClientIp.absent(); + } else if ("PRESENT".equals(clientIpPresence)) { + requireExactFields(clientIpObject, Set.of("presence", "value"), "mutation.clientIp"); + clientIp = + StartSessionOperatorAction.ClientIp.of( + requireString(clientIpObject.get("value"), "mutation.clientIp.value")); + } else { + throw new IllegalArgumentException("mutation.clientIp presence must be ABSENT or PRESENT"); + } + + StartSessionOperatorAction action = + new StartSessionOperatorAction( + schemaId, + schemaVersion, + scope, + target, + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation(clientIp), + requireString(root.get("auditReason"), "auditReason")); + StartSessionPreAuthorizationReservationTuple tuple = + new StartSessionPreAuthorizationReservationTuple(controlPlaneRequestId, actor, action); + if (!tuple.canonicalJson().equals(json)) { + throw new IllegalArgumentException("pre-authorization tuple shape is not canonical"); + } + return tuple; + } catch (IOException exception) { + throw new IllegalArgumentException("pre-authorization tuple JSON is invalid", exception); + } + } + + public String actionFamily() { + return action.actionFamily(); + } + + public String controlPlaneRequestId() { + return controlPlaneRequestId; + } + + public HumanActor actor() { + return actor; + } + + public NoAutomationPolicy automationPolicy() { + return NoAutomationPolicy.ABSENT; + } + + public StartSessionOperatorAction action() { + return action; + } + + /** Validate a stable request key without silently normalizing or changing its identity. */ + public static String requireCanonicalControlPlaneRequestId(String value) { + Objects.requireNonNull(value, "controlPlaneRequestId is required"); + if (!Normalizer.isNormalized(value, Normalizer.Form.NFC)) { + throw new IllegalArgumentException("controlPlaneRequestId must already be NFC-normalized"); + } + return requireBoundedText(value, "controlPlaneRequestId"); + } + + public String targetOwner() { + return action.targetOwner(); + } + + /** Returns ADR 0047's digest over the seven action-schema grammar fields. */ + public String mutationDigest() { + return StartSessionOperatorActionCodec.mutationDigest(action); + } + + /** Returns the complete canonical typed tuple, including explicit absence values. */ + public String canonicalJson() { + Map scope = + Map.of( + "tenantId", action.scope().tenantId().toString(), + "targetNamespace", action.scope().targetNamespace()); + Map target = + Map.of( + "gameTemplateId", Long.toString(action.target().gameTemplateId()), + "ownerAccountId", action.target().ownerAccountId().toString()); + Map clientIp = + action.mutation().clientIp() instanceof StartSessionOperatorAction.AbsentClientIp + ? Map.of("presence", "ABSENT") + : Map.of( + "presence", + "PRESENT", + "value", + ((StartSessionOperatorAction.StringClientIp) action.mutation().clientIp()).value()); + Map root = new LinkedHashMap<>(); + root.put("tupleSchemaId", TUPLE_SCHEMA_ID); + root.put("tupleSchemaVersion", TUPLE_SCHEMA_VERSION); + root.put( + "actionFamilyRequestIdentity", + Map.of("requestIdentityKind", "controlPlaneRequestId", "requestId", controlPlaneRequestId)); + root.put("actor", Map.of("kind", "HUMAN", "accountId", actor.accountId().toString())); + root.put("automationPolicy", Map.of("presence", automationPolicy().name())); + root.put("actionFamily", action.actionFamily()); + root.put("actionFamilySchemaId", action.actionFamilySchemaId()); + root.put("actionFamilySchemaVersion", action.actionFamilySchemaVersion()); + root.put("scope", scope); + root.put("target", target); + root.put("targetOwner", Map.of("ownerService", action.targetOwner())); + root.put("expectedVersion", Map.of("presence", action.expectedVersion().name())); + root.put("mutation", Map.of("clientIp", clientIp)); + root.put("auditReason", action.auditReason()); + try { + return new String( + Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(root)), + StandardCharsets.UTF_8); + } catch (IOException exception) { + throw new IllegalStateException("could not encode StartSession reservation tuple", exception); + } + } + + public record HumanActor(UUID accountId) { + public HumanActor { + Objects.requireNonNull(accountId, "actor accountId is required"); + if (accountId.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException("actor accountId must not be nil"); + } + } + } + + public enum NoAutomationPolicy { + ABSENT + } + + @Override + public boolean equals(Object other) { + if (this == other) { + return true; + } + if (!(other instanceof StartSessionPreAuthorizationReservationTuple that)) { + return false; + } + return controlPlaneRequestId.equals(that.controlPlaneRequestId) + && actor.equals(that.actor) + && action.equals(that.action); + } + + @Override + public int hashCode() { + return Objects.hash(controlPlaneRequestId, actor, action); + } + + private static String requireBoundedText(String value, String fieldName) { + Objects.requireNonNull(value, fieldName + " is required"); + String normalized = Normalizer.normalize(value, Normalizer.Form.NFC); + if (normalized.isBlank() + || normalized.codePoints().anyMatch(Character::isISOControl) + || normalized.getBytes(StandardCharsets.UTF_8).length + > MAX_CONTROL_PLANE_REQUEST_ID_UTF8_BYTES) { + throw new IllegalArgumentException(fieldName + " is blank or exceeds its bound"); + } + for (int index = 0; index < normalized.length(); index++) { + char current = normalized.charAt(index); + if (Character.isHighSurrogate(current)) { + if (index + 1 >= normalized.length() + || !Character.isLowSurrogate(normalized.charAt(index + 1))) { + throw new IllegalArgumentException(fieldName + " contains malformed Unicode"); + } + index++; + } else if (Character.isLowSurrogate(current)) { + throw new IllegalArgumentException(fieldName + " contains malformed Unicode"); + } + } + return normalized; + } + + private static UUID requireCanonicalUuid(Object value, String fieldName) { + String text = requireString(value, fieldName); + UUID parsed; + try { + parsed = UUID.fromString(text); + } catch (IllegalArgumentException exception) { + throw new IllegalArgumentException(fieldName + " must be a canonical UUID", exception); + } + if (!parsed.toString().equals(text) || parsed.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException(fieldName + " must be a canonical non-nil UUID"); + } + return parsed; + } + + private static long requirePositiveCanonicalLong(Object value) { + String text = requireString(value, "target.gameTemplateId"); + if (!text.matches("[1-9][0-9]*")) { + throw new IllegalArgumentException( + "target.gameTemplateId must be a positive canonical integer"); + } + try { + return Long.parseLong(text); + } catch (NumberFormatException exception) { + throw new IllegalArgumentException( + "target.gameTemplateId exceeds its supported range", exception); + } + } + + private static String requireString(Object value, String fieldName) { + if (!(value instanceof String text)) { + throw new IllegalArgumentException(fieldName + " must be a string"); + } + return text; + } + + @SuppressWarnings("unchecked") + private static Map requireObject(Object value, String fieldName) { + if (!(value instanceof Map map)) { + throw new IllegalArgumentException(fieldName + " must be an object"); + } + for (Object key : map.keySet()) { + if (!(key instanceof String)) { + throw new IllegalArgumentException(fieldName + " contains a non-string field name"); + } + } + return (Map) map; + } + + private static void requireExactFields( + Map object, Set expectedFields, String fieldName) { + if (!object.keySet().equals(expectedFields)) { + throw new IllegalArgumentException(fieldName + " has missing or unsupported fields"); + } + } +} diff --git a/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/operator/StartSessionPreAuthorizationReservationTupleTest.java b/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/operator/StartSessionPreAuthorizationReservationTupleTest.java new file mode 100644 index 0000000000..3f881b6d5e --- /dev/null +++ b/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/operator/StartSessionPreAuthorizationReservationTupleTest.java @@ -0,0 +1,134 @@ +package net.firedevops.firemud.common.operator; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.util.UUID; +import org.junit.jupiter.api.Test; + +class StartSessionPreAuthorizationReservationTupleTest { + private static final UUID TENANT_ID = UUID.fromString("9f8f06b4-36e5-4d11-9c2a-5adfd7f41531"); + private static final UUID ACTOR_ID = UUID.fromString("a4f5f4eb-8243-4d42-903a-33495456a622"); + private static final UUID OTHER_ACTOR_ID = + UUID.fromString("a44b728e-b58f-4fc1-a891-7644baef6ddc"); + private static final UUID OWNER_ACCOUNT_ID = + UUID.fromString("36aa9ce5-0ebc-4c14-9f6b-d160edc6059a"); + + @Test + void canonicalBytesMatchThePreAuthorizationReservationTupleV1Encoding() { + StartSessionPreAuthorizationReservationTuple tuple = + StartSessionPreAuthorizationReservationTuple.createHuman( + "tuple-contract-01", ACTOR_ID, action(StartSessionOperatorAction.ClientIp.absent())); + String expected = + "{\"actionFamily\":\"StartSession\"," + + "\"actionFamilyRequestIdentity\":{\"requestId\":\"tuple-contract-01\"," + + "\"requestIdentityKind\":\"controlPlaneRequestId\"}," + + "\"actionFamilySchemaId\":\"firemud.game-session.start-session\"," + + "\"actionFamilySchemaVersion\":\"1\"," + + "\"actor\":{\"accountId\":\"a4f5f4eb-8243-4d42-903a-33495456a622\"," + + "\"kind\":\"HUMAN\"}," + + "\"auditReason\":\"tuple codec contract\"," + + "\"automationPolicy\":{\"presence\":\"ABSENT\"}," + + "\"expectedVersion\":{\"presence\":\"ABSENT\"}," + + "\"mutation\":{\"clientIp\":{\"presence\":\"ABSENT\"}}," + + "\"scope\":{\"targetNamespace\":\"world-runtime\"," + + "\"tenantId\":\"9f8f06b4-36e5-4d11-9c2a-5adfd7f41531\"}," + + "\"target\":{\"gameTemplateId\":\"91\"," + + "\"ownerAccountId\":\"36aa9ce5-0ebc-4c14-9f6b-d160edc6059a\"}," + + "\"targetOwner\":{\"ownerService\":\"game-session-service\"}," + + "\"tupleSchemaId\":\"preAuthorizationReservationTuple\"," + + "\"tupleSchemaVersion\":\"1\"}"; + + assertThat(tuple.canonicalJson().getBytes(StandardCharsets.UTF_8)) + .containsExactly(expected.getBytes(StandardCharsets.UTF_8)); + assertThat( + StartSessionPreAuthorizationReservationTuple.fromCanonicalJson(expected) + .canonicalJson() + .getBytes(StandardCharsets.UTF_8)) + .containsExactly(expected.getBytes(StandardCharsets.UTF_8)); + assertThat(tuple.mutationDigest()) + .isEqualTo(StartSessionOperatorActionCodec.mutationDigest(tuple.action())); + } + + @Test + void roundTripsTypedContentsAndSameRequestIdWithDifferentActorIsAConflict() { + StartSessionOperatorAction action = + action(StartSessionOperatorAction.ClientIp.of("203.0.113.8")); + StartSessionPreAuthorizationReservationTuple original = + StartSessionPreAuthorizationReservationTuple.createHuman( + "tuple-conflict-01", ACTOR_ID, action); + StartSessionPreAuthorizationReservationTuple rehydrated = + StartSessionPreAuthorizationReservationTuple.fromCanonicalJson(original.canonicalJson()); + StartSessionPreAuthorizationReservationTuple changedActor = + StartSessionPreAuthorizationReservationTuple.createHuman( + "tuple-conflict-01", OTHER_ACTOR_ID, action); + + assertThat(rehydrated).isEqualTo(original); + assertThat(rehydrated.canonicalJson()).isEqualTo(original.canonicalJson()); + assertThat(rehydrated.mutationDigest()).isEqualTo(original.mutationDigest()); + assertThat(changedActor.controlPlaneRequestId()).isEqualTo(original.controlPlaneRequestId()); + assertThat(changedActor).isNotEqualTo(original); + assertThat(changedActor.canonicalJson()).isNotEqualTo(original.canonicalJson()); + // The action digest excludes reservation identity and actor; it cannot replace tuple + // comparison. + assertThat(changedActor.mutationDigest()).isEqualTo(original.mutationDigest()); + assertThat(original.canonicalJson()) + .contains("\"clientIp\":{\"presence\":\"PRESENT\",\"value\":\"203.0.113.8\"}"); + } + + @Test + void strictDecoderRejectsNoncanonicalAndUnsupportedTupleShapes() { + StartSessionPreAuthorizationReservationTuple tuple = + StartSessionPreAuthorizationReservationTuple.createHuman( + "tuple-strict-01", ACTOR_ID, action(StartSessionOperatorAction.ClientIp.absent())); + String json = tuple.canonicalJson(); + String withUnknownRootField = + json.replace( + "\"tupleSchemaVersion\":\"1\"}", "\"tupleSchemaVersion\":\"1\",\"unexpected\":true}"); + String missingTargetOwner = + json.replace(",\"targetOwner\":{\"ownerService\":\"game-session-service\"}", ""); + String invalidExpectedVersion = + json.replace( + "\"expectedVersion\":{\"presence\":\"ABSENT\"}", + "\"expectedVersion\":{\"presence\":\"PRESENT\"}"); + String invalidActorKind = json.replace("\"kind\":\"HUMAN\"", "\"kind\":\"WORKLOAD\""); + + assertThatThrownBy( + () -> StartSessionPreAuthorizationReservationTuple.fromCanonicalJson(" " + json)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("canonical JSON"); + assertThatThrownBy( + () -> + StartSessionPreAuthorizationReservationTuple.fromCanonicalJson( + withUnknownRootField)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("unsupported fields"); + assertThatThrownBy( + () -> + StartSessionPreAuthorizationReservationTuple.fromCanonicalJson(missingTargetOwner)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("unsupported fields"); + assertThatThrownBy( + () -> + StartSessionPreAuthorizationReservationTuple.fromCanonicalJson( + invalidExpectedVersion)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("expectedVersion"); + assertThatThrownBy( + () -> StartSessionPreAuthorizationReservationTuple.fromCanonicalJson(invalidActorKind)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("actor must be human"); + } + + private static StartSessionOperatorAction action(StartSessionOperatorAction.ClientIp clientIp) { + return new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(TENANT_ID, "world-runtime"), + new StartSessionOperatorAction.Target(91L, OWNER_ACCOUNT_ID), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation(clientIp), + "tuple codec contract"); + } +} diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/security/ControlUiJwtProfileValidator.java b/services/common-security/src/main/java/net/firedevops/firemud/common/security/ControlUiJwtProfileValidator.java new file mode 100644 index 0000000000..6fdfb4fc5e --- /dev/null +++ b/services/common-security/src/main/java/net/firedevops/firemud/common/security/ControlUiJwtProfileValidator.java @@ -0,0 +1,102 @@ +package net.firedevops.firemud.common.security; + +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** Validates the canonical claim shape of the registry-backed control-ui JWT profile. */ +public final class ControlUiJwtProfileValidator { + public static final String PROFILE = "control-ui"; + public static final String AUDIENCE = "control-ui"; + public static final String TOKEN_TYPE = "control-ui"; + private static final String ISSUER = "firemud-account-service"; + public static final Set REQUIRED_CLAIMS; + public static final Set OPTIONAL_CLAIMS = Set.of("globalRoles"); + + static { + Set required = + new java.util.HashSet<>(AccountJwtProfileClaimSupport.REQUIRED_BASE_CLAIMS); + required.add("scopedRoles"); + REQUIRED_CLAIMS = Set.copyOf(required); + } + + private ControlUiJwtProfileValidator() {} + + /** + * Checks claim shape only; it does not validate a registry record or current Account authority. + * + * @param claims immutable verified claims + * @param maxControlUiTenantScopes explicit finite profile cap for every applicable tenant map + */ + public static void validateClaims(Map claims, int maxControlUiTenantScopes) { + if (maxControlUiTenantScopes <= 0 + || maxControlUiTenantScopes + > GameSessionAccountDelegationProfile.MAX_AUTHORITY_TUPLE_BYTES) { + throw AccountJwtProfileClaimSupport.invalid(); + } + AccountJwtProfileClaimSupport.requireClaimFields(claims, REQUIRED_CLAIMS, OPTIONAL_CLAIMS); + AccountJwtProfileClaimSupport.requireCommonIdentity(claims, ISSUER, AUDIENCE); + + Map tuple = + AccountJwtProfileClaimSupport.requireAuthorityTuple( + claims.get("authorityTuple"), true, false, false); + if (!(tuple.get("privateRealmGrantVersions") instanceof List grants) || !grants.isEmpty()) { + throw AccountJwtProfileClaimSupport.invalid(); + } + Map tenantGenerations = + AccountJwtProfileClaimSupport.requireGenerationMap(tuple.get("tenantAuthorityGeneration")); + Map membershipGenerations = + AccountJwtProfileClaimSupport.requireGenerationMap( + tuple.get("membershipAuthorityGeneration")); + Map membershipVersions = + AccountJwtProfileClaimSupport.requireVersionMap(claims.get("membershipVersion")); + String accountId = (String) claims.get("accountId"); + // The canonical profile forbids an accountId as a tenant-map key; this is shape rejection, + // not evidence about tenant ownership or an authorization predicate. + if (!membershipGenerations.keySet().equals(membershipVersions.keySet()) + || tenantGenerations.containsKey(accountId) + || membershipGenerations.containsKey(accountId) + || membershipVersions.containsKey(accountId)) { + throw AccountJwtProfileClaimSupport.invalid(); + } + + Map scopedRoles = + AccountJwtProfileClaimSupport.requireObjectMap(claims.get("scopedRoles")); + scopedRoles.forEach( + (tenantId, roles) -> { + AccountJwtProfileClaimSupport.requireUuid(tenantId); + AccountJwtProfileClaimSupport.requireRoleList(roles); + if (((List) roles).isEmpty() || tenantId.equals(claims.get("accountId"))) { + throw AccountJwtProfileClaimSupport.invalid(); + } + }); + if (!scopedRoles.keySet().containsAll(tenantGenerations.keySet())) { + throw AccountJwtProfileClaimSupport.invalid(); + } + + requireAtMost(scopedRoles.size(), maxControlUiTenantScopes); + requireAtMost(tenantGenerations.size(), maxControlUiTenantScopes); + requireAtMost(membershipGenerations.size(), maxControlUiTenantScopes); + requireAtMost(membershipVersions.size(), maxControlUiTenantScopes); + + Object billingCutoff = tuple.get("tenantBillingCutoff"); + if (billingCutoff != null) { + Map billingCutoffs = + AccountJwtProfileClaimSupport.requireObjectMap(billingCutoff); + requireAtMost(billingCutoffs.size(), maxControlUiTenantScopes); + if (!scopedRoles.keySet().containsAll(billingCutoffs.keySet())) { + throw AccountJwtProfileClaimSupport.invalid(); + } + } + if (claims.containsKey("globalRoles")) { + AccountJwtProfileClaimSupport.requireRoleList(claims.get("globalRoles")); + } + } + + private static void requireAtMost(int entries, int maximum) { + if (entries > maximum) { + throw AccountJwtProfileClaimSupport.invalid(); + } + } +} + diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/security/GameSessionAccountDelegationRegistryRecord.java b/services/common-security/src/main/java/net/firedevops/firemud/common/security/GameSessionAccountDelegationRegistryRecord.java new file mode 100644 index 0000000000..d75869b238 --- /dev/null +++ b/services/common-security/src/main/java/net/firedevops/firemud/common/security/GameSessionAccountDelegationRegistryRecord.java @@ -0,0 +1,891 @@ +package net.firedevops.firemud.common.security; + +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.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Arrays; +import java.util.Base64; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.core.type.TypeReference; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.json.JsonMapper; + +/** + * Strict finite-bounded codec for initial and distinct public-production bound delegation + * candidates. + * + *

Pending records are non-authorizing. This codec checks JOSE/claim shape and exact Account + * snapshot equality, but does not verify the JWS signature or establish signer/currentness proof. + * The signing and Account evidence owners must do that before any active transition is usable. + */ +public final class GameSessionAccountDelegationRegistryRecord { + private static final int SCHEMA_VERSION = 2; + private static final int PENDING_REGISTRY_VERSION = 1; + private static final int ACTIVE_REGISTRY_VERSION = 2; + private static final String PENDING = "pending"; + private static final String ACTIVE = "active"; + private static final Pattern HASH = Pattern.compile("[0-9a-f]{64}"); + private static final Pattern POSITIVE_DECIMAL = Pattern.compile("[1-9][0-9]{0,18}"); + private static final Pattern POSITIVE_LINEARIZATION = Pattern.compile("[1-9][0-9]{0,19}"); + private static final Pattern KID = Pattern.compile("[A-Za-z0-9_-]{1,64}"); + private static final Set TOKEN_CLAIMS = + Set.of( + "iss", + "sub", + "jti", + "accountId", + "aud", + "iat", + "nbf", + "exp", + "tokenGeneration", + "authorityTuple", + "membershipVersion", + "issuanceFence"); + private static final Set HEADER_REQUIRED = Set.of("alg", "kid"); + private static final Set HEADER_ALLOWED = Set.of("alg", "kid", "typ"); + private static final Set RECORD_FIELDS = + Set.of( + "schemaVersion", + "registryVersion", + "tokenHash", + "kid", + "signerGeneration", + "accountId", + "issuer", + "profile", + "type", + "audience", + "jti", + "iat", + "nbf", + "exp", + "tokenGeneration", + "operationId", + "requestId", + "requestDigest", + "state", + "authorityTuple", + "membershipVersion", + "issuanceFence", + "authoritySourceVersions", + "authEvidenceBundle"); + private static final Set AUTHORITY_TUPLE_FIELDS = + Set.of( + "issuerAuthGeneration", + "accountAuthorityGeneration", + "tenantAuthorityGeneration", + "membershipAuthorityGeneration", + "privateRealmGrantVersions"); + private static final Set AUTHORITY_TUPLE_FIELDS_WITH_ACCOUNT_CUTOFF = + Set.of( + "issuerAuthGeneration", + "accountAuthorityGeneration", + "tenantAuthorityGeneration", + "membershipAuthorityGeneration", + "privateRealmGrantVersions", + "accountSecurityCutoff"); + private static final Set ACCOUNT_SECURITY_CUTOFF_FIELDS = + Set.of("accountAuthorityGeneration", "outboxStreamKey", "outboxSequence"); + private static final Set SOURCE_VERSION_FIELDS = + Set.of("issuerSourceVersion", "accountSourceVersion", "issuanceFenceSourceVersion"); + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + private final Map fields; + + private GameSessionAccountDelegationRegistryRecord(Map fields) { + this.fields = immutableMap(fields); + } + + /** Creates the distinct first public-production tenant-bound pending record. */ + public static GameSessionAccountDelegationRegistryRecord fromAccountSignedBoundCompactJwt( + String compactJwt, + String signerGeneration, + IssuanceBinding binding, + AccountAuthoritySnapshot account, + EvidenceBundleReference evidence, + String tenantId, + Map exactTuple, + Map exactMembershipVersion, + long now, + long maxBytes) { + GameSessionAccountDelegationProfile.requirePublicTenantBoundAuthority( + tenantId, exactTuple, exactMembershipVersion); + return fromCandidate( + compactJwt, + signerGeneration, + binding, + account, + evidence, + now, + maxBytes, + new BoundShape(tenantId, exactTuple, exactMembershipVersion)); + } + + private record BoundShape( + String tenantId, Map tuple, Map membershipVersion) {} + + /** Validates the exact signed-token candidate and creates only its pending registry record. */ + public static GameSessionAccountDelegationRegistryRecord fromAccountSignedCompactJwt( + String compactJwt, + String signerGeneration, + IssuanceBinding binding, + AccountAuthoritySnapshot snapshot, + EvidenceBundleReference evidenceBundleReference, + long nowEpochSecond, + long maxRecordBytes) { + return fromCandidate( + compactJwt, + signerGeneration, + binding, + snapshot, + evidenceBundleReference, + nowEpochSecond, + maxRecordBytes, + null); + } + + private static GameSessionAccountDelegationRegistryRecord fromCandidate( + String compactJwt, + String signerGeneration, + IssuanceBinding binding, + AccountAuthoritySnapshot snapshot, + EvidenceBundleReference evidenceBundleReference, + long nowEpochSecond, + long maxRecordBytes, + BoundShape bound) { + Objects.requireNonNull(compactJwt, "Compact Account JWT is required"); + Objects.requireNonNull(binding, "Durable issuance binding is required"); + Objects.requireNonNull(snapshot, "Locked Account authority snapshot is required"); + Objects.requireNonNull( + evidenceBundleReference, "Persisted Account evidence bundle is required"); + requirePositiveDecimal(signerGeneration, "signerGeneration"); + requirePositive(nowEpochSecond, "nowEpochSecond"); + requireBound( + maxRecordBytes, + GameSessionAccountDelegationProfile.MAX_REGISTRY_RECORD_BYTES, + "maxRecordBytes"); + + CompactToken compact = parseCompactJwt(compactJwt); + Map claims = compact.claims(); + requireExactFields(claims, fieldsFor(TOKEN_CLAIMS, bound != null), "JWT claims"); + String issuer = requireText(claims.get("iss"), "iss", 256); + String subject = requireCanonicalUuid(claims.get("sub"), "sub"); + String accountId = requireCanonicalUuid(claims.get("accountId"), "accountId"); + String jti = requireCanonicalUuid(claims.get("jti"), "jti"); + String audience = requireText(claims.get("aud"), "aud", 128); + long issuedAt = requirePositiveInteger(claims.get("iat"), "iat"); + long notBefore = requirePositiveInteger(claims.get("nbf"), "nbf"); + long expiresAt = requirePositiveInteger(claims.get("exp"), "exp"); + String tokenGeneration = + requirePositiveDecimal(claims.get("tokenGeneration"), "tokenGeneration"); + String issuanceFence = requirePositiveDecimal(claims.get("issuanceFence"), "issuanceFence"); + + requireEqual(GameSessionAccountDelegationProfile.ISSUER, issuer, "Account issuer mismatch"); + requireEqual(GameSessionAccountDelegationProfile.AUDIENCE, audience, "audience mismatch"); + requireEqual(snapshot.accountId().toString(), accountId, "Account UUID mismatch"); + requireEqual(subject, accountId, "sub and accountId mismatch"); + requireEqual(binding.accountId(), accountId, "durable operation account mismatch"); + requireEqual("1", tokenGeneration, "initial delegation tokenGeneration must be one"); + requireEqual( + Long.toString(snapshot.issuanceFence()), issuanceFence, "Account issuance fence mismatch"); + validateTimeWindow(issuedAt, notBefore, expiresAt, nowEpochSecond); + if (bound == null) { + validateAuthorityTuple( + claims.get("authorityTuple"), claims.get("membershipVersion"), snapshot); + } else { + GameSessionAccountDelegationJwtProfileValidator.validatePublicTenantBoundClaims(claims); + requireEqual(bound.tenantId(), claims.get("tenantId"), "bound tenant mismatch"); + requireEqual(bound.tuple(), claims.get("authorityTuple"), "bound tuple mismatch"); + requireEqual( + bound.membershipVersion(), + claims.get("membershipVersion"), + "independent membership version mismatch"); + requireEqual( + Long.toString(snapshot.issuerGeneration()), + bound.tuple().get("issuerAuthGeneration"), + "issuer mismatch"); + requireEqual( + Long.toString(snapshot.accountGeneration()), + bound.tuple().get("accountAuthorityGeneration"), + "account mismatch"); + if (!Objects.equals( + snapshot.accountSecurityCutoff().map(value -> value.toMap()).orElse(null), + bound.tuple().get("accountSecurityCutoff"))) throw invalid("Account cutoff mismatch"); + } + + Map record = new LinkedHashMap<>(); + record.put("schemaVersion", SCHEMA_VERSION); + record.put("registryVersion", PENDING_REGISTRY_VERSION); + record.put("tokenHash", sha256(compactJwt.getBytes(StandardCharsets.US_ASCII))); + record.put("kid", compact.keyId()); + record.put("signerGeneration", signerGeneration); + record.put("accountId", accountId); + if (bound != null) record.put("tenantId", bound.tenantId()); + record.put("issuer", issuer); + record.put("profile", GameSessionAccountDelegationProfile.PROFILE); + record.put("type", GameSessionAccountDelegationProfile.TYPE); + record.put("audience", audience); + record.put("jti", jti); + record.put("iat", issuedAt); + record.put("nbf", notBefore); + record.put("exp", expiresAt); + record.put("tokenGeneration", tokenGeneration); + record.put("operationId", binding.operationId()); + record.put("requestId", binding.requestId()); + record.put("requestDigest", binding.requestDigest()); + record.put("state", PENDING); + record.put("authorityTuple", claims.get("authorityTuple")); + record.put("membershipVersion", claims.get("membershipVersion")); + record.put("issuanceFence", issuanceFence); + record.put("authoritySourceVersions", snapshot.sourceVersions()); + record.put("authEvidenceBundle", evidenceBundleReference.toMap()); + + GameSessionAccountDelegationRegistryRecord result = + new GameSessionAccountDelegationRegistryRecord(record); + result.toCanonicalJsonBytes(maxRecordBytes); + return result; + } + + /** Decodes a supported canonical registry value without granting it authority. */ + public static GameSessionAccountDelegationRegistryRecord decode( + byte[] canonicalUtf8, long maxRecordBytes) { + Objects.requireNonNull(canonicalUtf8, "Registry bytes are required"); + requireBound( + maxRecordBytes, + GameSessionAccountDelegationProfile.MAX_REGISTRY_RECORD_BYTES, + "maxRecordBytes"); + if (canonicalUtf8.length == 0 || canonicalUtf8.length > maxRecordBytes) { + throw invalid("Registry record exceeds its byte bound"); + } + String json = strictUtf8(canonicalUtf8); + byte[] canonical = canonicalize(json); + if (!Arrays.equals(canonicalUtf8, canonical)) { + throw invalid("Registry value is not canonical RFC 8785 UTF-8"); + } + Map decoded = parseObject(json, "registry record"); + requireExactFields( + decoded, fieldsFor(RECORD_FIELDS, decoded.containsKey("tenantId")), "registry record"); + validateRecord(decoded); + return new GameSessionAccountDelegationRegistryRecord(decoded); + } + + /** Returns canonical RFC 8785 record bytes, subject to both the caller and profile ceilings. */ + public byte[] toCanonicalJsonBytes(long maxRecordBytes) { + requireBound( + maxRecordBytes, + GameSessionAccountDelegationProfile.MAX_REGISTRY_RECORD_BYTES, + "maxRecordBytes"); + byte[] canonical = canonicalize(serialize(fields)); + if (canonical.length == 0 || canonical.length > maxRecordBytes) { + throw invalid("Registry record exceeds its byte bound"); + } + return canonical; + } + + public String tokenHash() { + return textField("tokenHash"); + } + + public String kid() { + return textField("kid"); + } + + public String signerGeneration() { + return textField("signerGeneration"); + } + + public String accountId() { + return textField("accountId"); + } + + public String jti() { + return textField("jti"); + } + + public String operationId() { + return textField("operationId"); + } + + public String requestId() { + return textField("requestId"); + } + + public String requestDigest() { + return textField("requestDigest"); + } + + public String state() { + return textField("state"); + } + + public long issuedAtEpochSecond() { + return requirePositiveInteger(fields.get("iat"), "iat"); + } + + public long notBeforeEpochSecond() { + return requirePositiveInteger(fields.get("nbf"), "nbf"); + } + + public long issuanceFence() { + return requirePositiveDecimalLong(fields.get("issuanceFence"), "issuanceFence"); + } + + public long registryVersion() { + return requirePositiveInteger(fields.get("registryVersion"), "registryVersion"); + } + + public EvidenceBundleReference evidenceBundleReference() { + Map value = + requireObject(fields.get("authEvidenceBundle"), "authEvidenceBundle"); + return new EvidenceBundleReference( + requirePositiveDecimal(value.get("bundleVersion"), "bundleVersion"), + requirePositiveDecimal(value.get("sourceVersion"), "sourceVersion"), + requirePositiveDecimal(value.get("sourceFence"), "sourceFence"), + requirePositiveLinearization(value.get("linearization")), + requireMatchValue(HASH, value.get("canonicalSha256"), "canonicalSha256")); + } + + public long expiresAtEpochSecond() { + return requirePositiveInteger(fields.get("exp"), "exp"); + } + + public Map fields() { + return immutableMap(fields); + } + + private String textField(String field) { + return requireText(fields.get(field), field, 256); + } + + private static Set fieldsFor(Set initial, boolean bound) { + if (!bound) return initial; + var fields = new java.util.HashSet<>(initial); + fields.add("tenantId"); + return Set.copyOf(fields); + } + + private static void validateRecord(Map record) { + requireExactInteger(record.get("schemaVersion"), SCHEMA_VERSION, "schemaVersion"); + long registryVersion = requirePositiveInteger(record.get("registryVersion"), "registryVersion"); + String state = requireText(record.get("state"), "state", 16); + if (PENDING.equals(state)) { + if (registryVersion != PENDING_REGISTRY_VERSION) { + throw invalid("pending registry version mismatch"); + } + } else if (ACTIVE.equals(state)) { + if (registryVersion != ACTIVE_REGISTRY_VERSION) { + throw invalid("active registry version mismatch"); + } + } else { + throw invalid("Unsupported registry lifecycle state"); + } + requireMatch(HASH, record.get("tokenHash"), "tokenHash"); + requireMatch(HASH, record.get("requestDigest"), "requestDigest"); + requireCanonicalUuid(record.get("jti"), "jti"); + requireCanonicalUuid(record.get("operationId"), "operationId"); + requireCanonicalUuid(record.get("requestId"), "requestId"); + requireMatch(KID, record.get("kid"), "kid"); + requirePositiveDecimal(record.get("signerGeneration"), "signerGeneration"); + requireEqual(GameSessionAccountDelegationProfile.ISSUER, record.get("issuer"), "issuer"); + requireEqual(GameSessionAccountDelegationProfile.PROFILE, record.get("profile"), "profile"); + requireEqual(GameSessionAccountDelegationProfile.TYPE, record.get("type"), "type"); + requireEqual(GameSessionAccountDelegationProfile.AUDIENCE, record.get("audience"), "audience"); + String accountId = requireCanonicalUuid(record.get("accountId"), "accountId"); + long issuedAt = requirePositiveInteger(record.get("iat"), "iat"); + long notBefore = requirePositiveInteger(record.get("nbf"), "nbf"); + long expiresAt = requirePositiveInteger(record.get("exp"), "exp"); + requireEqual( + "1", + requirePositiveDecimal(record.get("tokenGeneration"), "tokenGeneration"), + "initial token generation mismatch"); + validateTimeWindow(issuedAt, notBefore, expiresAt, 0L); + Map tuple = requireObject(record.get("authorityTuple"), "authorityTuple"); + String accountGeneration = + requirePositiveDecimal( + tuple.get("accountAuthorityGeneration"), "accountAuthorityGeneration"); + boolean hasCutoff = tuple.containsKey("accountSecurityCutoff"); + if (hasCutoff != !"1".equals(accountGeneration)) { + throw invalid("Account security cutoff presence does not match the source generation"); + } + Set tupleFields = + new java.util.HashSet<>( + hasCutoff ? AUTHORITY_TUPLE_FIELDS_WITH_ACCOUNT_CUTOFF : AUTHORITY_TUPLE_FIELDS); + if (record.containsKey("tenantId") && tuple.containsKey("tenantBillingCutoff")) + tupleFields.add("tenantBillingCutoff"); + requireExactFields(tuple, tupleFields, "authorityTuple"); + requirePositiveDecimal(tuple.get("issuerAuthGeneration"), "issuerAuthGeneration"); + if (record.containsKey("tenantId")) { + GameSessionAccountDelegationProfile.requirePublicTenantBoundAuthority( + requireCanonicalUuid(record.get("tenantId"), "tenantId"), + tuple, + requireObject(record.get("membershipVersion"), "membershipVersion")); + } else { + requireEmptyObject(tuple.get("tenantAuthorityGeneration"), "tenantAuthorityGeneration"); + requireEmptyObject( + tuple.get("membershipAuthorityGeneration"), "membershipAuthorityGeneration"); + } + requireEmptyList(tuple.get("privateRealmGrantVersions"), "privateRealmGrantVersions"); + if (hasCutoff) { + Map cutoff = + requireObject(tuple.get("accountSecurityCutoff"), "accountSecurityCutoff"); + requireExactFields(cutoff, ACCOUNT_SECURITY_CUTOFF_FIELDS, "accountSecurityCutoff"); + String cutoffGeneration = + requirePositiveDecimal(cutoff.get("accountAuthorityGeneration"), "cutoff generation"); + String cutoffSequence = + requirePositiveDecimal(cutoff.get("outboxSequence"), "cutoff outbox sequence"); + String cutoffStream = requireText(cutoff.get("outboxStreamKey"), "cutoff stream", 2048); + long accountGenerationValue = + requirePositiveDecimalLong(accountGeneration, "account generation"); + if (!accountGeneration.equals(cutoffGeneration) + || !Long.toString(accountGenerationValue - 1L).equals(cutoffSequence) + || !("account:auth-authority:v1:account/" + accountId).equals(cutoffStream)) { + throw invalid("Account security cutoff scope or sequence is invalid"); + } + } + if (!record.containsKey("tenantId")) + requireEmptyObject(record.get("membershipVersion"), "membershipVersion"); + requirePositiveDecimal(record.get("issuanceFence"), "issuanceFence"); + Map versions = + requireObject(record.get("authoritySourceVersions"), "authoritySourceVersions"); + requireExactFields(versions, SOURCE_VERSION_FIELDS, "authoritySourceVersions"); + for (String field : SOURCE_VERSION_FIELDS) { + requirePositiveDecimal(versions.get(field), field); + } + Map bundle = + requireObject(record.get("authEvidenceBundle"), "authEvidenceBundle"); + requireExactFields( + bundle, + Set.of("bundleVersion", "sourceVersion", "sourceFence", "linearization", "canonicalSha256"), + "authEvidenceBundle"); + requirePositiveDecimal(bundle.get("bundleVersion"), "bundleVersion"); + requirePositiveDecimal(bundle.get("sourceVersion"), "sourceVersion"); + requirePositiveDecimal(bundle.get("sourceFence"), "sourceFence"); + requirePositiveLinearization(bundle.get("linearization")); + requireMatch(HASH, bundle.get("canonicalSha256"), "canonicalSha256"); + } + + private static void validateAuthorityTuple( + Object tupleValue, Object membershipVersionValue, AccountAuthoritySnapshot snapshot) { + Map tuple = requireObject(tupleValue, "authorityTuple"); + Set expectedFields = + snapshot.accountSecurityCutoff().isPresent() + ? AUTHORITY_TUPLE_FIELDS_WITH_ACCOUNT_CUTOFF + : AUTHORITY_TUPLE_FIELDS; + requireExactFields(tuple, expectedFields, "authorityTuple"); + if (canonicalize(serialize(tuple)).length + > GameSessionAccountDelegationProfile.MAX_AUTHORITY_TUPLE_BYTES) { + throw invalid("authorityTuple exceeds its finite profile byte bound"); + } + requireEqual( + Long.toString(snapshot.issuerGeneration()), + requirePositiveDecimal(tuple.get("issuerAuthGeneration"), "issuerAuthGeneration"), + "issuer authority generation mismatch"); + requireEqual( + Long.toString(snapshot.accountGeneration()), + requirePositiveDecimal( + tuple.get("accountAuthorityGeneration"), "accountAuthorityGeneration"), + "Account authority generation mismatch"); + requireEmptyObject(tuple.get("tenantAuthorityGeneration"), "tenantAuthorityGeneration"); + requireEmptyObject(tuple.get("membershipAuthorityGeneration"), "membershipAuthorityGeneration"); + requireEmptyList(tuple.get("privateRealmGrantVersions"), "privateRealmGrantVersions"); + if (snapshot.accountSecurityCutoff().isPresent()) { + Map cutoff = + requireObject(tuple.get("accountSecurityCutoff"), "accountSecurityCutoff"); + requireExactFields(cutoff, ACCOUNT_SECURITY_CUTOFF_FIELDS, "accountSecurityCutoff"); + requirePositiveDecimal(cutoff.get("accountAuthorityGeneration"), "cutoff generation"); + requirePositiveDecimal(cutoff.get("outboxSequence"), "cutoff outbox sequence"); + requireText(cutoff.get("outboxStreamKey"), "cutoff outboxStreamKey", 2048); + if (!snapshot.accountSecurityCutoff().orElseThrow().toMap().equals(cutoff)) { + throw invalid("Account security cutoff does not match the source snapshot"); + } + } + requireEmptyObject(membershipVersionValue, "membershipVersion"); + } + + private static CompactToken parseCompactJwt(String compactJwt) { + byte[] compactBytes = compactJwt.getBytes(StandardCharsets.US_ASCII); + if (compactJwt.length() == 0 + || compactJwt.length() > GameSessionAccountDelegationProfile.MAX_COMPACT_JWT_BYTES + || compactBytes.length != compactJwt.length()) { + throw invalid("Compact JWT is absent or exceeds its profile byte bound"); + } + String[] parts = compactJwt.split("\\.", -1); + if (parts.length != 3 || Arrays.stream(parts).anyMatch(String::isEmpty)) { + throw invalid("Compact JWT is malformed"); + } + byte[] headerBytes = decodeBase64Url(parts[0]); + byte[] claimsBytes = decodeBase64Url(parts[1]); + decodeBase64Url(parts[2]); + Map header = parseObject(strictUtf8(headerBytes), "JOSE header"); + Set headerFields = header.keySet(); + if (!HEADER_ALLOWED.containsAll(headerFields) || !headerFields.containsAll(HEADER_REQUIRED)) { + throw invalid("JOSE header fields are not the exact supported set"); + } + requireEqual("RS256", header.get("alg"), "Account delegation must use RS256"); + String kid = requireText(header.get("kid"), "kid", 64); + requireMatch(KID, kid, "kid"); + if (header.containsKey("typ")) requireEqual("JWT", header.get("typ"), "typ"); + Map claims = parseObject(strictUtf8(claimsBytes), "JWT claims"); + return new CompactToken(kid, claims); + } + + private static void validateTimeWindow(long issuedAt, long notBefore, long expiresAt, long now) { + long lifetime; + try { + lifetime = Math.subtractExact(expiresAt, issuedAt); + } catch (ArithmeticException ex) { + throw invalid("JWT time bounds are invalid or expired"); + } + long latestAllowedIssuedAt = now; + if (now > 0L) { + try { + latestAllowedIssuedAt = Math.addExact(now, 5L); + } catch (ArithmeticException ex) { + latestAllowedIssuedAt = Long.MAX_VALUE; + } + } + if (notBefore > issuedAt + || lifetime <= 0L + || lifetime > GameSessionAccountDelegationProfile.MAX_TOKEN_LIFETIME_SECONDS + || (now > 0L && (issuedAt > latestAllowedIssuedAt || expiresAt <= now))) { + throw invalid("JWT time bounds are invalid or expired"); + } + } + + private static byte[] decodeBase64Url(String value) { + try { + if (value.indexOf('=') >= 0 || !value.matches("[A-Za-z0-9_-]+")) + throw invalid("JWT segment is not base64url"); + byte[] decoded = Base64.getUrlDecoder().decode(value); + if (!Base64.getUrlEncoder().withoutPadding().encodeToString(decoded).equals(value)) { + throw invalid("JWT segment has a non-canonical base64url encoding"); + } + return decoded; + } catch (IllegalArgumentException ex) { + if (ex instanceof InvalidRecordException invalid) throw invalid; + throw invalid("JWT segment is malformed"); + } + } + + private static Map parseObject(String json, String field) { + try { + Map parsed = JSON.readValue(json, new TypeReference<>() {}); + if (parsed == null || parsed.isEmpty()) throw invalid(field + " must be a non-empty object"); + return parsed; + } catch (RuntimeException ex) { + if (ex instanceof InvalidRecordException invalid) throw invalid; + throw invalid(field + " is malformed"); + } + } + + private static Map requireObject(Object value, String field) { + if (!(value instanceof Map map)) throw invalid(field + " must be an object"); + Map result = new LinkedHashMap<>(); + map.forEach( + (key, item) -> { + if (!(key instanceof String name) || item == null || result.put(name, item) != null) { + throw invalid(field + " contains an invalid member"); + } + }); + return result; + } + + private static Map immutableMap(Map input) { + Map copy = new LinkedHashMap<>(); + input.forEach( + (key, value) -> { + if (key == null || value == null) throw invalid("Null registry field is forbidden"); + copy.put(key, deepImmutable(value)); + }); + return Map.copyOf(copy); + } + + private static Object deepImmutable(Object value) { + if (value instanceof Map map) { + Map nested = new LinkedHashMap<>(); + map.forEach( + (key, item) -> { + if (!(key instanceof String name) || item == null) { + throw invalid("Null or invalid nested registry field is forbidden"); + } + nested.put(name, deepImmutable(item)); + }); + return Map.copyOf(nested); + } + if (value instanceof List list) { + return list.stream().map(GameSessionAccountDelegationRegistryRecord::deepImmutable).toList(); + } + return value; + } + + private static void requireExactFields( + Map value, Set expected, String field) { + if (!value.keySet().equals(expected)) throw invalid(field + " has missing or unknown fields"); + if (value.values().stream().anyMatch(Objects::isNull)) throw invalid(field + " contains null"); + } + + private static void requireEmptyObject(Object value, String field) { + if (!(value instanceof Map map) || !map.isEmpty()) + throw invalid(field + " must be an empty object"); + } + + private static void requireEmptyList(Object value, String field) { + if (!(value instanceof List list) || !list.isEmpty()) + throw invalid(field + " must be an empty list"); + } + + private static long requirePositiveInteger(Object value, String field) { + if (!(value instanceof Number number)) throw invalid(field + " must be a JSON integer"); + String encoded = number.toString(); + if (!POSITIVE_DECIMAL.matcher(encoded).matches()) { + throw invalid(field + " must be a bounded positive integer"); + } + try { + return Long.parseLong(encoded); + } catch (NumberFormatException ex) { + throw invalid(field + " must be a bounded positive integer"); + } + } + + private static long requirePositiveDecimalLong(Object value, String field) { + String decimal = requirePositiveDecimal(value, field); + try { + return Long.parseLong(decimal); + } catch (NumberFormatException ex) { + throw invalid(field + " exceeds the supported range"); + } + } + + private static long requirePositive(long value, String field) { + if (value <= 0L) throw invalid(field + " must be positive"); + return value; + } + + private static String requirePositiveDecimal(Object value, String field) { + if (!(value instanceof String string) || !POSITIVE_DECIMAL.matcher(string).matches()) { + throw invalid(field + " must be a canonical positive decimal string"); + } + try { + Long.parseLong(string); + return string; + } catch (NumberFormatException ex) { + throw invalid(field + " exceeds the supported range"); + } + } + + private static String requireCanonicalUuid(Object value, String field) { + String text = requireText(value, field, 36); + try { + UUID parsed = UUID.fromString(text); + if (!parsed.toString().equals(text) || parsed.equals(new UUID(0L, 0L))) + throw invalid(field + " is not a canonical UUID"); + return text; + } catch (IllegalArgumentException ex) { + if (ex instanceof InvalidRecordException invalid) throw invalid; + throw invalid(field + " is not a canonical UUID"); + } + } + + private static String requireText(Object value, String field, int maxLength) { + if (!(value instanceof String text) || text.isEmpty() || text.length() > maxLength) { + throw invalid(field + " must be a bounded non-empty string"); + } + for (int i = 0; i < text.length(); i++) { + if (Character.isISOControl(text.charAt(i))) + throw invalid(field + " contains a control character"); + } + return text; + } + + private static void requireMatch(Pattern pattern, Object value, String field) { + if (!(value instanceof String text) || !pattern.matcher(text).matches()) + throw invalid(field + " has an invalid format"); + } + + private static String requireMatchValue(Pattern pattern, Object value, String field) { + requireMatch(pattern, value, field); + return (String) value; + } + + private static String requirePositiveLinearization(Object value) { + if (!(value instanceof String text) || !POSITIVE_LINEARIZATION.matcher(text).matches()) { + throw invalid("bundle linearization is malformed"); + } + return text; + } + + private static void requireExactInteger(Object value, long expected, String field) { + if (!(value instanceof Number number)) throw invalid(field + " must be an integer"); + String encoded = number.toString(); + if (!encoded.matches("0|[1-9][0-9]{0,18}")) { + throw invalid(field + " is unsupported"); + } + try { + if (Long.parseLong(encoded) != expected) throw invalid(field + " is unsupported"); + } catch (NumberFormatException ex) { + throw invalid(field + " is unsupported"); + } + } + + private static void requireEqual(Object expected, Object actual, String message) { + if (!Objects.equals(expected, actual)) throw invalid(message); + } + + private static void requireBound(long value, long maximum, String field) { + if (value <= 0L || value > maximum) + throw invalid(field + " is outside the finite profile bound"); + } + + private static String strictUtf8(byte[] bytes) { + try { + return StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(bytes)) + .toString(); + } catch (CharacterCodingException ex) { + throw invalid("JWT/registry JSON is not valid UTF-8"); + } + } + + private static String serialize(Object value) { + try { + return JSON.writeValueAsString(value); + } catch (RuntimeException ex) { + throw invalid("Registry JSON could not be serialized"); + } + } + + private static byte[] canonicalize(String value) { + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(value); + } catch (IOException | RuntimeException ex) { + throw invalid("RFC 8785 canonicalization failed"); + } + } + + private static String sha256(byte[] bytes) { + try { + return java.util.HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException ex) { + throw new IllegalStateException("SHA-256 is unavailable", ex); + } + } + + private static InvalidRecordException invalid(String message) { + return new InvalidRecordException(message); + } + + private record CompactToken(String keyId, Map claims) {} + + public record AccountAuthoritySnapshot( + UUID accountId, + long issuerGeneration, + long issuerSourceVersion, + long accountGeneration, + long accountSourceVersion, + long issuanceFence, + long issuanceFenceSourceVersion, + Optional accountSecurityCutoff) { + public AccountAuthoritySnapshot { + Objects.requireNonNull(accountId, "Canonical Account UUID is required"); + Objects.requireNonNull(accountSecurityCutoff, "Account cutoff applicability is required"); + if (accountId.equals(new UUID(0L, 0L)) + || issuerGeneration <= 0L + || issuerSourceVersion <= 0L + || accountGeneration <= 0L + || accountSourceVersion <= 0L + || issuanceFence <= 0L + || issuanceFenceSourceVersion <= 0L + || issuerGeneration != issuerSourceVersion + || accountGeneration != accountSourceVersion + || accountGeneration != issuanceFence + || accountGeneration != issuanceFenceSourceVersion) { + throw invalid("Durable Account authority snapshot is malformed"); + } + String expectedStream = "account:auth-authority:v1:account/" + accountId; + if (accountGeneration == 1L) { + if (accountSecurityCutoff.isPresent()) { + throw invalid("Fresh sequence-zero Account authority cannot carry a cutoff"); + } + } else { + GameSessionAccountDelegationProfile.AccountSecurityCutoff cutoff = + accountSecurityCutoff.orElseThrow( + () -> invalid("Advanced Account authority requires its source cutoff")); + if (!Long.toString(accountGeneration).equals(cutoff.accountAuthorityGeneration()) + || !expectedStream.equals(cutoff.outboxStreamKey()) + || !Long.toString(accountGeneration - 1L).equals(cutoff.outboxSequence())) { + throw invalid("Account security cutoff scope or sequence is stale"); + } + } + } + + public Map sourceVersions() { + return Map.of( + "issuerSourceVersion", Long.toString(issuerSourceVersion), + "accountSourceVersion", Long.toString(accountSourceVersion), + "issuanceFenceSourceVersion", Long.toString(issuanceFenceSourceVersion)); + } + } + + public record IssuanceBinding( + String operationId, String requestId, String requestDigest, String accountId) { + public IssuanceBinding { + requireCanonicalUuid(operationId, "operationId"); + requireCanonicalUuid(requestId, "requestId"); + requireMatch(HASH, requestDigest, "requestDigest"); + requireCanonicalUuid(accountId, "accountId"); + } + } + + /** Exact immutable V46 bundle reference and digest bound into the registry projection. */ + public record EvidenceBundleReference( + String bundleVersion, + String sourceVersion, + String sourceFence, + String linearization, + String canonicalSha256) { + public EvidenceBundleReference { + requirePositiveDecimal(bundleVersion, "bundleVersion"); + requirePositiveDecimal(sourceVersion, "sourceVersion"); + requirePositiveDecimal(sourceFence, "sourceFence"); + requirePositiveLinearization(linearization); + requireMatch(HASH, canonicalSha256, "canonicalSha256"); + } + + public Map toMap() { + return Map.of( + "bundleVersion", bundleVersion, + "sourceVersion", sourceVersion, + "sourceFence", sourceFence, + "linearization", linearization, + "canonicalSha256", canonicalSha256); + } + } + + public static final class InvalidRecordException extends IllegalArgumentException { + public InvalidRecordException(String message) { + super(message); + } + } +} + diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/security/PlayerBootstrapJwtProfileValidator.java b/services/common-security/src/main/java/net/firedevops/firemud/common/security/PlayerBootstrapJwtProfileValidator.java new file mode 100644 index 0000000000..4eab9411e3 --- /dev/null +++ b/services/common-security/src/main/java/net/firedevops/firemud/common/security/PlayerBootstrapJwtProfileValidator.java @@ -0,0 +1,39 @@ +package net.firedevops.firemud.common.security; + +import java.util.Map; +import java.util.Set; + +/** Validates the canonical, tenant-free player-bootstrap JWT claim shape. */ +public final class PlayerBootstrapJwtProfileValidator { + public static final String PROFILE = "player-bootstrap"; + public static final String AUDIENCE = "player-bootstrap"; + public static final String TOKEN_TYPE = "player-bootstrap"; + private static final String ISSUER = "firemud-account-service"; + public static final Set REQUIRED_CLAIMS; + public static final Set OPTIONAL_CLAIMS = Set.of("globalRoles"); + + static { + Set required = + new java.util.HashSet<>(AccountJwtProfileClaimSupport.REQUIRED_BASE_CLAIMS); + required.add("scopedRoles"); + REQUIRED_CLAIMS = Set.copyOf(required); + } + + private PlayerBootstrapJwtProfileValidator() {} + + /** Checks profile shape only; it does not validate current membership or authorize a route. */ + public static void validateClaims(Map claims) { + AccountJwtProfileClaimSupport.requireClaimFields(claims, REQUIRED_CLAIMS, OPTIONAL_CLAIMS); + AccountJwtProfileClaimSupport.requireCommonIdentity(claims, ISSUER, AUDIENCE); + AccountJwtProfileClaimSupport.requireAuthorityTuple( + claims.get("authorityTuple"), false, true, false); + if (!AccountJwtProfileClaimSupport.requireVersionMap(claims.get("membershipVersion")).isEmpty() + || !AccountJwtProfileClaimSupport.requireObjectMap(claims.get("scopedRoles")).isEmpty()) { + throw AccountJwtProfileClaimSupport.invalid(); + } + if (claims.containsKey("globalRoles")) { + AccountJwtProfileClaimSupport.requireRoleList(claims.get("globalRoles")); + } + } +} + diff --git a/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/ControlUiJwtProfileValidatorTest.java b/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/ControlUiJwtProfileValidatorTest.java new file mode 100644 index 0000000000..f33d68c204 --- /dev/null +++ b/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/ControlUiJwtProfileValidatorTest.java @@ -0,0 +1,219 @@ +package net.firedevops.firemud.common.security; + +import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import org.junit.jupiter.api.Test; + +class ControlUiJwtProfileValidatorTest { + private static final String ACCOUNT = "11111111-1111-4111-8111-111111111111"; + private static final String TENANT_A = "22222222-2222-4222-8222-222222222222"; + private static final String TENANT_B = "33333333-3333-4333-8333-333333333333"; + + @Test + void acceptsSeparateTargetAndMembershipApplicabilityAndOptionalGlobalRoles() { + Map claims = baseClaims(); + claims.put( + "authorityTuple", authorityTuple(Map.of(TENANT_A, 2L), Map.of(TENANT_B, 3L), List.of())); + claims.put("membershipVersion", Map.of(TENANT_B, 8L)); + claims.put("scopedRoles", Map.of(TENANT_A, List.of("tenantAdmin"))); + + assertThatCode(() -> ControlUiJwtProfileValidator.validateClaims(claims, 1)) + .doesNotThrowAnyException(); + claims.put("globalRoles", List.of()); + assertThatCode(() -> ControlUiJwtProfileValidator.validateClaims(claims, 1)) + .doesNotThrowAnyException(); + } + + @Test + void preservesProfileSpecificOptionalAccountCutoffOmission() { + Map claims = validClaims(); + Map tuple = object(claims.get("authorityTuple")); + tuple.put("accountAuthorityGeneration", 2L); + claims.put("authorityTuple", tuple); + + assertThatCode(() -> ControlUiJwtProfileValidator.validateClaims(claims, 1)) + .doesNotThrowAnyException(); + } + + @Test + void rejectsMismatchedMembershipPairMalformedScopeAndEmptyPresentOptionalObject() { + Map mismatch = validClaims(); + mismatch.put("membershipVersion", Map.of(TENANT_A, 8L)); + assertInvalid(mismatch); + + Map badScope = validClaims(); + badScope.put("scopedRoles", Map.of(ACCOUNT, List.of("tenantAdmin"))); + assertInvalid(badScope); + + Map emptyBillingObject = validClaims(); + Map tuple = object(emptyBillingObject.get("authorityTuple")); + tuple.put("tenantBillingCutoff", Map.of()); + emptyBillingObject.put("authorityTuple", tuple); + assertInvalid(emptyBillingObject); + + Map nullBillingObject = validClaims(); + tuple = object(nullBillingObject.get("authorityTuple")); + tuple.put("tenantBillingCutoff", null); + nullBillingObject.put("authorityTuple", tuple); + assertInvalid(nullBillingObject); + + Map malformedRole = validClaims(); + malformedRole.put("scopedRoles", Map.of(TENANT_A, List.of("tenantAdmin", "tenantAdmin"))); + assertInvalid(malformedRole); + assertInvalid(Map.of("unexpected", true)); + } + + @Test + void sharedConfiguredScopeCapBoundsEveryControlUiApplicabilityMap() { + Map tooManyScopedRoles = validClaims(); + tooManyScopedRoles.put( + "scopedRoles", Map.of(TENANT_A, List.of("tenantAdmin"), TENANT_B, List.of("reader"))); + assertInvalidAtCap(tooManyScopedRoles, 1); + + Map tooManyTenantGenerations = validClaims(); + Map tenantTuple = object(tooManyTenantGenerations.get("authorityTuple")); + tenantTuple.put("tenantAuthorityGeneration", Map.of(TENANT_A, 2L, TENANT_B, 3L)); + tooManyTenantGenerations.put("authorityTuple", tenantTuple); + tooManyTenantGenerations.put( + "scopedRoles", Map.of(TENANT_A, List.of("tenantAdmin"), TENANT_B, List.of("reader"))); + assertInvalidAtCap(tooManyTenantGenerations, 1); + + Map tooManyMembershipGenerations = validClaims(); + Map membershipTuple = + object(tooManyMembershipGenerations.get("authorityTuple")); + membershipTuple.put("membershipAuthorityGeneration", Map.of(TENANT_A, 2L, TENANT_B, 3L)); + tooManyMembershipGenerations.put("authorityTuple", membershipTuple); + tooManyMembershipGenerations.put("membershipVersion", Map.of(TENANT_A, 7L, TENANT_B, 8L)); + tooManyMembershipGenerations.put("scopedRoles", Map.of(TENANT_A, List.of("tenantAdmin"))); + assertInvalidAtCap(tooManyMembershipGenerations, 1); + + Map tooManyBillingCutoffs = validClaims(); + Map billingTuple = object(tooManyBillingCutoffs.get("authorityTuple")); + Map cutoff = + Map.of( + "tenantAuthorityGeneration", 2L, + "tenantBillingSequence", 3L, + "outboxStreamKey", "account:tenant-billing:v1:tenant/" + TENANT_A, + "outboxSequence", 4L); + billingTuple.put("tenantBillingCutoff", Map.of(TENANT_A, cutoff, TENANT_B, cutoff)); + tooManyBillingCutoffs.put("authorityTuple", billingTuple); + tooManyBillingCutoffs.put( + "scopedRoles", Map.of(TENANT_A, List.of("tenantAdmin"), TENANT_B, List.of("reader"))); + assertInvalidAtCap(tooManyBillingCutoffs, 1); + } + + @Test + void eachControlUiApplicabilityMapAcceptsTheExactConfiguredCap() { + Map claims = validClaims(); + Map tuple = object(claims.get("authorityTuple")); + tuple.put( + "tenantBillingCutoff", + Map.of( + TENANT_A, + Map.of( + "tenantAuthorityGeneration", + 2L, + "tenantBillingSequence", + 3L, + "outboxStreamKey", + "account:tenant-billing:v1:tenant/" + TENANT_A, + "outboxSequence", + 4L))); + claims.put("authorityTuple", tuple); + + assertThatCode(() -> ControlUiJwtProfileValidator.validateClaims(claims, 1)) + .doesNotThrowAnyException(); + } + + @Test + void nilAndAccountIdTenantKeysAreRejectedAsMalformedProfileKeys() { + Map nilAccount = validClaims(); + nilAccount.put("sub", "00000000-0000-0000-0000-000000000000"); + nilAccount.put("accountId", "00000000-0000-0000-0000-000000000000"); + assertInvalid(nilAccount); + + Map accountKey = validClaims(); + Map tuple = object(accountKey.get("authorityTuple")); + tuple.put("tenantAuthorityGeneration", Map.of(ACCOUNT, 2L)); + accountKey.put("authorityTuple", tuple); + accountKey.put("scopedRoles", Map.of(ACCOUNT, List.of("tenantAdmin"))); + assertInvalid(accountKey); + } + + @Test + void canonicalAuthorityTupleByteCeilingIsEnforcedAfterTheFiniteCountCap() { + Map tenantGenerations = new LinkedHashMap<>(); + Map> scopedRoles = new LinkedHashMap<>(); + for (int index = 0; index < 100; index++) { + String tenantId = UUID.randomUUID().toString(); + tenantGenerations.put(tenantId, 1L); + scopedRoles.put(tenantId, List.of("reader")); + } + Map claims = baseClaims(); + claims.put("authorityTuple", authorityTuple(tenantGenerations, Map.of(), List.of())); + claims.put("membershipVersion", Map.of()); + claims.put("scopedRoles", scopedRoles); + + assertInvalidAtCap(claims, 128); + } + + private static Map validClaims() { + Map claims = baseClaims(); + claims.put( + "authorityTuple", authorityTuple(Map.of(TENANT_A, 2L), Map.of(TENANT_B, 3L), List.of())); + claims.put("membershipVersion", Map.of(TENANT_B, 8L)); + claims.put("scopedRoles", Map.of(TENANT_A, List.of("tenantAdmin"))); + return claims; + } + + private static Map baseClaims() { + Map claims = new LinkedHashMap<>(); + claims.put("iss", "firemud-account-service"); + claims.put("sub", ACCOUNT); + claims.put("accountId", ACCOUNT); + claims.put("jti", UUID.randomUUID().toString()); + claims.put("aud", ControlUiJwtProfileValidator.AUDIENCE); + claims.put("iat", 1L); + claims.put("nbf", 1L); + claims.put("exp", 300L); + claims.put("tokenGeneration", 1L); + claims.put("issuanceFence", 1L); + return claims; + } + + private static Map authorityTuple( + Map tenantGenerations, + Map membershipGenerations, + List privateGrants) { + Map tuple = new LinkedHashMap<>(); + tuple.put("issuerAuthGeneration", 1L); + tuple.put("accountAuthorityGeneration", 1L); + tuple.put("tenantAuthorityGeneration", tenantGenerations); + tuple.put("membershipAuthorityGeneration", membershipGenerations); + tuple.put("privateRealmGrantVersions", privateGrants); + return tuple; + } + + @SuppressWarnings("unchecked") + private static Map object(Object value) { + return new LinkedHashMap<>((Map) value); + } + + private static void assertInvalid(Map claims) { + assertThatThrownBy(() -> ControlUiJwtProfileValidator.validateClaims(claims, 8)) + .isInstanceOf(AccountAsymmetricJwtVerifier.VerificationException.class) + .hasNoCause(); + } + + private static void assertInvalidAtCap(Map claims, int cap) { + assertThatThrownBy(() -> ControlUiJwtProfileValidator.validateClaims(claims, cap)) + .isInstanceOf(AccountAsymmetricJwtVerifier.VerificationException.class) + .hasNoCause(); + } +} + diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/operator/StartSessionPreAuthorizationReservationService.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/operator/StartSessionPreAuthorizationReservationService.java new file mode 100644 index 0000000000..a3a3b914d9 --- /dev/null +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/operator/StartSessionPreAuthorizationReservationService.java @@ -0,0 +1,360 @@ +package net.firedevops.firemud.loggingadmin.operator; + +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.loggingadmin.repository.StartSessionPreAuthorizationReservationRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +/** Durable, bounded Logging/Admin claim lifecycle for the StartSession pre-authorization phase. */ +@Service +public final class StartSessionPreAuthorizationReservationService { + public static final Duration CLAIM_TTL = Duration.ofSeconds(30); + + private final StartSessionPreAuthorizationReservationRepository repository; + private final Clock clock; + + @Autowired + public StartSessionPreAuthorizationReservationService( + StartSessionPreAuthorizationReservationRepository repository) { + this(repository, Clock.systemUTC()); + } + + StartSessionPreAuthorizationReservationService( + StartSessionPreAuthorizationReservationRepository repository, Clock clock) { + this.repository = Objects.requireNonNull(repository, "repository is required"); + this.clock = Objects.requireNonNull(clock, "clock is required"); + } + + /** + * Atomically creates one reservation or returns the exact existing reservation as a duplicate. + * Only the first caller receives a claim capability; an exact duplicate cannot dispatch work. + */ + public Acquisition acquire(StartSessionPreAuthorizationReservationTuple tuple) { + Objects.requireNonNull(tuple, "tuple is required"); + if (!tuple.isAuthorityDerived()) { + throw new IllegalArgumentException( + "initial reservation requires an actor derived from the authenticated request context"); + } + Instant now = clock.instant(); + UUID ownerId = UUID.randomUUID(); + StartSessionPreAuthorizationReservationRepository.AcquireResult result = + repository.acquire(tuple, ownerId, epochMillis(now), epochMillis(now.plus(CLAIM_TTL))); + ClaimHandle claim = + result.created() + ? new ClaimHandle( + tuple, + tuple.mutationDigest(), + ownerId, + ownerId, + result.snapshot().reservationClaimFence(), + result.snapshot().claimFence(), + ClaimKind.ORIGINAL) + : null; + return new Acquisition(result.snapshot(), claim); + } + + /** Read-only lookup by the one stable orchestration key. */ + public Optional find(String controlPlaneRequestId) { + return repository.find(controlPlaneRequestId); + } + + /** Read-only exact lookup; a reused key with any tuple difference conflicts. */ + public Optional findExact(StartSessionPreAuthorizationReservationTuple tuple) { + Objects.requireNonNull(tuple, "tuple is required"); + return repository.findExact(tuple); + } + + /** + * Durably enters AUTHORIZATION_PENDING before the Account call is dispatched by a later + * integration. Only the first successful transition returns {@code mayDispatch=true}; observing + * the pending state again never authorizes another issuance call. + */ + public PendingTransition markAuthorizationPending(ClaimHandle claim) { + requireClaim(claim); + if (claim.isRecoveryLookupOnly()) { + throw new StaleReservationClaimException(claim.controlPlaneRequestId()); + } + StartSessionPreAuthorizationReservationRepository.TransitionResult result = + repository.markAuthorizationPending( + claim.tuple, + claim.mutationDigest, + claim.ownerId, + claim.fence, + epochMillis(clock.instant())); + return new PendingTransition(result.snapshot(), result.transitioned()); + } + + /** Renew only the exact current, active claim before its expiry. */ + public Snapshot renew(ClaimHandle claim, Phase expectedPhase, State expectedState) { + requireClaim(claim); + Instant now = clock.instant(); + return repository.renew( + claim.tuple, + claim.mutationDigest, + claim.ownerId, + claim.fence, + expectedPhase, + expectedState, + epochMillis(now), + epochMillis(now.plus(CLAIM_TTL))); + } + + /** + * Advance the current fence after the exact claim expires. Expiry leaves the phase and state + * unchanged; it is not evidence that Account authorization did not happen. + */ + public Snapshot expireClaim(ClaimHandle claim, Phase expectedPhase, State expectedState) { + requireClaim(claim); + return repository.expireClaim( + claim.tuple, + claim.mutationDigest, + claim.ownerId, + claim.fence, + expectedPhase, + expectedState, + epochMillis(clock.instant())); + } + + /** + * Acquire one fresh recovery claim only for an expired AUTHORIZATION_PENDING reservation. The + * returned claim is suitable only for a future read-only Account recovery lookup; it cannot + * initiate issuance or authorize owner forwarding. Original reservation owner/fence evidence is + * preserved in the row and snapshot. + */ + public Optional acquireAuthorizationRecoveryClaim( + StartSessionPreAuthorizationReservationTuple tuple) { + Objects.requireNonNull(tuple, "tuple is required"); + Instant now = clock.instant(); + UUID recoveryOwnerId = UUID.randomUUID(); + Optional acquired = + repository.acquireRecoveryClaim( + tuple, recoveryOwnerId, epochMillis(now), epochMillis(now.plus(CLAIM_TTL))); + return acquired.map( + result -> + new RecoveryAcquisition( + result.snapshot(), + new ClaimHandle( + tuple, + tuple.mutationDigest(), + result.reservationOwnerId(), + recoveryOwnerId, + result.snapshot().reservationClaimFence(), + result.snapshot().claimFence(), + ClaimKind.RECOVERY_LOOKUP_ONLY))); + } + + private static void requireClaim(ClaimHandle claim) { + Objects.requireNonNull(claim, "claim is required"); + } + + private static long epochMillis(Instant instant) { + long millis = instant.toEpochMilli(); + if (millis <= 0) { + throw new IllegalArgumentException("reservation time must be after the Unix epoch"); + } + return millis; + } + + public enum Phase { + ACCOUNT_AUTHORIZATION + } + + public enum State { + RESERVED, + AUTHORIZATION_PENDING + } + + public enum ClaimState { + ACTIVE, + EXPIRED + } + + private enum ClaimKind { + ORIGINAL, + RECOVERY_LOOKUP_ONLY + } + + public record Snapshot( + StartSessionPreAuthorizationReservationTuple tuple, + String mutationDigest, + Phase phase, + State state, + long reservationClaimFence, + long claimFence, + long claimExpiresAtEpochMillis, + ClaimState claimState) { + public Snapshot { + Objects.requireNonNull(tuple, "tuple is required"); + Objects.requireNonNull(mutationDigest, "mutationDigest is required"); + Objects.requireNonNull(phase, "phase is required"); + Objects.requireNonNull(state, "state is required"); + Objects.requireNonNull(claimState, "claimState is required"); + if (reservationClaimFence != 1 || claimFence < reservationClaimFence) { + throw new IllegalArgumentException("reservation claim fences are invalid"); + } + if (claimExpiresAtEpochMillis <= 0) { + throw new IllegalArgumentException("claim expiry must be positive"); + } + if (!tuple.mutationDigest().equals(mutationDigest)) { + throw new IllegalArgumentException("stored mutationDigest does not match the typed tuple"); + } + } + } + + /** Opaque capability returned only to the caller that acquired a new claim. */ + public static final class ClaimHandle { + private final StartSessionPreAuthorizationReservationTuple tuple; + private final String mutationDigest; + private final UUID reservationOwnerId; + private final UUID ownerId; + private final long reservationFence; + private final long fence; + private final ClaimKind kind; + + private ClaimHandle( + StartSessionPreAuthorizationReservationTuple tuple, + String mutationDigest, + UUID reservationOwnerId, + UUID ownerId, + long reservationFence, + long fence, + ClaimKind kind) { + this.tuple = Objects.requireNonNull(tuple, "tuple is required"); + this.mutationDigest = Objects.requireNonNull(mutationDigest, "mutationDigest is required"); + this.reservationOwnerId = + Objects.requireNonNull(reservationOwnerId, "reservationOwnerId is required"); + this.ownerId = Objects.requireNonNull(ownerId, "ownerId is required"); + this.reservationFence = reservationFence; + this.fence = fence; + this.kind = Objects.requireNonNull(kind, "claim kind is required"); + if (reservationOwnerId.equals(new UUID(0L, 0L)) + || ownerId.equals(new UUID(0L, 0L)) + || reservationFence <= 0 + || fence < reservationFence) { + throw new IllegalArgumentException("reservation claim fences are invalid"); + } + } + + public String controlPlaneRequestId() { + return tuple.controlPlaneRequestId(); + } + + public long claimFence() { + return fence; + } + + public StartSessionPreAuthorizationReservationTuple tuple() { + return tuple; + } + + public String mutationDigest() { + return mutationDigest; + } + + /** Original tuple owner/fence and current fenced claim, kept distinct during recovery. */ + public ClaimEvidence claimEvidence() { + return new ClaimEvidence(reservationOwnerId, reservationFence, ownerId, fence); + } + + public boolean isRecoveryLookupOnly() { + return kind == ClaimKind.RECOVERY_LOOKUP_ONLY; + } + } + + public record Acquisition(Snapshot snapshot, ClaimHandle claim) { + public Acquisition { + Objects.requireNonNull(snapshot, "snapshot is required"); + if (claim != null + && (claim.kind != ClaimKind.ORIGINAL + || snapshot.phase() != Phase.ACCOUNT_AUTHORIZATION + || snapshot.state() != State.RESERVED + || snapshot.claimState() != ClaimState.ACTIVE + || snapshot.claimFence() != claim.fence + || !snapshot.tuple().canonicalJson().equals(claim.tuple.canonicalJson()) + || !snapshot.mutationDigest().equals(claim.mutationDigest))) { + throw new IllegalArgumentException("initial claim does not match its reservation"); + } + } + + public boolean newlyAcquired() { + return claim != null; + } + } + + public static final class PendingTransition { + private final Snapshot snapshot; + private final boolean mayDispatchAccountAuthorization; + + private PendingTransition(Snapshot snapshot, boolean mayDispatchAccountAuthorization) { + this.snapshot = Objects.requireNonNull(snapshot, "snapshot is required"); + this.mayDispatchAccountAuthorization = mayDispatchAccountAuthorization; + if (snapshot.state() != State.AUTHORIZATION_PENDING && mayDispatchAccountAuthorization) { + throw new IllegalArgumentException("dispatch requires durable AUTHORIZATION_PENDING state"); + } + } + + public Snapshot snapshot() { + return snapshot; + } + + public boolean mayDispatchAccountAuthorization() { + return mayDispatchAccountAuthorization; + } + } + + public record RecoveryAcquisition(Snapshot snapshot, ClaimHandle claim) { + public RecoveryAcquisition { + Objects.requireNonNull(snapshot, "snapshot is required"); + Objects.requireNonNull(claim, "claim is required"); + if (snapshot.phase() != Phase.ACCOUNT_AUTHORIZATION + || snapshot.state() != State.AUTHORIZATION_PENDING + || snapshot.claimState() != ClaimState.ACTIVE + || !claim.isRecoveryLookupOnly() + || snapshot.claimFence() != claim.fence + || !snapshot.tuple().canonicalJson().equals(claim.tuple.canonicalJson()) + || !snapshot.mutationDigest().equals(claim.mutationDigest)) { + throw new IllegalArgumentException( + "recovery claim is not read-only authorization recovery"); + } + } + } + + public record ClaimEvidence( + UUID reservationOwnerId, + long reservationClaimFence, + UUID currentClaimOwnerId, + long currentClaimFence) { + public ClaimEvidence { + Objects.requireNonNull(reservationOwnerId, "reservationOwnerId is required"); + Objects.requireNonNull(currentClaimOwnerId, "currentClaimOwnerId is required"); + if (reservationClaimFence != 1 || currentClaimFence < reservationClaimFence) { + throw new IllegalArgumentException("reservation claim evidence is invalid"); + } + } + } + + public static class IdempotencyConflictException extends RuntimeException { + public IdempotencyConflictException(String controlPlaneRequestId) { + super( + "controlPlaneRequestId is already bound to a different StartSession tuple: " + + controlPlaneRequestId); + } + } + + public static class StaleReservationClaimException extends RuntimeException { + public StaleReservationClaimException(String controlPlaneRequestId) { + super("StartSession reservation claim is stale: " + controlPlaneRequestId); + } + } + + public static class ReservationClaimNotExpiredException extends RuntimeException { + public ReservationClaimNotExpiredException(String controlPlaneRequestId) { + super("StartSession reservation claim has not expired: " + controlPlaneRequestId); + } + } +} diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/operator/StartSessionPreAuthorizationReservationTuple.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/operator/StartSessionPreAuthorizationReservationTuple.java new file mode 100644 index 0000000000..74ea3a3da5 --- /dev/null +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/operator/StartSessionPreAuthorizationReservationTuple.java @@ -0,0 +1,139 @@ +package net.firedevops.firemud.loggingadmin.operator; + +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.security.SessionContext; + +/** Logging/Admin authority wrapper around the shared immutable StartSession tuple value. */ +public final class StartSessionPreAuthorizationReservationTuple { + public static final String TUPLE_SCHEMA_ID = + net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple + .TUPLE_SCHEMA_ID; + public static final String TUPLE_SCHEMA_VERSION = + net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple + .TUPLE_SCHEMA_VERSION; + public static final int MAX_CONTROL_PLANE_REQUEST_ID_UTF8_BYTES = + net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple + .MAX_CONTROL_PLANE_REQUEST_ID_UTF8_BYTES; + + private final net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple + value; + private final boolean authorityDerived; + + private StartSessionPreAuthorizationReservationTuple( + net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple value, + boolean authorityDerived) { + this.value = Objects.requireNonNull(value, "tuple value is required"); + this.authorityDerived = authorityDerived; + } + + /** Builds the tuple from the current authenticated tenant-admin request context. */ + public static StartSessionPreAuthorizationReservationTuple fromCurrentTenantAdmin( + String controlPlaneRequestId, StartSessionOperatorAction action) { + Objects.requireNonNull(action, "action is required"); + if (SessionContext.isInternalService() || !SessionContext.hasAuthenticatedCallerContext()) { + throw new IllegalArgumentException("a human control-ui identity is required"); + } + String tenantId = action.scope().tenantId().toString(); + if (!SessionContext.getScopedRoles(tenantId).contains("tenantAdmin")) { + throw new IllegalArgumentException("tenantAdmin authority is required for the target tenant"); + } + UUID actorAccountId = requireCanonicalUuid(SessionContext.getAccountId(), "actor accountId"); + return new StartSessionPreAuthorizationReservationTuple( + net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple + .createHuman(controlPlaneRequestId, actorAccountId, action), + true); + } + + /** Rehydrates only tuple contents; persisted bytes do not establish request authority. */ + public static StartSessionPreAuthorizationReservationTuple fromCanonicalJson(String json) { + return new StartSessionPreAuthorizationReservationTuple( + net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple + .fromCanonicalJson(json), + false); + } + + public String actionFamily() { + return value.actionFamily(); + } + + public String controlPlaneRequestId() { + return value.controlPlaneRequestId(); + } + + public HumanActor actor() { + return new HumanActor(value.actor().accountId()); + } + + public NoAutomationPolicy automationPolicy() { + return NoAutomationPolicy.ABSENT; + } + + public StartSessionOperatorAction action() { + return value.action(); + } + + public boolean isAuthorityDerived() { + return authorityDerived; + } + + /** Validate a stable request key without silently normalizing or changing its identity. */ + public static String requireCanonicalControlPlaneRequestId(String value) { + return net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple + .requireCanonicalControlPlaneRequestId(value); + } + + public String targetOwner() { + return value.targetOwner(); + } + + /** Returns ADR 0047's digest over the seven action-schema grammar fields. */ + public String mutationDigest() { + return value.mutationDigest(); + } + + /** Returns the single shared canonical encoding for ADR 0048's typed tuple. */ + public String canonicalJson() { + return value.canonicalJson(); + } + + public record HumanActor(UUID accountId) { + public HumanActor { + Objects.requireNonNull(accountId, "actor accountId is required"); + if (accountId.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException("actor accountId must not be nil"); + } + } + } + + public enum NoAutomationPolicy { + ABSENT + } + + @Override + public boolean equals(Object other) { + return this == other + || other instanceof StartSessionPreAuthorizationReservationTuple that + && value.equals(that.value); + } + + @Override + public int hashCode() { + return value.hashCode(); + } + + private static UUID requireCanonicalUuid(String value, String fieldName) { + Objects.requireNonNull(value, fieldName + " is required"); + UUID parsed; + try { + parsed = UUID.fromString(value); + } catch (IllegalArgumentException exception) { + throw new IllegalArgumentException(fieldName + " must be a canonical UUID", exception); + } + if (!parsed.toString().equals(value) || parsed.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException(fieldName + " must be a canonical non-nil UUID"); + } + return parsed; + } +} diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/repository/StartSessionPreAuthorizationReservationRepository.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/repository/StartSessionPreAuthorizationReservationRepository.java new file mode 100644 index 0000000000..4c32e3a97c --- /dev/null +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/repository/StartSessionPreAuthorizationReservationRepository.java @@ -0,0 +1,415 @@ +package net.firedevops.firemud.loggingadmin.repository; + +import static net.firedevops.firemud.loggingadmin.jooq.tables.StartSessionPreAuthorizationReservations.START_SESSION_PRE_AUTHORIZATION_RESERVATIONS; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.loggingadmin.jooq.tables.StartSessionPreAuthorizationReservations; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.ClaimState; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.Phase; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.Snapshot; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.State; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationTuple; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.impl.DSL; +import org.springframework.stereotype.Repository; + +/** jOOQ persistence for the single-key StartSession ADR 0048 reservation phase. */ +@Repository +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Injected DSLContext is an internal Spring collaborator.") +public class StartSessionPreAuthorizationReservationRepository { + private static final StartSessionPreAuthorizationReservations TABLE = + START_SESSION_PRE_AUTHORIZATION_RESERVATIONS; + + private final DSLContext dsl; + + public StartSessionPreAuthorizationReservationRepository(DSLContext dsl) { + this.dsl = dsl; + } + + public AcquireResult acquire( + StartSessionPreAuthorizationReservationTuple tuple, + UUID ownerId, + long nowEpochMillis, + long expiresAtEpochMillis) { + requireBoundedClaim(ownerId, nowEpochMillis, expiresAtEpochMillis); + if (!tuple.isAuthorityDerived()) { + throw new IllegalArgumentException( + "initial reservation requires an authority-derived StartSession tuple"); + } + String tupleJson = tuple.canonicalJson(); + String mutationDigest = tuple.mutationDigest(); + return dsl.transactionResult( + configuration -> { + DSLContext tx = DSL.using(configuration); + int inserted = + tx.insertInto(TABLE) + .set(TABLE.CONTROL_PLANE_REQUEST_ID, tuple.controlPlaneRequestId()) + .set(TABLE.PRE_AUTHORIZATION_TUPLE_JSON, tupleJson) + .set(TABLE.MUTATION_DIGEST, mutationDigest) + .set(TABLE.PHASE, Phase.ACCOUNT_AUTHORIZATION.name()) + .set(TABLE.STATE, State.RESERVED.name()) + .set(TABLE.RESERVATION_OWNER_ID, ownerId) + .set(TABLE.RESERVATION_CLAIM_FENCE, 1L) + .set(TABLE.CLAIM_OWNER_ID, ownerId) + .set(TABLE.CLAIM_FENCE, 1L) + .set(TABLE.CLAIM_EXPIRES_AT_EPOCH_MS, expiresAtEpochMillis) + .set(TABLE.CLAIM_STATE, ClaimState.ACTIVE.name()) + .set(TABLE.CREATED_AT_EPOCH_MS, nowEpochMillis) + .set(TABLE.UPDATED_AT_EPOCH_MS, nowEpochMillis) + .onConflict(TABLE.CONTROL_PLANE_REQUEST_ID) + .doNothing() + .execute(); + Record row = lockByRequestId(tx, tuple.controlPlaneRequestId()); + if (row == null) { + throw new IllegalStateException("reservation row was not visible after acquire"); + } + Snapshot snapshot = toSnapshot(row); + requireExactTuple(row, tuple, mutationDigest); + return new AcquireResult(snapshot, inserted == 1); + }); + } + + public Optional find(String controlPlaneRequestId) { + StartSessionPreAuthorizationReservationTuple.requireCanonicalControlPlaneRequestId( + controlPlaneRequestId); + return dsl.selectFrom(TABLE) + .where(TABLE.CONTROL_PLANE_REQUEST_ID.eq(controlPlaneRequestId)) + .fetchOptional(this::toSnapshot); + } + + public Optional findExact(StartSessionPreAuthorizationReservationTuple tuple) { + return find(tuple.controlPlaneRequestId()) + .map( + snapshot -> { + if (!snapshot.tuple().canonicalJson().equals(tuple.canonicalJson()) + || !snapshot.mutationDigest().equals(tuple.mutationDigest())) { + throw new StartSessionPreAuthorizationReservationService + .IdempotencyConflictException(tuple.controlPlaneRequestId()); + } + return snapshot; + }); + } + + public TransitionResult markAuthorizationPending( + StartSessionPreAuthorizationReservationTuple tuple, + String mutationDigest, + UUID ownerId, + long claimFence, + long nowEpochMillis) { + requireClaimOwner(ownerId, claimFence, nowEpochMillis); + return dsl.transactionResult( + configuration -> { + DSLContext tx = DSL.using(configuration); + int updated = + tx.update(TABLE) + .set(TABLE.STATE, State.AUTHORIZATION_PENDING.name()) + .set(TABLE.UPDATED_AT_EPOCH_MS, nowEpochMillis) + .where(TABLE.CONTROL_PLANE_REQUEST_ID.eq(tuple.controlPlaneRequestId())) + .and(TABLE.PRE_AUTHORIZATION_TUPLE_JSON.eq(tuple.canonicalJson())) + .and(TABLE.MUTATION_DIGEST.eq(mutationDigest)) + .and(TABLE.PHASE.eq(Phase.ACCOUNT_AUTHORIZATION.name())) + .and(TABLE.STATE.eq(State.RESERVED.name())) + .and(TABLE.RESERVATION_OWNER_ID.eq(ownerId)) + .and(TABLE.RESERVATION_CLAIM_FENCE.eq(1L)) + .and(TABLE.CLAIM_OWNER_ID.eq(ownerId)) + .and(TABLE.CLAIM_FENCE.eq(claimFence)) + .and(TABLE.CLAIM_STATE.eq(ClaimState.ACTIVE.name())) + .and(TABLE.CLAIM_EXPIRES_AT_EPOCH_MS.gt(nowEpochMillis)) + .execute(); + Record row = lockByRequestId(tx, tuple.controlPlaneRequestId()); + if (row == null) { + throw new StartSessionPreAuthorizationReservationService.StaleReservationClaimException( + tuple.controlPlaneRequestId()); + } + Snapshot snapshot = toSnapshot(row); + requireExactTuple(row, tuple, mutationDigest); + if (updated == 1) { + return new TransitionResult(snapshot, true); + } + if (isCurrentClaim(row, ownerId, claimFence, nowEpochMillis) + && snapshot.phase() == Phase.ACCOUNT_AUTHORIZATION + && snapshot.state() == State.AUTHORIZATION_PENDING) { + return new TransitionResult(snapshot, false); + } + throw new StartSessionPreAuthorizationReservationService.StaleReservationClaimException( + tuple.controlPlaneRequestId()); + }); + } + + public Snapshot renew( + StartSessionPreAuthorizationReservationTuple tuple, + String mutationDigest, + UUID ownerId, + long claimFence, + Phase expectedPhase, + State expectedState, + long nowEpochMillis, + long expiresAtEpochMillis) { + requireClaimOwner(ownerId, claimFence, nowEpochMillis); + Objects.requireNonNull(expectedPhase, "expectedPhase is required"); + Objects.requireNonNull(expectedState, "expectedState is required"); + requireBoundedClaim(ownerId, nowEpochMillis, expiresAtEpochMillis); + return dsl.transactionResult( + configuration -> { + DSLContext tx = DSL.using(configuration); + int updated = + tx.update(TABLE) + .set(TABLE.CLAIM_EXPIRES_AT_EPOCH_MS, expiresAtEpochMillis) + .set(TABLE.UPDATED_AT_EPOCH_MS, nowEpochMillis) + .where(TABLE.CONTROL_PLANE_REQUEST_ID.eq(tuple.controlPlaneRequestId())) + .and(TABLE.PRE_AUTHORIZATION_TUPLE_JSON.eq(tuple.canonicalJson())) + .and(TABLE.MUTATION_DIGEST.eq(mutationDigest)) + .and(TABLE.PHASE.eq(expectedPhase.name())) + .and(TABLE.STATE.eq(expectedState.name())) + .and(TABLE.CLAIM_OWNER_ID.eq(ownerId)) + .and(TABLE.CLAIM_FENCE.eq(claimFence)) + .and(TABLE.CLAIM_STATE.eq(ClaimState.ACTIVE.name())) + .and(TABLE.CLAIM_EXPIRES_AT_EPOCH_MS.gt(nowEpochMillis)) + .execute(); + Record row = lockByRequestId(tx, tuple.controlPlaneRequestId()); + if (row == null) { + throw new StartSessionPreAuthorizationReservationService.StaleReservationClaimException( + tuple.controlPlaneRequestId()); + } + Snapshot snapshot = toSnapshot(row); + requireExactTuple(row, tuple, mutationDigest); + if (updated != 1) { + throw new StartSessionPreAuthorizationReservationService.StaleReservationClaimException( + tuple.controlPlaneRequestId()); + } + return snapshot; + }); + } + + public Snapshot expireClaim( + StartSessionPreAuthorizationReservationTuple tuple, + String mutationDigest, + UUID ownerId, + long claimFence, + Phase expectedPhase, + State expectedState, + long nowEpochMillis) { + requireClaimOwner(ownerId, claimFence, nowEpochMillis); + Objects.requireNonNull(expectedPhase, "expectedPhase is required"); + Objects.requireNonNull(expectedState, "expectedState is required"); + return dsl.transactionResult( + configuration -> { + DSLContext tx = DSL.using(configuration); + int updated = + tx.update(TABLE) + .setNull(TABLE.CLAIM_OWNER_ID) + .set(TABLE.CLAIM_FENCE, TABLE.CLAIM_FENCE.add(1L)) + .set(TABLE.CLAIM_STATE, ClaimState.EXPIRED.name()) + .set(TABLE.UPDATED_AT_EPOCH_MS, nowEpochMillis) + .where(TABLE.CONTROL_PLANE_REQUEST_ID.eq(tuple.controlPlaneRequestId())) + .and(TABLE.PRE_AUTHORIZATION_TUPLE_JSON.eq(tuple.canonicalJson())) + .and(TABLE.MUTATION_DIGEST.eq(mutationDigest)) + .and(TABLE.PHASE.eq(expectedPhase.name())) + .and(TABLE.STATE.eq(expectedState.name())) + .and(TABLE.CLAIM_OWNER_ID.eq(ownerId)) + .and(TABLE.CLAIM_FENCE.eq(claimFence)) + .and(TABLE.CLAIM_STATE.eq(ClaimState.ACTIVE.name())) + .and(TABLE.CLAIM_EXPIRES_AT_EPOCH_MS.le(nowEpochMillis)) + .execute(); + Record row = lockByRequestId(tx, tuple.controlPlaneRequestId()); + if (row == null) { + throw new StartSessionPreAuthorizationReservationService.StaleReservationClaimException( + tuple.controlPlaneRequestId()); + } + Snapshot snapshot = toSnapshot(row); + requireExactTuple(row, tuple, mutationDigest); + if (updated == 1) { + return snapshot; + } + if (isCurrentClaim(row, ownerId, claimFence, nowEpochMillis)) { + throw new StartSessionPreAuthorizationReservationService + .ReservationClaimNotExpiredException(tuple.controlPlaneRequestId()); + } + throw new StartSessionPreAuthorizationReservationService.StaleReservationClaimException( + tuple.controlPlaneRequestId()); + }); + } + + public Optional acquireRecoveryClaim( + StartSessionPreAuthorizationReservationTuple tuple, + UUID recoveryOwnerId, + long nowEpochMillis, + long expiresAtEpochMillis) { + requireBoundedClaim(recoveryOwnerId, nowEpochMillis, expiresAtEpochMillis); + String mutationDigest = tuple.mutationDigest(); + return dsl.transactionResult( + configuration -> { + DSLContext tx = DSL.using(configuration); + Record row = lockByRequestId(tx, tuple.controlPlaneRequestId()); + if (row == null) { + return Optional.empty(); + } + Snapshot snapshot = toSnapshot(row); + requireExactTuple(row, tuple, mutationDigest); + if (snapshot.phase() != Phase.ACCOUNT_AUTHORIZATION + || snapshot.state() != State.AUTHORIZATION_PENDING) { + return Optional.empty(); + } + UUID reservationOwnerId = row.get(TABLE.RESERVATION_OWNER_ID); + String previousClaimState = row.get(TABLE.CLAIM_STATE); + long previousFence = row.get(TABLE.CLAIM_FENCE); + long previousExpiry = row.get(TABLE.CLAIM_EXPIRES_AT_EPOCH_MS); + if (!ClaimState.EXPIRED.name().equals(previousClaimState) + && !(ClaimState.ACTIVE.name().equals(previousClaimState) + && previousExpiry <= nowEpochMillis)) { + return Optional.empty(); + } + long recoveryFence = Math.addExact(previousFence, 1L); + int updated = + tx.update(TABLE) + .set(TABLE.CLAIM_OWNER_ID, recoveryOwnerId) + .set(TABLE.CLAIM_FENCE, recoveryFence) + .set(TABLE.CLAIM_EXPIRES_AT_EPOCH_MS, expiresAtEpochMillis) + .set(TABLE.CLAIM_STATE, ClaimState.ACTIVE.name()) + .set(TABLE.UPDATED_AT_EPOCH_MS, nowEpochMillis) + .where(TABLE.CONTROL_PLANE_REQUEST_ID.eq(tuple.controlPlaneRequestId())) + .and(TABLE.PRE_AUTHORIZATION_TUPLE_JSON.eq(tuple.canonicalJson())) + .and(TABLE.MUTATION_DIGEST.eq(mutationDigest)) + .and(TABLE.PHASE.eq(Phase.ACCOUNT_AUTHORIZATION.name())) + .and(TABLE.STATE.eq(State.AUTHORIZATION_PENDING.name())) + .and(TABLE.CLAIM_FENCE.eq(previousFence)) + .and(TABLE.CLAIM_STATE.eq(previousClaimState)) + .and( + ClaimState.EXPIRED.name().equals(previousClaimState) + ? DSL.trueCondition() + : TABLE.CLAIM_EXPIRES_AT_EPOCH_MS.le(nowEpochMillis)) + .execute(); + if (updated != 1) { + return Optional.empty(); + } + Record updatedRow = lockByRequestId(tx, tuple.controlPlaneRequestId()); + if (updatedRow == null) { + throw new IllegalStateException("recovery claim row disappeared after update"); + } + return Optional.of(new RecoveryClaimResult(toSnapshot(updatedRow), reservationOwnerId)); + }); + } + + private Record lockByRequestId(DSLContext context, String controlPlaneRequestId) { + return context + .selectFrom(TABLE) + .where(TABLE.CONTROL_PLANE_REQUEST_ID.eq(controlPlaneRequestId)) + .forUpdate() + .fetchOne(); + } + + private void requireBoundedClaim(UUID ownerId, long nowEpochMillis, long expiresAtEpochMillis) { + requireClaimOwner(ownerId, 1L, nowEpochMillis); + if (expiresAtEpochMillis <= nowEpochMillis + || expiresAtEpochMillis - nowEpochMillis + > StartSessionPreAuthorizationReservationService.CLAIM_TTL.toMillis()) { + throw new IllegalArgumentException("reservation claim must have a bounded positive expiry"); + } + } + + private void requireClaimOwner(UUID ownerId, long claimFence, long nowEpochMillis) { + if (ownerId == null + || ownerId.equals(new UUID(0L, 0L)) + || claimFence <= 0L + || nowEpochMillis <= 0L) { + throw new IllegalArgumentException("reservation claim identity and time must be positive"); + } + } + + private Snapshot toSnapshot(Record row) { + String requestId = row.get(TABLE.CONTROL_PLANE_REQUEST_ID); + String tupleJson = row.get(TABLE.PRE_AUTHORIZATION_TUPLE_JSON); + String storedDigest = row.get(TABLE.MUTATION_DIGEST); + StartSessionPreAuthorizationReservationTuple tuple; + try { + tuple = StartSessionPreAuthorizationReservationTuple.fromCanonicalJson(tupleJson); + } catch (RuntimeException exception) { + throw new IllegalStateException( + "stored StartSession pre-authorization tuple is malformed for " + requestId, exception); + } + if (!requestId.equals(tuple.controlPlaneRequestId())) { + throw new IllegalStateException( + "stored StartSession tuple key does not match reservation key " + requestId); + } + String recomputedDigest = tuple.mutationDigest(); + if (!recomputedDigest.equals(storedDigest)) { + throw new IllegalStateException( + "stored StartSession mutationDigest does not match its full tuple for " + requestId); + } + Phase phase = enumValue(Phase.class, row.get(TABLE.PHASE), "phase", requestId); + State state = enumValue(State.class, row.get(TABLE.STATE), "state", requestId); + ClaimState claimState = + enumValue(ClaimState.class, row.get(TABLE.CLAIM_STATE), "claimState", requestId); + UUID reservationOwnerId = row.get(TABLE.RESERVATION_OWNER_ID); + UUID currentClaimOwnerId = row.get(TABLE.CLAIM_OWNER_ID); + long originalFence = row.get(TABLE.RESERVATION_CLAIM_FENCE); + long currentFence = row.get(TABLE.CLAIM_FENCE); + long createdAt = row.get(TABLE.CREATED_AT_EPOCH_MS); + long updatedAt = row.get(TABLE.UPDATED_AT_EPOCH_MS); + if (phase != Phase.ACCOUNT_AUTHORIZATION + || (state != State.RESERVED && state != State.AUTHORIZATION_PENDING) + || reservationOwnerId == null + || reservationOwnerId.equals(new UUID(0L, 0L)) + || originalFence != 1L + || currentFence < originalFence + || createdAt <= 0L + || updatedAt <= 0L + || (claimState == ClaimState.ACTIVE + && (currentClaimOwnerId == null || currentClaimOwnerId.equals(new UUID(0L, 0L)))) + || (claimState == ClaimState.EXPIRED + && (currentClaimOwnerId != null || currentFence <= originalFence))) { + throw new IllegalStateException("stored StartSession reservation lifecycle is malformed"); + } + return new Snapshot( + tuple, + storedDigest, + phase, + state, + originalFence, + currentFence, + row.get(TABLE.CLAIM_EXPIRES_AT_EPOCH_MS), + claimState); + } + + private void requireExactTuple( + Record row, StartSessionPreAuthorizationReservationTuple tuple, String mutationDigest) { + if (!tuple.controlPlaneRequestId().equals(row.get(TABLE.CONTROL_PLANE_REQUEST_ID)) + || !tuple.canonicalJson().equals(row.get(TABLE.PRE_AUTHORIZATION_TUPLE_JSON)) + || !tuple.mutationDigest().equals(mutationDigest) + || !mutationDigest.equals(row.get(TABLE.MUTATION_DIGEST))) { + throw new StartSessionPreAuthorizationReservationService.IdempotencyConflictException( + tuple.controlPlaneRequestId()); + } + } + + private boolean isCurrentClaim(Record row, UUID ownerId, long claimFence, long nowEpochMillis) { + return ownerId.equals(row.get(TABLE.CLAIM_OWNER_ID)) + && claimFence == row.get(TABLE.CLAIM_FENCE) + && ClaimState.ACTIVE.name().equals(row.get(TABLE.CLAIM_STATE)) + && row.get(TABLE.CLAIM_EXPIRES_AT_EPOCH_MS) > nowEpochMillis; + } + + private > T enumValue( + Class enumClass, String value, String fieldName, String requestId) { + try { + return Enum.valueOf(enumClass, value); + } catch (IllegalArgumentException exception) { + throw new IllegalStateException( + "stored StartSession reservation " + fieldName + " is invalid for " + requestId, + exception); + } + } + + public record AcquireResult(Snapshot snapshot, boolean created) {} + + public record TransitionResult(Snapshot snapshot, boolean transitioned) {} + + public record RecoveryClaimResult(Snapshot snapshot, UUID reservationOwnerId) {} +} diff --git a/services/logging-admin-service/src/main/resources/db/migration/V2__start_session_pre_authorization_reservations.sql b/services/logging-admin-service/src/main/resources/db/migration/V2__start_session_pre_authorization_reservations.sql new file mode 100644 index 0000000000..d91510fa3f --- /dev/null +++ b/services/logging-admin-service/src/main/resources/db/migration/V2__start_session_pre_authorization_reservations.sql @@ -0,0 +1,27 @@ +CREATE TABLE start_session_pre_authorization_reservations ( + control_plane_request_id VARCHAR(128) PRIMARY KEY, + pre_authorization_tuple_json VARCHAR(8192) NOT NULL, + mutation_digest VARCHAR(64) NOT NULL, + phase VARCHAR(32) NOT NULL + CHECK (phase = 'ACCOUNT_AUTHORIZATION'), + state VARCHAR(40) NOT NULL + CHECK (state IN ('RESERVED', 'AUTHORIZATION_PENDING')), + reservation_owner_id UUID NOT NULL, + reservation_claim_fence BIGINT NOT NULL + CHECK (reservation_claim_fence = 1), + claim_owner_id UUID, + claim_fence BIGINT NOT NULL + CHECK (claim_fence >= reservation_claim_fence), + claim_expires_at_epoch_ms BIGINT NOT NULL + CHECK (claim_expires_at_epoch_ms > 0), + claim_state VARCHAR(16) NOT NULL + CHECK (claim_state IN ('ACTIVE', 'EXPIRED')), + created_at_epoch_ms BIGINT NOT NULL + CHECK (created_at_epoch_ms > 0), + updated_at_epoch_ms BIGINT NOT NULL + CHECK (updated_at_epoch_ms > 0), + CHECK ( + (claim_state = 'ACTIVE' AND claim_owner_id IS NOT NULL) + OR (claim_state = 'EXPIRED' AND claim_owner_id IS NULL) + ) +); diff --git a/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/StartSessionPreAuthorizationReservationPostgresIntegrationTest.java b/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/StartSessionPreAuthorizationReservationPostgresIntegrationTest.java new file mode 100644 index 0000000000..e86be465f8 --- /dev/null +++ b/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/StartSessionPreAuthorizationReservationPostgresIntegrationTest.java @@ -0,0 +1,252 @@ +package net.firedevops.firemud.loggingadmin; + +import static net.firedevops.firemud.loggingadmin.jooq.tables.StartSessionPreAuthorizationReservations.START_SESSION_PRE_AUTHORIZATION_RESERVATIONS; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.ClaimState; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.Phase; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.State; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationTuple; +import net.firedevops.firemud.loggingadmin.repository.StartSessionPreAuthorizationReservationRepository; +import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +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; + +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class StartSessionPreAuthorizationReservationPostgresIntegrationTest { + private static final long NOW_EPOCH_MILLIS = 1_800_000_000_000L; + private static final UUID TENANT_ID = UUID.fromString("ffbe29e3-a8d2-4b7d-a046-cf1af57ae904"); + private static final UUID ACTOR_ID = UUID.fromString("4c5b3e92-f60d-4e3d-8b8f-6d89b28495d8"); + + @Container + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + private DriverManagerDataSource dataSource; + private DSLContext dsl; + private StartSessionPreAuthorizationReservationRepository repository; + + @BeforeEach + void migrateAndCreateRepository() { + dataSource = + new DriverManagerDataSource( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); + Flyway.configure() + .dataSource(dataSource) + .locations("classpath:db/migration") + .cleanDisabled(false) + .load() + .clean(); + Flyway.configure().dataSource(dataSource).locations("classpath:db/migration").load().migrate(); + dsl = DSL.using(dataSource, SQLDialect.POSTGRES); + repository = new StartSessionPreAuthorizationReservationRepository(dsl); + } + + @AfterEach + void clearAuthenticatedContext() { + SessionContext.clear(); + } + + @Test + void concurrentExactAcquiresPersistOneDurableReservationOwner() throws Exception { + StartSessionPreAuthorizationReservationTuple tuple = + tuple("postgres-concurrent-01", "same action"); + int callerCount = 8; + ExecutorService executor = Executors.newFixedThreadPool(callerCount); + CountDownLatch ready = new CountDownLatch(callerCount); + CountDownLatch start = new CountDownLatch(1); + List> futures = + new ArrayList<>(); + try { + for (int index = 0; index < callerCount; index++) { + futures.add( + executor.submit( + () -> { + ready.countDown(); + if (!start.await(5, TimeUnit.SECONDS)) { + throw new IllegalStateException("concurrent acquire gate timed out"); + } + return acquire(tuple, UUID.randomUUID()); + })); + } + assertThat(ready.await(5, TimeUnit.SECONDS)).isTrue(); + start.countDown(); + + List results = + new ArrayList<>(); + for (Future future : + futures) { + results.add(future.get(10, TimeUnit.SECONDS)); + } + + assertThat(results) + .filteredOn(StartSessionPreAuthorizationReservationRepository.AcquireResult::created) + .hasSize(1); + assertThat(results) + .allSatisfy(result -> assertThat(result.snapshot().tuple()).isEqualTo(tuple)); + assertThat(dsl.fetchCount(START_SESSION_PRE_AUTHORIZATION_RESERVATIONS)).isEqualTo(1); + } finally { + executor.shutdownNow(); + } + } + + @Test + void sameRequestIdWithChangedTupleConflictsAndFullTupleIsPersisted() { + StartSessionPreAuthorizationReservationTuple original = + tuple("postgres-conflict-02", "same action"); + acquire(original, UUID.randomUUID()); + StartSessionPreAuthorizationReservationTuple changed = + tuple("postgres-conflict-02", "changed audit reason"); + + assertThatThrownBy(() -> acquire(changed, UUID.randomUUID())) + .isInstanceOf( + StartSessionPreAuthorizationReservationService.IdempotencyConflictException.class); + + String storedTuple = + dsl.fetchOne( + "SELECT pre_authorization_tuple_json FROM start_session_pre_authorization_reservations " + + "WHERE control_plane_request_id = ?", + original.controlPlaneRequestId()) + .get(0, String.class); + assertThat(storedTuple) + .contains(ACTOR_ID.toString()) + .contains("\"ownerService\":\"game-session-service\"") + .contains("\"expectedVersion\":{\"presence\":\"ABSENT\"}") + .contains("\"clientIp\":{\"presence\":\"ABSENT\"}"); + } + + @Test + void expiryRecoveryFencesStaleOwnerAndCannotInventTerminalOutcome() { + StartSessionPreAuthorizationReservationTuple tuple = + tuple("postgres-recovery-03", "recovery fixture"); + UUID originalOwner = UUID.randomUUID(); + repository.acquire(tuple, originalOwner, NOW_EPOCH_MILLIS, NOW_EPOCH_MILLIS + 30_000L); + + var firstTransition = + repository.markAuthorizationPending( + tuple, tuple.mutationDigest(), originalOwner, 1L, NOW_EPOCH_MILLIS + 1_000L); + assertThat(firstTransition.transitioned()).isTrue(); + assertThat(firstTransition.snapshot().state()).isEqualTo(State.AUTHORIZATION_PENDING); + var duplicateTransition = + repository.markAuthorizationPending( + tuple, tuple.mutationDigest(), originalOwner, 1L, NOW_EPOCH_MILLIS + 1_000L); + assertThat(duplicateTransition.transitioned()).isFalse(); + + var expired = + repository.expireClaim( + tuple, + tuple.mutationDigest(), + originalOwner, + 1L, + Phase.ACCOUNT_AUTHORIZATION, + State.AUTHORIZATION_PENDING, + NOW_EPOCH_MILLIS + 30_000L); + assertThat(expired.claimState()).isEqualTo(ClaimState.EXPIRED); + assertThat(expired.claimFence()).isEqualTo(2L); + assertThat(expired.reservationClaimFence()).isEqualTo(1L); + assertThat(expired.state()).isEqualTo(State.AUTHORIZATION_PENDING); + + assertThatThrownBy( + () -> + repository.renew( + tuple, + tuple.mutationDigest(), + originalOwner, + 1L, + Phase.ACCOUNT_AUTHORIZATION, + State.AUTHORIZATION_PENDING, + NOW_EPOCH_MILLIS + 30_001L, + NOW_EPOCH_MILLIS + 60_001L)) + .isInstanceOf( + StartSessionPreAuthorizationReservationService.StaleReservationClaimException.class); + + UUID recoveryOwner = UUID.randomUUID(); + var recovery = + repository + .acquireRecoveryClaim( + tuple, recoveryOwner, NOW_EPOCH_MILLIS + 30_001L, NOW_EPOCH_MILLIS + 60_001L) + .orElseThrow(); + assertThat(recovery.reservationOwnerId()).isEqualTo(originalOwner); + assertThat(recovery.snapshot().claimFence()).isEqualTo(3L); + assertThat(recovery.snapshot().reservationClaimFence()).isEqualTo(1L); + assertThat(recovery.snapshot().claimState()).isEqualTo(ClaimState.ACTIVE); + assertThat(recovery.snapshot().state()).isEqualTo(State.AUTHORIZATION_PENDING); + assertThat( + repository.acquireRecoveryClaim( + tuple, UUID.randomUUID(), NOW_EPOCH_MILLIS + 30_002L, NOW_EPOCH_MILLIS + 60_002L)) + .isEmpty(); + + var recoveredRecord = repository.findExact(tuple).orElseThrow(); + assertThat(recoveredRecord.phase()).isEqualTo(Phase.ACCOUNT_AUTHORIZATION); + assertThat(recoveredRecord.state()).isEqualTo(State.AUTHORIZATION_PENDING); + assertThat(recoveredRecord.reservationClaimFence()).isEqualTo(1L); + assertThat(recoveredRecord.claimFence()).isEqualTo(3L); + assertThat(State.values()).containsExactly(State.RESERVED, State.AUTHORIZATION_PENDING); + } + + @Test + void lookupRecomputesDigestAndRejectsCorruptedStoredEvidence() { + StartSessionPreAuthorizationReservationTuple tuple = + tuple("postgres-integrity-04", "integrity fixture"); + acquire(tuple, UUID.randomUUID()); + dsl.execute( + "UPDATE start_session_pre_authorization_reservations SET mutation_digest = ? " + + "WHERE control_plane_request_id = ?", + "0".repeat(64), + tuple.controlPlaneRequestId()); + + assertThatThrownBy(() -> repository.find(tuple.controlPlaneRequestId())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("mutationDigest"); + } + + private StartSessionPreAuthorizationReservationRepository.AcquireResult acquire( + StartSessionPreAuthorizationReservationTuple tuple, UUID ownerId) { + return repository.acquire(tuple, ownerId, NOW_EPOCH_MILLIS, NOW_EPOCH_MILLIS + 30_000L); + } + + private static StartSessionPreAuthorizationReservationTuple tuple( + String requestId, String auditReason) { + SessionContext.setContext( + ACTOR_ID.toString(), + List.of(), + Map.of(TENANT_ID.toString(), List.of("tenantAdmin")), + false, + null, + null); + StartSessionOperatorAction action = + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(TENANT_ID, "world-runtime"), + new StartSessionOperatorAction.Target( + 29L, UUID.fromString("be78a8de-a113-48c4-a247-39e3505aed8c")), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation(StartSessionOperatorAction.ClientIp.absent()), + auditReason); + return StartSessionPreAuthorizationReservationTuple.fromCurrentTenantAdmin(requestId, action); + } +} diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/operator/StartSessionPreAuthorizationReservationServiceTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/operator/StartSessionPreAuthorizationReservationServiceTest.java new file mode 100644 index 0000000000..6f000f80c8 --- /dev/null +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/operator/StartSessionPreAuthorizationReservationServiceTest.java @@ -0,0 +1,164 @@ +package net.firedevops.firemud.loggingadmin.operator; + +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.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.Acquisition; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.ClaimState; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.Phase; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.RecoveryAcquisition; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.Snapshot; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.State; +import net.firedevops.firemud.loggingadmin.repository.StartSessionPreAuthorizationReservationRepository; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; + +class StartSessionPreAuthorizationReservationServiceTest { + private static final long NOW_EPOCH_MILLIS = 1_800_000_000_000L; + private static final UUID TENANT_ID = UUID.fromString("3d3c5ca5-6d43-4db6-821d-8a0de883a467"); + private static final UUID ACTOR_ID = UUID.fromString("863843ee-f00a-4905-a9ad-11f706f1b693"); + private final StartSessionPreAuthorizationReservationRepository repository = + mock(StartSessionPreAuthorizationReservationRepository.class); + private final Clock clock = Clock.fixed(Instant.ofEpochMilli(NOW_EPOCH_MILLIS), ZoneOffset.UTC); + private final StartSessionPreAuthorizationReservationService service = + new StartSessionPreAuthorizationReservationService(repository, clock); + + @AfterEach + void clearAuthenticatedContext() { + SessionContext.clear(); + } + + @Test + void firstAcquisitionGetsOneBoundedClaimAndExactDuplicateGetsNoClaim() { + StartSessionPreAuthorizationReservationTuple tuple = tuple("service-unit-01"); + Snapshot initial = snapshot(tuple, State.RESERVED, 1L, 1L, ClaimState.ACTIVE); + when(repository.acquire(any(), any(), eq(NOW_EPOCH_MILLIS), eq(NOW_EPOCH_MILLIS + 30_000L))) + .thenReturn( + new StartSessionPreAuthorizationReservationRepository.AcquireResult(initial, true)) + .thenReturn( + new StartSessionPreAuthorizationReservationRepository.AcquireResult(initial, false)); + + Acquisition first = service.acquire(tuple); + Acquisition duplicate = service.acquire(tuple); + + assertThat(first.newlyAcquired()).isTrue(); + assertThat(first.claim()).isNotNull(); + assertThat(first.claim().claimFence()).isEqualTo(1L); + assertThat(duplicate.newlyAcquired()).isFalse(); + assertThat(duplicate.claim()).isNull(); + verify(repository, org.mockito.Mockito.times(2)) + .acquire(any(), any(), eq(NOW_EPOCH_MILLIS), eq(NOW_EPOCH_MILLIS + 30_000L)); + } + + @Test + void parsedTupleCannotBeUsedAsAnInitialReservationAuthorityAssertion() { + StartSessionPreAuthorizationReservationTuple parsed = + StartSessionPreAuthorizationReservationTuple.fromCanonicalJson( + tuple("service-unit-02").canonicalJson()); + + assertThat(parsed.isAuthorityDerived()).isFalse(); + assertThatThrownBy(() -> service.acquire(parsed)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("actor derived"); + } + + @Test + void expiredPendingClaimCanOnlyBeReacquiredAsReadOnlyRecoveryClaim() { + StartSessionPreAuthorizationReservationTuple tuple = tuple("service-unit-03"); + Snapshot recovered = snapshot(tuple, State.AUTHORIZATION_PENDING, 1L, 3L, ClaimState.ACTIVE); + when(repository.acquireRecoveryClaim( + eq(tuple), any(), eq(NOW_EPOCH_MILLIS), eq(NOW_EPOCH_MILLIS + 30_000L))) + .thenReturn( + Optional.of( + new StartSessionPreAuthorizationReservationRepository.RecoveryClaimResult( + recovered, UUID.fromString("6e0ef777-8661-4139-80eb-904b75de5860")))); + + Optional acquisition = service.acquireAuthorizationRecoveryClaim(tuple); + + assertThat(acquisition).isPresent(); + assertThat(acquisition.orElseThrow().claim().isRecoveryLookupOnly()).isTrue(); + assertThat(acquisition.orElseThrow().snapshot().reservationClaimFence()).isEqualTo(1L); + assertThat(acquisition.orElseThrow().snapshot().claimFence()).isEqualTo(3L); + assertThat(acquisition.orElseThrow().snapshot().state()).isEqualTo(State.AUTHORIZATION_PENDING); + assertThat(acquisition.orElseThrow().claim().claimEvidence().reservationClaimFence()) + .isEqualTo(1L); + assertThat(acquisition.orElseThrow().claim().claimEvidence().currentClaimFence()).isEqualTo(3L); + assertThatThrownBy(() -> service.markAuthorizationPending(acquisition.orElseThrow().claim())) + .isInstanceOf( + StartSessionPreAuthorizationReservationService.StaleReservationClaimException.class); + } + + @Test + void phaseQualifiedStateModelHasNoSyntheticTerminalOutcome() { + assertThat(State.values()).containsExactly(State.RESERVED, State.AUTHORIZATION_PENDING); + assertThat(Phase.values()).containsExactly(Phase.ACCOUNT_AUTHORIZATION); + } + + @Test + void annotationConfigContextSelectsRepositoryConstructorWithoutDatabase() { + AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); + context.registerBean(StartSessionPreAuthorizationReservationRepository.class, () -> repository); + context.register(StartSessionPreAuthorizationReservationService.class); + + try { + context.refresh(); + + assertThat(context.getBean(StartSessionPreAuthorizationReservationService.class)).isNotNull(); + } finally { + context.close(); + } + } + + private static Snapshot snapshot( + StartSessionPreAuthorizationReservationTuple tuple, + State state, + long reservationFence, + long currentFence, + ClaimState claimState) { + return new Snapshot( + tuple, + tuple.mutationDigest(), + Phase.ACCOUNT_AUTHORIZATION, + state, + reservationFence, + currentFence, + NOW_EPOCH_MILLIS + 30_000L, + claimState); + } + + private static StartSessionPreAuthorizationReservationTuple tuple(String requestId) { + SessionContext.setContext( + ACTOR_ID.toString(), + List.of(), + Map.of(TENANT_ID.toString(), List.of("tenantAdmin")), + false, + null, + null); + StartSessionOperatorAction action = + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(TENANT_ID, "world-runtime"), + new StartSessionOperatorAction.Target( + 17L, UUID.fromString("2a9a4d47-a544-4984-bbc4-8e85f84116e4")), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation(StartSessionOperatorAction.ClientIp.absent()), + "unit-test StartSession prerequisite"); + return StartSessionPreAuthorizationReservationTuple.fromCurrentTenantAdmin(requestId, action); + } +} diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/operator/StartSessionPreAuthorizationReservationTupleTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/operator/StartSessionPreAuthorizationReservationTupleTest.java new file mode 100644 index 0000000000..85c8e3a164 --- /dev/null +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/operator/StartSessionPreAuthorizationReservationTupleTest.java @@ -0,0 +1,171 @@ +package net.firedevops.firemud.loggingadmin.operator; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionOperatorActionCodec; +import net.firedevops.firemud.common.security.SessionContext; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; + +class StartSessionPreAuthorizationReservationTupleTest { + private static final UUID TENANT_ID = UUID.fromString("9f8f06b4-36e5-4d11-9c2a-5adfd7f41531"); + private static final UUID ACTOR_ID = UUID.fromString("a4f5f4eb-8243-4d42-903a-33495456a622"); + + @AfterEach + void clearAuthenticatedContext() { + SessionContext.clear(); + } + + @Test + void createsCanonicalHumanOnlyTupleFromCurrentTenantAdminAndPreservesAbsence() { + setTenantAdminContext(TENANT_ID, ACTOR_ID); + StartSessionOperatorAction action = action(StartSessionOperatorAction.ClientIp.absent()); + + StartSessionPreAuthorizationReservationTuple tuple = + StartSessionPreAuthorizationReservationTuple.fromCurrentTenantAdmin( + "start-session-request-01", action); + String canonicalJson = tuple.canonicalJson(); + + assertThat(tuple.actor().accountId()).isEqualTo(ACTOR_ID); + assertThat(tuple.isAuthorityDerived()).isTrue(); + assertThat(tuple.automationPolicy()) + .isEqualTo(StartSessionPreAuthorizationReservationTuple.NoAutomationPolicy.ABSENT); + assertThat(tuple.targetOwner()).isEqualTo(StartSessionOperatorAction.OWNER_SERVICE); + assertThat(tuple.mutationDigest()) + .isEqualTo(StartSessionOperatorActionCodec.mutationDigest(action)); + assertThat(canonicalJson) + .contains("\"requestIdentityKind\":\"controlPlaneRequestId\"") + .contains("\"targetOwner\":{\"ownerService\":\"game-session-service\"}") + .contains("\"expectedVersion\":{\"presence\":\"ABSENT\"}") + .contains("\"clientIp\":{\"presence\":\"ABSENT\"}") + .contains("\"automationPolicy\":{\"presence\":\"ABSENT\"}") + .doesNotContain("authorityDerived"); + StartSessionPreAuthorizationReservationTuple rehydrated = + StartSessionPreAuthorizationReservationTuple.fromCanonicalJson(canonicalJson); + assertThat(rehydrated).isEqualTo(tuple); + assertThat(rehydrated.isAuthorityDerived()).isFalse(); + assertThat( + net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple + .fromCanonicalJson(canonicalJson) + .canonicalJson()) + .isEqualTo(canonicalJson); + } + + @Test + void preservesPresentClientIpAsASeparateTypedPresenceValue() { + setTenantAdminContext(TENANT_ID, ACTOR_ID); + StartSessionOperatorAction action = + action(StartSessionOperatorAction.ClientIp.of("203.0.113.8")); + + StartSessionPreAuthorizationReservationTuple tuple = + StartSessionPreAuthorizationReservationTuple.fromCurrentTenantAdmin( + "start-session-request-02", action); + + assertThat(tuple.canonicalJson()) + .contains("\"clientIp\":{\"presence\":\"PRESENT\",\"value\":\"203.0.113.8\"}"); + assertThat( + StartSessionPreAuthorizationReservationTuple.fromCanonicalJson(tuple.canonicalJson())) + .isEqualTo(tuple); + } + + @Test + void rejectsMissingHumanAuthorityAndDoesNotAcceptOtherRoleAsTenantAdmin() { + StartSessionOperatorAction action = action(StartSessionOperatorAction.ClientIp.absent()); + SessionContext.setContext(ACTOR_ID.toString(), List.of(), Map.of(), false, null, null); + + assertThatThrownBy( + () -> + StartSessionPreAuthorizationReservationTuple.fromCurrentTenantAdmin( + "start-session-request-03", action)) + .isInstanceOf(IllegalArgumentException.class); + + SessionContext.setContext( + ACTOR_ID.toString(), + List.of(), + Map.of(TENANT_ID.toString(), List.of("moderator")), + false, + null, + null); + assertThatThrownBy( + () -> + StartSessionPreAuthorizationReservationTuple.fromCurrentTenantAdmin( + "start-session-request-03", action)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void rejectsInternalOrWrongTenantAuthority() { + StartSessionOperatorAction action = action(StartSessionOperatorAction.ClientIp.absent()); + SessionContext.setContext( + ACTOR_ID.toString(), + List.of(), + Map.of(TENANT_ID.toString(), List.of("tenantAdmin")), + true, + "logging-admin-service", + "instance-1"); + assertThatThrownBy( + () -> + StartSessionPreAuthorizationReservationTuple.fromCurrentTenantAdmin( + "start-session-request-04", action)) + .isInstanceOf(IllegalArgumentException.class); + + SessionContext.setContext( + ACTOR_ID.toString(), + List.of(), + Map.of(UUID.randomUUID().toString(), List.of("tenantAdmin")), + false, + null, + null); + assertThatThrownBy( + () -> + StartSessionPreAuthorizationReservationTuple.fromCurrentTenantAdmin( + "start-session-request-04", action)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void rejectsNonCanonicalAndUnsupportedPersistedTupleShapes() { + setTenantAdminContext(TENANT_ID, ACTOR_ID); + String canonicalJson = + StartSessionPreAuthorizationReservationTuple.fromCurrentTenantAdmin( + "start-session-request-05", action(StartSessionOperatorAction.ClientIp.absent())) + .canonicalJson(); + + assertThatThrownBy( + () -> + StartSessionPreAuthorizationReservationTuple.fromCanonicalJson(" " + canonicalJson)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + StartSessionPreAuthorizationReservationTuple.fromCanonicalJson( + canonicalJson.replace("\"presence\":\"ABSENT\"", "\"presence\":\"NULL\""))) + .isInstanceOf(IllegalArgumentException.class); + } + + private static void setTenantAdminContext(UUID tenantId, UUID actorId) { + SessionContext.setContext( + actorId.toString(), + List.of(), + Map.of(tenantId.toString(), List.of("tenantAdmin")), + false, + null, + null); + } + + private static StartSessionOperatorAction action(StartSessionOperatorAction.ClientIp clientIp) { + return new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(TENANT_ID, "world-runtime"), + new StartSessionOperatorAction.Target( + 91L, UUID.fromString("36aa9ce5-0ebc-4c14-9f6b-d160edc6059a")), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation(clientIp), + "approved StartSession prerequisite"); + } +} From 62f504bd40ffba7ab724730a191e437e976083b5 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 19:21:19 +1300 Subject: [PATCH 3/3] Fix authorization physical proof fixtures and validation hygiene --- dev-tools/tests/test_start_session_action_digest.py | 7 +++---- ...trolUiCommittedIssuanceRepositoryIntegrationTest.java | 2 +- .../common/security/ControlUiJwtProfileValidator.java | 1 - .../GameSessionAccountDelegationRegistryRecord.java | 1 - .../security/PlayerBootstrapJwtProfileValidator.java | 1 - .../security/ControlUiJwtProfileValidatorTest.java | 1 - ...eAuthorizationReservationPostgresIntegrationTest.java | 9 ++++++++- 7 files changed, 12 insertions(+), 10 deletions(-) diff --git a/dev-tools/tests/test_start_session_action_digest.py b/dev-tools/tests/test_start_session_action_digest.py index 93a94b9a2e..c97b109ce0 100644 --- a/dev-tools/tests/test_start_session_action_digest.py +++ b/dev-tools/tests/test_start_session_action_digest.py @@ -9,7 +9,6 @@ from dataclasses import dataclass from pathlib import Path - ROOT = Path(__file__).resolve().parents[2] FIXTURE = ( ROOT @@ -62,7 +61,7 @@ def parse_json(raw): def scalar_string(value, byte_limit=4_096): if not isinstance(value, str): - raise ValueError("string value required") + raise TypeError("string value required") if any(0xD800 <= ord(character) <= 0xDFFF for character in value): raise ValueError("malformed Unicode") normalized = unicodedata.normalize("NFC", value) @@ -147,7 +146,7 @@ def encoded_value(value, depth=0): def ordered_members(value, declared_order, optional=()): if not isinstance(value, RawObject): - raise ValueError("object value required") + raise TypeError("object value required") if len(value.members) > 16: raise ValueError("object exceeds its member limit") members = {} @@ -262,7 +261,7 @@ def test_action_vectors(self): with self.subTest(vector=vector["name"]): raw = raw_vector_bytes(vector) if not vector["accepted"]: - with self.assertRaises((ValueError, UnicodeError, json.JSONDecodeError)): + with self.assertRaises((TypeError, ValueError, UnicodeError, json.JSONDecodeError)): action_preimage(raw) continue preimage = action_preimage(raw) diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountControlUiCommittedIssuanceRepositoryIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountControlUiCommittedIssuanceRepositoryIntegrationTest.java index 970109378e..4723996011 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountControlUiCommittedIssuanceRepositoryIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountControlUiCommittedIssuanceRepositoryIntegrationTest.java @@ -440,7 +440,7 @@ private static final class Context { () -> { String suffix = UUID.randomUUID().toString(); Account account = new Account(); - account.setUsername("control-ui-committed-" + suffix); + account.setUsername("cui-" + suffix.replace("-", "")); account.setEmail("control-ui-committed-" + suffix + "@example.test"); account.setPasswordHash("test-only-account-password-hash"); Account saved = new AccountRepository(transactionDsl).save(account); diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/security/ControlUiJwtProfileValidator.java b/services/common-security/src/main/java/net/firedevops/firemud/common/security/ControlUiJwtProfileValidator.java index 6fdfb4fc5e..051e4009be 100644 --- a/services/common-security/src/main/java/net/firedevops/firemud/common/security/ControlUiJwtProfileValidator.java +++ b/services/common-security/src/main/java/net/firedevops/firemud/common/security/ControlUiJwtProfileValidator.java @@ -99,4 +99,3 @@ private static void requireAtMost(int entries, int maximum) { } } } - diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/security/GameSessionAccountDelegationRegistryRecord.java b/services/common-security/src/main/java/net/firedevops/firemud/common/security/GameSessionAccountDelegationRegistryRecord.java index d75869b238..17584d3171 100644 --- a/services/common-security/src/main/java/net/firedevops/firemud/common/security/GameSessionAccountDelegationRegistryRecord.java +++ b/services/common-security/src/main/java/net/firedevops/firemud/common/security/GameSessionAccountDelegationRegistryRecord.java @@ -888,4 +888,3 @@ public InvalidRecordException(String message) { } } } - diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/security/PlayerBootstrapJwtProfileValidator.java b/services/common-security/src/main/java/net/firedevops/firemud/common/security/PlayerBootstrapJwtProfileValidator.java index 4eab9411e3..86d11650b4 100644 --- a/services/common-security/src/main/java/net/firedevops/firemud/common/security/PlayerBootstrapJwtProfileValidator.java +++ b/services/common-security/src/main/java/net/firedevops/firemud/common/security/PlayerBootstrapJwtProfileValidator.java @@ -36,4 +36,3 @@ public static void validateClaims(Map claims) { } } } - diff --git a/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/ControlUiJwtProfileValidatorTest.java b/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/ControlUiJwtProfileValidatorTest.java index f33d68c204..b721526a86 100644 --- a/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/ControlUiJwtProfileValidatorTest.java +++ b/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/ControlUiJwtProfileValidatorTest.java @@ -216,4 +216,3 @@ private static void assertInvalidAtCap(Map claims, int cap) { .hasNoCause(); } } - diff --git a/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/StartSessionPreAuthorizationReservationPostgresIntegrationTest.java b/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/StartSessionPreAuthorizationReservationPostgresIntegrationTest.java index e86be465f8..044c11d89a 100644 --- a/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/StartSessionPreAuthorizationReservationPostgresIntegrationTest.java +++ b/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/StartSessionPreAuthorizationReservationPostgresIntegrationTest.java @@ -38,6 +38,7 @@ @SuppressWarnings("resource") class StartSessionPreAuthorizationReservationPostgresIntegrationTest { private static final long NOW_EPOCH_MILLIS = 1_800_000_000_000L; + private static final Map FLYWAY_PLACEHOLDERS = Map.of("serviceSchema", "public"); private static final UUID TENANT_ID = UUID.fromString("ffbe29e3-a8d2-4b7d-a046-cf1af57ae904"); private static final UUID ACTOR_ID = UUID.fromString("4c5b3e92-f60d-4e3d-8b8f-6d89b28495d8"); @@ -57,10 +58,16 @@ void migrateAndCreateRepository() { Flyway.configure() .dataSource(dataSource) .locations("classpath:db/migration") + .placeholders(FLYWAY_PLACEHOLDERS) .cleanDisabled(false) .load() .clean(); - Flyway.configure().dataSource(dataSource).locations("classpath:db/migration").load().migrate(); + Flyway.configure() + .dataSource(dataSource) + .locations("classpath:db/migration") + .placeholders(FLYWAY_PLACEHOLDERS) + .load() + .migrate(); dsl = DSL.using(dataSource, SQLDialect.POSTGRES); repository = new StartSessionPreAuthorizationReservationRepository(dsl); }