Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
# 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.

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).
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
310 changes: 310 additions & 0 deletions dev-tools/tests/test_start_session_action_digest.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,310 @@
#!/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 TypeError("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 TypeError("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((TypeError, 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()
1 change: 1 addition & 0 deletions services/account-service/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
Loading
Loading