Skip to content
Merged
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
Expand Up @@ -8,6 +8,8 @@ Account owns platform identity, hosted Creator Party/operator and terms currentn

## Implementation Status

Account V29 now persists an immutable, unique, non-nil `account_uuid` with provenance and the unchanged numeric source-row id. The repository writes or reads back that identity for Account rows. This is a storage prerequisite only: REST/gRPC authentication outputs and downstream session carriers do not yet use the UUID. Focused repository and retained-row migration integration cases are present, but local PostgreSQL execution is unavailable while Docker is disabled; [ADR 0020](../../decisions/adr-0020-scoped-domain-and-operational-identifiers.md) remains the identifier authority.

The account lifecycle state machine, global deletion preconditions, account-scoped versus tenant-scoped portable-data export split, separate safety-restriction lifecycles, hosting-billing authority, and future-marketplace `purchase_entitlement` substrate are the canonical target design. The current service has live identity/authentication, profile, external-link persistence, recovery/verification, payment, subscription, notification, and virtual-currency foundations, but lifecycle state transitions, genuine provider authentication, cross-service export, retained-record handling, complete account lock/platform-ban enforcement, purchased-entitlement fulfillment, and complete billing/subscription follow-through remain partial. The current account export returns only Account and profile rows, the tenant export includes excessive global Account fields, and successful deletion immediately removes Account-owned rows including payment transactions. Those behaviors directly conflict with [ADR 0050](../../decisions/adr-0050-versioned-export-retention-and-erasure-policy.md) and the bounded erasure workflow below.

Account V22/V23 rewrite retained email values to canonical form and validate a canonical-email check, but compatibility with older binaries is unproved; the retained-data and rollout proof gap is tracked in [Shared Runtime Contracts and Persistence](../../../project-management/implementation-tracking/shared-runtime-contracts-and-persistence.md#unit-5b-persistence-review-consequences).
Expand Down Expand Up @@ -57,7 +59,7 @@ The target capacity retry contract uses stable outer `(tenantId, requestId, admi

## Data Model

- `account` table stores username, password hash, email, and status flags for the global platform account.
- `account` table stores username, password hash, email, and status flags for the global platform account, with an immutable unique non-nil `account_uuid`, its provenance, and the unchanged numeric source-row id added by V29. This is Account-local storage identity only; authentication outputs and downstream session carriers do not yet use the UUID.
- Target `profile` relationships are tenant-scoped and keyed exactly by `{accountId, tenantId}`; profile reads/writes require the corresponding membership and exact tenant filter. Any legacy account-only profile shape is implementation drift and must not authorize or expose a tenant relationship.
- Target `achievement` relationships are tenant-scoped and keyed exactly by `{tenantId, accountId, achievementId}` (with any additional version/effect identity carried separately); the legacy “account and game” wording/shape is implementation drift because `game` is not an authority identifier.
- Target `external_account` records link a server-verified canonical `{provider, issuer, subject}` to one global platform account without tenant scope. The current tenant-scoped, caller-asserted row shape is implementation drift.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ The service runtime model assumes replaceable workers, not authoritative in-proc

The sections below define the target-state runtime contract. Current implementation and proof status is:

- Game Session V11 adds nullable `gameplay_command.account_uuid` storage and repository round-trip mapping alongside the retained numeric `account_id`. Historical commands remain without an inferred UUID, and no producer or session carrier supplies or consumes this field yet. The focused migration and repository PostgreSQL cases are present but skip locally while Docker is disabled; Account UUID ownership remains in [Account Runtime and Data](../account-service/runtime-and-data.md) under [ADR 0020](../../decisions/adr-0020-scoped-domain-and-operational-identifiers.md).

- The current effective-settings HTTP read is admitted by the service-wide `PRIVILEGED` role requirement, whose shared classifier accepts any global privileged role or any tenant-scoped `tenantAdmin`/`moderator` claim. `EffectiveSettingsController` then trusts query tenant/game selectors and session ids: it can synthesize a requested tenant scope without binding it to the caller's scoped role, or resolve a persisted session without checking that its tenant is authorized by the caller. The current controller/integration tests do not prove denial of a tenant-A caller reading tenant-B settings.
- **Target effective-settings boundary:** keep this as a read-only operator surface but make authorization route-aware. Bind a tenant-scoped role to the exact target tenant and require persisted session tenant ownership/equality; allow a global `platformAdmin` branch to select a tenant only with current operator authorization, target-tenant generation, and `privileged_control`. Reject ambiguous/missing target authority, tenant/session mismatches, and unavailable owner/session evidence before invoking any resolver. The negative proof must cover scoped cross-tenant synthetic and persisted-session reads and the global branch without privileged control.
- Script pin/epoch rollout remains partial: the authoritative `{scriptPatchVersion, scriptPinEpoch, controlPlaneRequestId}` owner read, CAS-backed pin transition, and instance-bound Automation admission epoch validation are live. Local instance-scoped Automation admission, duplicate replay, durable tick staging/replay, and final Game Session execution now compare the complete tuple; the live ledger is still limited to current atomic request/result rows, and bounded rollout-history readback plus complete source/target remote command identity and final-effect fencing remain gaps. See the [canonical runtime-execution owner](../../system-architecture-scripting-runtime-execution.md#normative-target-contract) and the [Game Session runtime and tick coordination tracker](../../../project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md#active-gaps).
Expand Down

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
package net.firedevops.firemud.accountservice.entity;

import java.util.UUID;
import lombok.Data;

@Data
public class Account {
private Long id;
private UUID accountUuid;
private AccountIdentityProvenance accountUuidProvenance;
private Long accountUuidSourceNumericId;
private String username;
private String email;
private String passwordHash;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package net.firedevops.firemud.accountservice.entity;

public enum AccountIdentityProvenance {
ACCOUNT_V29_MIGRATION,
ACCOUNT_REPOSITORY_INSERT,
ACCOUNT_DATABASE_INSERT;

public static AccountIdentityProvenance fromStorageValue(String value) {
if (value == null) {
throw new IllegalStateException("Account UUID provenance must not be null");
}
try {
return AccountIdentityProvenance.valueOf(value);
} catch (IllegalArgumentException exception) {
throw new IllegalStateException("Unknown Account UUID provenance: " + value, exception);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,11 @@
import static net.firedevops.firemud.accountservice.jooq.Tables.ACCOUNTS;

import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.util.Objects;
import java.util.Optional;
import java.util.UUID;
import net.firedevops.firemud.accountservice.entity.Account;
import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance;
import net.firedevops.firemud.accountservice.jooq.tables.records.AccountsRecord;
import net.firedevops.firemud.common.EmailCanonicalization;
import org.jooq.DSLContext;
Expand All @@ -26,6 +29,14 @@ public Optional<Account> findById(Long id) {
dsl.selectFrom(ACCOUNTS).where(ACCOUNTS.ID.eq(id)).fetchOne(this::toEntity));
}

public Optional<Account> findByAccountUuid(UUID accountUuid) {
Objects.requireNonNull(accountUuid, "accountUuid must not be null");
return Optional.ofNullable(
dsl.selectFrom(ACCOUNTS)
.where(ACCOUNTS.ACCOUNT_UUID.eq(accountUuid))
.fetchOne(this::toEntity));
}

public Optional<Account> findByUsername(String username) {
return Optional.ofNullable(
dsl.selectFrom(ACCOUNTS).where(ACCOUNTS.USERNAME.eq(username)).fetchOne(this::toEntity));
Expand All @@ -41,33 +52,62 @@ public Optional<Account> findByEmail(String email) {
public Account save(Account entity) {
entity.setEmail(EmailCanonicalization.normalize(entity.getEmail()));
if (entity.getId() == null) {
Long id =
UUID expectedUuid = UUID.randomUUID();
AccountsRecord inserted =
dsl.insertInto(ACCOUNTS)
.set(ACCOUNTS.ACCOUNT_UUID, expectedUuid)
.set(
ACCOUNTS.ACCOUNT_UUID_PROVENANCE,
AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT.name())
.set(ACCOUNTS.USERNAME, entity.getUsername())
.set(ACCOUNTS.EMAIL, entity.getEmail())
.set(ACCOUNTS.PASSWORD_HASH, entity.getPasswordHash())
.set(ACCOUNTS.ROLE, entity.getRole())
.set(ACCOUNTS.EMAIL_VERIFIED, entity.isEmailVerified())
.set(ACCOUNTS.LOGIN_AUTH_MODES, normalizedLoginAuthModes(entity))
.set(ACCOUNTS.LIFECYCLE_STATE, entity.getLifecycleState().storageValue())
.returningResult(ACCOUNTS.ID)
.fetchOne(ACCOUNTS.ID);
entity.setId(id);
.returning()
.fetchOne();
if (inserted == null) {
throw new IllegalStateException("Account insert did not return its persisted identity");
}
requireExactIdentityReadback(
inserted, expectedUuid, AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT);
copyIdentityToEntity(entity, inserted);
return entity;
}
int updated =
UUID expectedUuid = entity.getAccountUuid();
AccountIdentityProvenance expectedProvenance = entity.getAccountUuidProvenance();
Long expectedSourceNumericId = entity.getAccountUuidSourceNumericId();
var update =
dsl.update(ACCOUNTS)
.set(ACCOUNTS.USERNAME, entity.getUsername())
.set(ACCOUNTS.EMAIL, entity.getEmail())
.set(ACCOUNTS.PASSWORD_HASH, entity.getPasswordHash())
.set(ACCOUNTS.ROLE, entity.getRole())
.set(ACCOUNTS.EMAIL_VERIFIED, entity.isEmailVerified())
.set(ACCOUNTS.LOGIN_AUTH_MODES, normalizedLoginAuthModes(entity))
.where(ACCOUNTS.ID.eq(entity.getId()))
.execute();
if (updated != 1) {
.where(ACCOUNTS.ID.eq(entity.getId()));
if (expectedUuid != null) {
update = update.and(ACCOUNTS.ACCOUNT_UUID.eq(expectedUuid));
}
if (expectedProvenance != null) {
update = update.and(ACCOUNTS.ACCOUNT_UUID_PROVENANCE.eq(expectedProvenance.name()));
}
if (expectedSourceNumericId != null) {
update = update.and(ACCOUNTS.ACCOUNT_UUID_SOURCE_NUMERIC_ID.eq(expectedSourceNumericId));
}
AccountsRecord updated = update.returning().fetchOne();
if (updated == null) {
throw JooqAccountRepositorySupport.staleWrite("accounts", entity.getId());
}
requireExactIdentityReadback(
updated,
expectedUuid == null ? updated.getAccountUuid() : expectedUuid,
expectedProvenance == null
? AccountIdentityProvenance.fromStorageValue(updated.getAccountUuidProvenance())
: expectedProvenance);
copyIdentityToEntity(entity, updated);
return entity;
}

Expand All @@ -78,15 +118,47 @@ public void delete(Account entity) {
}

private Account toEntity(AccountsRecord record) {
return JooqAccountRepositorySupport.partialAccount(
record.getId(),
record.getUsername(),
record.getEmail(),
record.getPasswordHash(),
record.getRole(),
record.getEmailVerified(),
record.getLoginAuthModes(),
record.getLifecycleState());
Account account =
JooqAccountRepositorySupport.partialAccount(
record.getId(),
record.getUsername(),
record.getEmail(),
record.getPasswordHash(),
record.getRole(),
record.getEmailVerified(),
record.getLoginAuthModes(),
record.getLifecycleState());
if (account != null) {
account.setAccountUuid(record.getAccountUuid());
account.setAccountUuidProvenance(
AccountIdentityProvenance.fromStorageValue(record.getAccountUuidProvenance()));
account.setAccountUuidSourceNumericId(record.getAccountUuidSourceNumericId());
requireExactIdentityReadback(
record, record.getAccountUuid(), account.getAccountUuidProvenance());
}
return account;
}

private void requireExactIdentityReadback(
AccountsRecord record, UUID expectedUuid, AccountIdentityProvenance expectedProvenance) {
if (record.getId() == null
|| expectedUuid == null
|| new UUID(0L, 0L).equals(expectedUuid)
|| expectedProvenance == null
|| !Objects.equals(record.getAccountUuid(), expectedUuid)
|| !Objects.equals(record.getAccountUuidProvenance(), expectedProvenance.name())
|| !Objects.equals(record.getAccountUuidSourceNumericId(), record.getId())) {
throw new IllegalStateException(
"Account UUID readback did not match its exact persisted source row");
}
}

private void copyIdentityToEntity(Account entity, AccountsRecord record) {
entity.setId(record.getId());
entity.setAccountUuid(record.getAccountUuid());
entity.setAccountUuidProvenance(
AccountIdentityProvenance.fromStorageValue(record.getAccountUuidProvenance()));
entity.setAccountUuidSourceNumericId(record.getAccountUuidSourceNumericId());
}

private String normalizedLoginAuthModes(Account entity) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
-- Keep the numeric primary key as an Account-local storage detail while adding
-- the canonical, durable UUID identity required at cross-service boundaries.
-- Each retained UUID is assigned to its exact source row in place; the numeric
-- source is copied from that row's unchanged primary key.
ALTER TABLE accounts
ADD COLUMN account_uuid UUID,
ADD COLUMN account_uuid_provenance VARCHAR(40),
ADD COLUMN account_uuid_source_numeric_id BIGINT;

UPDATE accounts
SET account_uuid = gen_random_uuid(),
account_uuid_provenance = 'ACCOUNT_V29_MIGRATION',
account_uuid_source_numeric_id = id;

-- jOOQ's open-source DDL parser cannot model the PostgreSQL UUID generator default.
-- [jooq ignore start]
ALTER TABLE accounts ALTER COLUMN account_uuid SET DEFAULT gen_random_uuid();
ALTER TABLE accounts
ALTER COLUMN account_uuid_provenance SET DEFAULT 'ACCOUNT_DATABASE_INSERT';
-- [jooq ignore stop]

ALTER TABLE accounts ALTER COLUMN account_uuid SET NOT NULL;
ALTER TABLE accounts ALTER COLUMN account_uuid_provenance SET NOT NULL;
ALTER TABLE accounts ALTER COLUMN account_uuid_source_numeric_id SET NOT NULL;
ALTER TABLE accounts
ADD CONSTRAINT accounts_account_uuid_unique UNIQUE (account_uuid);
ALTER TABLE accounts
ADD CONSTRAINT accounts_account_uuid_source_numeric_id_unique
UNIQUE (account_uuid_source_numeric_id);
ALTER TABLE accounts
ADD CONSTRAINT accounts_account_uuid_source_numeric_id_check
CHECK (account_uuid_source_numeric_id = id);
ALTER TABLE accounts
ADD CONSTRAINT accounts_account_uuid_non_nil_check
CHECK (account_uuid <> '00000000-0000-0000-0000-000000000000'::UUID);
ALTER TABLE accounts
ADD CONSTRAINT accounts_account_uuid_provenance_check
CHECK (account_uuid_provenance IN (
'ACCOUNT_V29_MIGRATION',
'ACCOUNT_REPOSITORY_INSERT',
'ACCOUNT_DATABASE_INSERT'
));

-- The UUID and its source record are immutable identity evidence. The numeric
-- primary key remains unchanged and cannot be reassigned after UUID backfill.
-- [jooq ignore start]
CREATE FUNCTION account_identity_source_row_on_insert()
RETURNS TRIGGER
LANGUAGE plpgsql
AS $$
BEGIN
IF NEW.account_uuid_provenance = 'ACCOUNT_V29_MIGRATION' THEN
RAISE EXCEPTION 'ACCOUNT_V29_MIGRATION provenance is reserved for retained rows'
USING ERRCODE = '23514', CONSTRAINT = 'accounts_identity_migration_insert_only';
END IF;
NEW.account_uuid_source_numeric_id := NEW.id;
RETURN NEW;
END;
$$;

CREATE TRIGGER accounts_identity_source_row_on_insert
BEFORE INSERT ON accounts
FOR EACH ROW
EXECUTE FUNCTION account_identity_source_row_on_insert();

CREATE FUNCTION account_identity_immutable_guard()
RETURNS TRIGGER
LANGUAGE plpgsql
AS $$
BEGIN
IF NEW.id IS DISTINCT FROM OLD.id
OR NEW.account_uuid IS DISTINCT FROM OLD.account_uuid
OR NEW.account_uuid_provenance IS DISTINCT FROM OLD.account_uuid_provenance
OR NEW.account_uuid_source_numeric_id IS DISTINCT FROM OLD.account_uuid_source_numeric_id THEN
RAISE EXCEPTION 'Account identity cannot be reassigned'
USING ERRCODE = '23514', CONSTRAINT = 'accounts_identity_immutable';
END IF;
RETURN NEW;
END;
$$;

CREATE TRIGGER accounts_identity_immutable
BEFORE UPDATE OF id, account_uuid, account_uuid_provenance, account_uuid_source_numeric_id
ON accounts
FOR EACH ROW
EXECUTE FUNCTION account_identity_immutable_guard();
-- [jooq ignore stop]
Loading
Loading