diff --git a/api/README.en.md b/api/README.en.md index b00115e..f5e59da 100644 --- a/api/README.en.md +++ b/api/README.en.md @@ -109,7 +109,7 @@ Registration and verification: - Accounts are not enumerated. Registration and resend answer the same neutral 202 for a new, unverified, verified, or unknown email, and login answers 401 `invalid_credentials` for both an unknown email and a wrong password. - Before the server looks up the email, it validates the whole registration body (password bounds after NFKC normalization, the password blocklist, the C1 version) and computes the Argon2id hash on every branch, so neither a 400 nor the response time depends on whether the account exists. - Registering an unverified email again replaces the password hash, the scenario, the onboarding step, and the C1 record, advances the registration version, invalidates every earlier verification token, and sends a new one. A pre-registration with someone else's password therefore does not survive the owner's own registration. For a verified email nothing changes; the server may send a rate-limited "you already have an account" notice. -- Every verification token is bound to the registration version it was issued for, so a token issued before a re-registration never confirms the newer credentials. Resend issues a token for the current version, invalidates the earlier ones, and changes nothing else. Planned values: tokens live 24 hours; an account that stays unverified is deleted with its consent record and tokens 7 days after its last registration. +- Every verification token is bound to the registration version it was issued for, so a token issued before a re-registration never confirms the newer credentials. Resend issues a token for the current version, invalidates the earlier ones, and changes nothing else. Planned values: tokens live 24 hours; an account that stays unverified is deleted with its consent record and tokens 7 days after its last registration. These lifetimes come from the versioned product policy (demo version 1 of the `product` family), not from configuration; see [ARCHITECTURE.md](../docs/en/ARCHITECTURE.md#product-policy-versions). - Registration requires Idempotency-Key. For this anonymous operation the key is scoped by the operation, the key, and an HMAC of the normalized email; the fingerprint is an HMAC-SHA-256 with a server secret over the canonical JSON body. The body, the password, and plain hashes of either are never stored, and the secret keeps the fingerprint from serving as an offline password check. - The verification link is `/verify-email#token=`. The page removes the fragment with `history.replaceState` and posts the token only after an explicit user action, so the token stays out of server logs and Referer headers and a link scanner does not consume it. Verification does not start a session. - An expired token answers `verification_token_expired`; an unknown, used, replaced, or superseded token answers `verification_token_invalid`. The client offers a new link and sign-in for both. A repeated confirmation with a used token is deliberately not an idempotent 200: exactly one request succeeds per token. @@ -123,7 +123,7 @@ Consent C1 and the account: Sessions and CSRF: -- The `sessionCookie` scheme is the cookie `__Host-lincodex_session` with `Path=/; Secure; HttpOnly; SameSite=Strict` and no Domain. The server keeps sessions in PostgreSQL and takes the caller only from the session. Only a verified account gets a session. Login revokes the session the request carried and issues a new identifier and CSRF token; logout revokes the session server-side. Planned timeouts: 24 hours idle and 7 days absolute; activity extends only the idle deadline. +- The `sessionCookie` scheme is the cookie `__Host-lincodex_session` with `Path=/; Secure; HttpOnly; SameSite=Strict` and no Domain. The server keeps sessions in PostgreSQL and takes the caller only from the session. Only a verified account gets a session. Login revokes the session the request carried and issues a new identifier and CSRF token; logout revokes the session server-side. Planned timeouts: 24 hours idle and 7 days absolute; activity extends only the idle deadline. Both come from the versioned product policy, not from configuration. - The `sessionCsrf` scheme is the `X-CSRF-Token` header with the session-bound token from `Session.csrf_token`. Every unsafe operation that requires `sessionCookie` must also require `sessionCsrf`; `TestUnsafeSessionOperationsRequireCSRFToken` in the backend enforces it on the bundle. The client keeps the token in memory and restores it with `GetCurrentSession` after a reload or after 403 `csrf_check_failed`. - Every unsafe request, including the public ones, must carry an `Origin` from the configured allowlist, otherwise 403 `csrf_check_failed` (planned, TASK-056; see the [development guide](../docs/en/DEVELOPMENT.md#sessions-on-local-http)). Public identity operations are rate-limited (429 with `Retry-After`). - Responses with a session or account carry `Cache-Control: no-store`. diff --git a/api/README.md b/api/README.md index 7b719d8..5c7e396 100644 --- a/api/README.md +++ b/api/README.md @@ -109,7 +109,7 @@ ML-сервис отвечает на ошибки той же схемой `Pro - Аккаунты не перечисляются. Регистрация и повторная отправка отвечают одинаковым нейтральным 202 для нового, неподтвержденного, подтвержденного и неизвестного email, а вход отвечает 401 `invalid_credentials` и для неизвестного email, и для неверного пароля. - До поиска email сервер проверяет все тело регистрации (длину пароля после нормализации NFKC, blocklist паролей, версию C1) и в каждой ветке вычисляет хеш Argon2id, поэтому ни 400, ни время ответа не зависят от существования аккаунта. - Повторная регистрация неподтвержденного email заменяет хеш пароля, сценарий, шаг онбординга и запись C1, увеличивает версию регистрации, аннулирует все прежние токены подтверждения и отправляет новый. Поэтому предрегистрация с чужим паролем не переживает собственную регистрацию владельца адреса. Для подтвержденного email ничего не меняется; сервер может отправить ограниченное по частоте уведомление "у вас уже есть аккаунт". -- Каждый токен подтверждения привязан к версии регистрации, для которой выпущен, поэтому токен, выпущенный до повторной регистрации, никогда не подтверждает новые учетные данные. Повторная отправка выпускает токен для текущей версии, аннулирует прежние и больше ничего не меняет. Запланированные значения: токен живет 24 часа; аккаунт, оставшийся неподтвержденным, удаляется вместе с записью согласия и токенами через 7 дней после последней регистрации. +- Каждый токен подтверждения привязан к версии регистрации, для которой выпущен, поэтому токен, выпущенный до повторной регистрации, никогда не подтверждает новые учетные данные. Повторная отправка выпускает токен для текущей версии, аннулирует прежние и больше ничего не меняет. Запланированные значения: токен живет 24 часа; аккаунт, оставшийся неподтвержденным, удаляется вместе с записью согласия и токенами через 7 дней после последней регистрации. Эти сроки берутся из версионированной продуктовой политики (демонстрационная версия 1 семейства `product`), а не из конфигурации; см. [ARCHITECTURE.md](../docs/ru/ARCHITECTURE.md#версии-продуктовой-политики). - Регистрация требует Idempotency-Key. Для этой анонимной операции ключ ограничивается операцией, самим ключом и HMAC нормализованного email; отпечаток - HMAC-SHA-256 с серверным секретом над каноническим JSON тела. Тело, пароль и их простые хеши не хранятся, а секрет не дает использовать отпечаток для офлайн-проверки пароля. - Ссылка подтверждения имеет вид `/verify-email#token=`. Страница удаляет фрагмент через `history.replaceState` и отправляет токен только после явного действия пользователя, поэтому токен не попадает в логи сервера и заголовок Referer, а сканер ссылок его не расходует. Подтверждение не создает сессию. - Истекший токен дает `verification_token_expired`; неизвестный, использованный, замененный или устаревший по версии - `verification_token_invalid`. В обоих случаях клиент предлагает новую ссылку и вход. Повторное подтверждение использованным токеном намеренно не дает идемпотентный 200: по одному токену успешен ровно один запрос. @@ -123,7 +123,7 @@ ML-сервис отвечает на ошибки той же схемой `Pro Сессии и CSRF: -- Схема `sessionCookie` - cookie `__Host-lincodex_session` с `Path=/; Secure; HttpOnly; SameSite=Strict` и без Domain. Сервер хранит сессии в PostgreSQL и берет вызывающего только из сессии. Сессию получает только подтвержденный аккаунт. Вход отзывает сессию, пришедшую с запросом, и выдает новый идентификатор и CSRF-токен; выход отзывает сессию на сервере. Запланированные тайм-ауты: 24 часа простоя и 7 дней абсолютного срока; активность продлевает только срок простоя. +- Схема `sessionCookie` - cookie `__Host-lincodex_session` с `Path=/; Secure; HttpOnly; SameSite=Strict` и без Domain. Сервер хранит сессии в PostgreSQL и берет вызывающего только из сессии. Сессию получает только подтвержденный аккаунт. Вход отзывает сессию, пришедшую с запросом, и выдает новый идентификатор и CSRF-токен; выход отзывает сессию на сервере. Запланированные тайм-ауты: 24 часа простоя и 7 дней абсолютного срока; активность продлевает только срок простоя. Оба значения берутся из версионированной продуктовой политики, а не из конфигурации. - Схема `sessionCsrf` - заголовок `X-CSRF-Token` с привязанным к сессии токеном из `Session.csrf_token`. Любая небезопасная операция, требующая `sessionCookie`, обязана требовать и `sessionCsrf`; это проверяет `TestUnsafeSessionOperationsRequireCSRFToken` в backend по bundle. Клиент хранит токен только в памяти и восстанавливает его через `GetCurrentSession` после перезагрузки страницы или после 403 `csrf_check_failed`. - Любой небезопасный запрос, включая публичные, должен нести `Origin` из настроенного allowlist, иначе 403 `csrf_check_failed` (запланировано, TASK-056; см. [руководство по разработке](../docs/ru/DEVELOPMENT.md#сессии-на-локальном-http)). Публичные операции identity ограничены по частоте (429 с `Retry-After`). - Ответы с сессией или аккаунтом несут `Cache-Control: no-store`. diff --git a/backend/db/migrations/00003_create_policy_versions.sql b/backend/db/migrations/00003_create_policy_versions.sql new file mode 100644 index 0000000..2dd2594 --- /dev/null +++ b/backend/db/migrations/00003_create_policy_versions.sql @@ -0,0 +1,116 @@ +-- +goose Up +-- Versioned product policy: deadlines, quotas, thresholds, and coefficients +-- that product rules read. Every row is one immutable version of one policy +-- family. Records built under a policy, such as grade decisions, selection +-- snapshots, and invitations, will store the policy_versions.id they used, so +-- a newer version never changes how an earlier decision was made. +CREATE TABLE policy_versions ( + -- UUIDv7 generated in Go. + id uuid NOT NULL, + -- Policy family. Each family has one document layout and one decoder in + -- Go; "product" is the only family. A new family changes this CHECK. + policy_key text NOT NULL, + -- Numbered from 1 within the family; the newest publication has the + -- highest number. + version integer NOT NULL, + -- Calibration state of the whole version, the flag consumers read. "demo" + -- values are an initial policy for verification and make no calibrated + -- quality claim. + kind text NOT NULL, + -- The version can apply to decisions made at or after this time. A NULL + -- in the INSERT means "at publication"; the stamp trigger fills it in. + effective_at timestamptz NOT NULL, + -- Operator identity such as "system:demo-seed" or "operator:". + -- Never an email address or other contact data. + author text NOT NULL, + -- The typed policy serialized by the domain in canonical form. jsonb + -- normalizes key order and whitespace; integrity is checked against + -- document_sha256 after the domain re-encodes the decoded document. + document jsonb NOT NULL, + -- SHA-256 of the canonical document bytes, 32 raw bytes. + document_sha256 bytea NOT NULL, + -- Publication time from the database clock, set by the stamp trigger on + -- every insert; a value from the caller is ignored. + created_at timestamptz NOT NULL, + CONSTRAINT policy_versions_pkey PRIMARY KEY (id), + CONSTRAINT policy_versions_policy_key_version_key UNIQUE ( + policy_key, version + ), + CONSTRAINT policy_versions_policy_key_known CHECK ( + policy_key IN ('product') + ), + CONSTRAINT policy_versions_version_positive CHECK (version > 0), + CONSTRAINT policy_versions_kind_known CHECK ( + kind IN ('demo', 'calibrated') + ), + CONSTRAINT policy_versions_author_format CHECK ( + char_length(author) <= 128 + AND author ~ '^(system|operator):[a-z0-9][a-z0-9._-]*$' + ), + CONSTRAINT policy_versions_document_object CHECK ( + jsonb_typeof(document) = 'object' + ), + -- A calibrated version cannot carry an assessment section that its own + -- document marks as uncalibrated. + CONSTRAINT policy_versions_calibrated_kind_matches_document CHECK ( + kind <> 'calibrated' + OR document #>> '{assessment,calibration}' = 'calibrated' + ), + CONSTRAINT policy_versions_document_sha256_size CHECK ( + octet_length(document_sha256) = 32 + ), + -- A version is never backdated: publishing it cannot change which version + -- applied at a moment that already passed. + CONSTRAINT policy_versions_effective_after_creation CHECK ( + effective_at >= created_at + ) +); + +-- Sets created_at from the database clock and defaults effective_at to it. +-- NOT NULL and CHECK constraints run after BEFORE triggers, so they see the +-- stamped values. +-- +goose StatementBegin +CREATE FUNCTION policy_versions_stamp_creation() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + NEW.created_at := clock_timestamp(); + NEW.effective_at := coalesce(NEW.effective_at, NEW.created_at); + RETURN NEW; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER policy_versions_stamp_creation +BEFORE INSERT ON policy_versions +FOR EACH ROW EXECUTE FUNCTION policy_versions_stamp_creation(); + +-- Refuses every UPDATE, DELETE, and TRUNCATE of policy versions. The error +-- uses SQLSTATE 23000 (integrity_constraint_violation) and the constraint name +-- policy_versions_immutable, which the adapter maps to a port sentinel without +-- reading the message. The message quotes no row values. +-- +goose StatementBegin +CREATE FUNCTION policy_versions_refuse_change() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + RAISE EXCEPTION USING + ERRCODE = 'integrity_constraint_violation', + CONSTRAINT = 'policy_versions_immutable', + TABLE = 'policy_versions', + MESSAGE = 'policy versions are immutable: publish a new version instead'; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER policy_versions_refuse_update_delete +BEFORE UPDATE OR DELETE ON policy_versions +FOR EACH ROW EXECUTE FUNCTION policy_versions_refuse_change(); + +-- Row triggers do not fire for TRUNCATE, so a statement trigger covers it. +CREATE TRIGGER policy_versions_refuse_truncate +BEFORE TRUNCATE ON policy_versions +FOR EACH STATEMENT EXECUTE FUNCTION policy_versions_refuse_change(); + +-- +goose Down +DROP TABLE policy_versions; +DROP FUNCTION policy_versions_refuse_change(); +DROP FUNCTION policy_versions_stamp_creation(); diff --git a/backend/db/queries/policy.sql b/backend/db/queries/policy.sql new file mode 100644 index 0000000..5fd8201 --- /dev/null +++ b/backend/db/queries/policy.sql @@ -0,0 +1,96 @@ +-- Stores a version and returns the stored row with the publication time and +-- effective time set by the stamp trigger. A taken ID or version number +-- returns no row instead of an error, so a conflict does not abort the +-- surrounding transaction. created_at is never taken from the caller, and a +-- NULL effective_at means "at publication". +-- name: InsertPolicyVersion :one +INSERT INTO policy_versions ( + id, + policy_key, + version, + kind, + effective_at, + author, + document, + document_sha256 +) VALUES ( + sqlc.arg(id), + sqlc.arg(policy_key), + sqlc.arg(version), + sqlc.arg(kind), + sqlc.narg(effective_at), + sqlc.arg(author), + sqlc.arg(document), + sqlc.arg(document_sha256) +) +ON CONFLICT DO NOTHING +RETURNING + id, + policy_key, + version, + kind, + effective_at, + author, + document, + document_sha256, + created_at; + +-- name: GetPolicyVersionByID :one +SELECT + id, + policy_key, + version, + kind, + effective_at, + author, + document, + document_sha256, + created_at +FROM policy_versions +WHERE id = sqlc.arg(id); + +-- Among the versions of a family already effective at a time, the newest +-- publication wins. A version scheduled for later therefore never undoes a +-- version published after it. The unique (policy_key, version) index serves +-- the backward scan. +-- name: GetEffectivePolicyVersion :one +SELECT + id, + policy_key, + version, + kind, + effective_at, + author, + document, + document_sha256, + created_at +FROM policy_versions +WHERE + policy_key = sqlc.arg(policy_key) + AND effective_at <= sqlc.arg(at) +ORDER BY version DESC +LIMIT 1; + +-- name: GetLatestPolicyVersion :one +SELECT + id, + policy_key, + version, + kind, + effective_at, + author, + document, + document_sha256, + created_at +FROM policy_versions +WHERE policy_key = sqlc.arg(policy_key) +ORDER BY version DESC +LIMIT 1; + +-- Reports whether a family has any version without reading a document, so a +-- caller that only needs presence never depends on decoding. +-- name: PolicyVersionExists :one +SELECT exists( + SELECT 1 FROM policy_versions + WHERE policy_key = sqlc.arg(policy_key) +) AS present; diff --git a/backend/integration_test/policy_test.go b/backend/integration_test/policy_test.go new file mode 100644 index 0000000..68b156b --- /dev/null +++ b/backend/integration_test/policy_test.go @@ -0,0 +1,728 @@ +//go:build integration + +package integration_test + +import ( + "context" + "crypto/rand" + "crypto/sha256" + "errors" + "fmt" + "slices" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5/pgconn" + "github.com/jackc/pgx/v5/pgxpool" + + postgresadapter "lincodex/backend/internal/adapter/secondary/postgres" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" + "lincodex/backend/internal/usecase/policy" +) + +const ( + policyTestTimeout = 3 * time.Minute + // concurrentPublishers stays below the publisher's attempt bound, so each + // of them must succeed. + concurrentPublishers = 8 + concurrentSeeders = 4 + // policyImmutableSQLState and policyImmutableConstraint identify the + // refusal raised by the policy_versions trigger. + policyImmutableSQLState = "23000" + policyImmutableConstraint = "policy_versions_immutable" + foreignKeyViolationState = "23503" + policyTestAuthor = domain.PolicyAuthor("operator:integration-test") + // databaseClockTolerance bounds the difference between the test clock and + // the PostgreSQL container clock that stamps created_at. + databaseClockTolerance = time.Minute +) + +// policyFixture works on its own database. "product" is the only policy +// family and the table refuses TRUNCATE, so every subtest gets a fresh +// database instead of a key of its own or a cleanup. +type policyFixture struct { + ctx context.Context + databaseURL string + pool *pgxpool.Pool + store *postgresadapter.PolicyStore + transactor *postgresadapter.Transactor +} + +func TestPolicyVersions(t *testing.T) { + env := bootstrap(t, postgresService) + ctx, cancel := context.WithTimeout(t.Context(), policyTestTimeout) + defer cancel() + newFixture := func(t *testing.T) policyFixture { + t.Helper() + databaseURL := env.createIsolatedDatabase(ctx, t) + applyMigrations(ctx, t, databaseURL) + pool := newPoolFor(ctx, t, databaseURL) + return policyFixture{ + ctx: ctx, + databaseURL: databaseURL, + pool: pool, + store: postgresadapter.NewPolicyStore(pool), + transactor: postgresadapter.NewTransactor(pool), + } + } + + t.Run("saves two versions and reads both by ID", func(t *testing.T) { + fixture := newFixture(t) + before := time.Now() + first := fixture.publish(t, fixture.store.Policies(), 1, time.Time{}, integrationPolicy(11)) + scheduledAt := before.Add(time.Hour).Truncate(time.Microsecond) + second := fixture.publish(t, fixture.store.Policies(), 2, scheduledAt, integrationPolicy(12)) + for _, want := range []domain.PolicyVersion{first, second} { + got, err := fixture.store.Policies().GetByID(ctx, want.ID()) + if err != nil { + t.Fatalf("GetByID(%s) error = %v", want.ID(), err) + } + assertSamePolicyVersion(t, got, want) + } + assertDatabaseTime(t, "created_at", first.CreatedAt(), before) + if !first.EffectiveAt().Equal(first.CreatedAt()) || !second.EffectiveAt().Equal(scheduledAt) { + t.Fatalf("effective times = %s and %s, want publication and %s", first.EffectiveAt(), second.EffectiveAt(), scheduledAt) + } + if got := fixture.readMaxPending(t, second.ID()); got != 12 { + t.Fatalf("second version max_pending_per_need = %d, want 12", got) + } + var storedHash []byte + if err := fixture.pool.QueryRow(ctx, `SELECT document_sha256 FROM policy_versions WHERE id = $1`, first.ID().UUID()).Scan(&storedHash); err != nil { + t.Fatalf("read stored hash: %v", err) + } + if want := sha256.Sum256(first.Document()); string(storedHash) != string(want[:]) { + t.Fatal("stored document_sha256 is not the SHA-256 of the canonical document") + } + if _, err := fixture.store.Policies().GetByID(ctx, domain.PolicyVersionID(uuid.New())); !errors.Is(err, outbound.ErrPolicyVersionNotFound) { + t.Fatalf("GetByID(unknown) error = %v, want ErrPolicyVersionNotFound", err) + } + }) + + t.Run("the database sets the publication time", func(t *testing.T) { + fixture := newFixture(t) + before := time.Now() + draft := fixture.draft(t, 1, time.Time{}, integrationPolicy(13)) + hash := draft.DocumentHash() + // A caller-supplied created_at and a missing effective_at are both + // replaced by the stamp trigger. + var createdAt, effectiveAt time.Time + err := fixture.pool.QueryRow(ctx, ` + INSERT INTO policy_versions (id, policy_key, version, kind, effective_at, author, document, document_sha256, created_at) + VALUES ($1, $2, $3, $4, NULL, $5, $6, $7, '2000-01-01T00:00:00Z') + RETURNING created_at, effective_at`, + draft.ID().UUID(), string(draft.Key()), draft.Version(), string(draft.Kind()), string(draft.Author()), + draft.Document(), hash[:]).Scan(&createdAt, &effectiveAt) + if err != nil { + t.Fatalf("insert with a caller-supplied created_at: %v", err) + } + assertDatabaseTime(t, "created_at", createdAt, before) + if !effectiveAt.Equal(createdAt) { + t.Fatalf("effective_at = %s, want created_at %s", effectiveAt, createdAt) + } + + backdated := fixture.draft(t, 2, time.Now().Add(-time.Hour), integrationPolicy(14)) + _, err = fixture.store.Policies().Create(ctx, backdated) + if !errors.Is(err, outbound.ErrPolicyVersionBackdated) { + t.Fatalf("Create(backdated) error = %v, want ErrPolicyVersionBackdated", err) + } + fixture.assertVersionCount(t, 1) + }) + + t.Run("a conflict inside a unit of work leaves the transaction usable", func(t *testing.T) { + fixture := newFixture(t) + existing := fixture.publish(t, fixture.store.Policies(), 1, time.Time{}, integrationPolicy(15)) + var stored []domain.PolicyVersion + err := fixture.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + duplicate := fixture.draft(t, 1, time.Time{}, integrationPolicy(16)) + if _, err := unit.Policies().Create(ctx, duplicate); !errors.Is(err, outbound.ErrPolicyVersionConflict) { + return fmt.Errorf("Create(duplicate number) error = %w, want ErrPolicyVersionConflict", err) + } + second, err := unit.Policies().Create(ctx, fixture.draft(t, 2, time.Time{}, integrationPolicy(17))) + if err != nil { + return fmt.Errorf("Create(v2) after the conflict: %w", err) + } + // The publisher works through the transaction too. + third, err := policy.NewPublisher(unit.Policies(), time.Now).Publish(ctx, policy.PublishInput{ + Key: domain.ProductPolicyKey, Kind: domain.PolicyKindCalibrated, Author: policyTestAuthor, Policy: integrationPolicy(18), + }) + if err != nil { + return fmt.Errorf("Publish() in the transaction: %w", err) + } + got, err := unit.Policies().GetByID(ctx, second.ID()) + if err != nil { + return fmt.Errorf("GetByID() in the transaction: %w", err) + } + assertSamePolicyVersion(t, got, second) + // The pool store must not bypass the transaction. + if _, err := fixture.store.Policies().GetByID(ctx, second.ID()); !errors.Is(err, outbound.ErrNestedTransaction) { + t.Errorf("standalone GetByID inside a transaction error = %v, want ErrNestedTransaction", err) + } + stored = []domain.PolicyVersion{existing, second, third} + return nil + }) + if err != nil { + t.Fatalf("WithinTransaction() error = %v", err) + } + for index, want := range stored { + got, err := fixture.store.Policies().GetByID(ctx, want.ID()) + if err != nil || got.Version() != int32(index+1) { + t.Fatalf("GetByID(v%d) after commit = v%d, %v", index+1, got.Version(), err) + } + } + fixture.assertVersionCount(t, len(stored)) + }) + + t.Run("the newest effective publication wins, also over an earlier schedule", func(t *testing.T) { + fixture := newFixture(t) + policies := fixture.store.Policies() + first := fixture.publish(t, policies, 1, time.Time{}, integrationPolicy(21)) + if _, err := policies.GetEffective(ctx, domain.ProductPolicyKey, first.CreatedAt().Add(-time.Microsecond)); !errors.Is(err, outbound.ErrPolicyVersionNotFound) { + t.Fatalf("GetEffective(before version 1) error = %v, want ErrPolicyVersionNotFound", err) + } + scheduledAt := first.CreatedAt().Add(time.Hour) + scheduled := fixture.publish(t, policies, 2, scheduledAt, integrationPolicy(22)) + fixture.assertEffective(t, first.CreatedAt(), first) + fixture.assertEffective(t, scheduledAt.Add(-time.Minute), first) + fixture.assertEffective(t, scheduledAt, scheduled) + fixture.assertEffective(t, scheduledAt.Add(time.Hour), scheduled) + + // An urgent correction published after the schedule takes effect at + // once and stays in effect when the scheduled time arrives. + urgent := fixture.publish(t, policies, 3, time.Time{}, integrationPolicy(23)) + fixture.assertEffective(t, first.CreatedAt(), first) + fixture.assertEffective(t, urgent.CreatedAt(), urgent) + fixture.assertEffective(t, scheduledAt, urgent) + fixture.assertEffective(t, scheduledAt.Add(time.Hour), urgent) + latest, err := policies.GetLatest(ctx, domain.ProductPolicyKey) + if err != nil || latest.ID() != urgent.ID() { + t.Fatalf("GetLatest() = v%d, %v; want v3", latest.Version(), err) + } + }) + + t.Run("a taken version number or ID is a conflict", func(t *testing.T) { + fixture := newFixture(t) + draft := fixture.draft(t, 1, time.Time{}, integrationPolicy(31)) + if _, err := fixture.store.Policies().Create(ctx, draft); err != nil { + t.Fatalf("Create() error = %v", err) + } + duplicateNumber := fixture.draft(t, 1, time.Time{}, integrationPolicy(32)) + if _, err := fixture.store.Policies().Create(ctx, duplicateNumber); !errors.Is(err, outbound.ErrPolicyVersionConflict) { + t.Fatalf("Create(duplicate number) error = %v, want ErrPolicyVersionConflict", err) + } + sameID, err := draft.WithVersion(2) + if err != nil { + t.Fatalf("WithVersion(2) error = %v", err) + } + if _, err := fixture.store.Policies().Create(ctx, sameID); !errors.Is(err, outbound.ErrPolicyVersionConflict) { + t.Fatalf("Create(same ID) error = %v, want ErrPolicyVersionConflict", err) + } + fixture.assertVersionCount(t, 1) + if got := fixture.readMaxPending(t, draft.ID()); got != 31 { + t.Fatalf("stored version changed: max_pending_per_need = %d, want 31", got) + } + }) + + t.Run("the database refuses UPDATE, DELETE, and TRUNCATE of a version", func(t *testing.T) { + fixture := newFixture(t) + stored := fixture.publish(t, fixture.store.Policies(), 1, time.Time{}, integrationPolicy(41)) + id := stored.ID().UUID() + statements := []struct { + name string + sql string + args []any + }{ + {name: "update of a value", sql: `UPDATE policy_versions SET author = 'operator:intruder' WHERE id = $1`, args: []any{id}}, + {name: "update without a change", sql: `UPDATE policy_versions SET document = document WHERE id = $1`, args: []any{id}}, + {name: "update of the document", sql: `UPDATE policy_versions + SET document = jsonb_set(document, '{invitations,max_pending_per_need}', '99') WHERE id = $1`, args: []any{id}}, + {name: "delete", sql: `DELETE FROM policy_versions WHERE id = $1`, args: []any{id}}, + {name: "delete of every row", sql: `DELETE FROM policy_versions`}, + {name: "truncate", sql: `TRUNCATE policy_versions`}, + } + for _, statement := range statements { + _, err := fixture.pool.Exec(ctx, statement.sql, statement.args...) + assertPolicyImmutable(t, statement.name, err) + } + + // The same refusal inside a unit of work aborts the transaction. + err := fixture.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + tx := integrationTx(t, unit) + if _, err := tx.Exec(ctx, `UPDATE policy_versions SET effective_at = effective_at + interval '1 day' WHERE id = $1`, id); err != nil { + return fmt.Errorf("move effective time: %w", postgresadapter.MapPolicyErrorForIntegrationTest(err)) + } + return nil + }) + if !errors.Is(err, outbound.ErrPolicyVersionImmutable) { + t.Fatalf("UPDATE in a transaction error = %v, want ErrPolicyVersionImmutable", err) + } + + got, err := fixture.store.Policies().GetByID(ctx, stored.ID()) + if err != nil { + t.Fatalf("GetByID() after refused changes error = %v", err) + } + assertSamePolicyVersion(t, got, stored) + fixture.assertVersionCount(t, 1) + }) + + t.Run("a document changed behind the trigger fails its hash check", func(t *testing.T) { + fixture := newFixture(t) + stored := fixture.publish(t, fixture.store.Policies(), 1, time.Time{}, integrationPolicy(45)) + // The table owner can bypass the trigger. The change stays inside a + // transaction that is always rolled back, which also restores the + // trigger. + errTampered := errors.New("roll back tampering") + err := fixture.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + tx := integrationTx(t, unit) + if _, err := tx.Exec(ctx, `ALTER TABLE policy_versions DISABLE TRIGGER policy_versions_refuse_update_delete`); err != nil { + return fmt.Errorf("disable trigger: %w", err) + } + if _, err := tx.Exec(ctx, `UPDATE policy_versions + SET document = jsonb_set(document, '{invitations,max_pending_per_need}', '46') WHERE id = $1`, stored.ID().UUID()); err != nil { + return fmt.Errorf("change document: %w", err) + } + if _, err := unit.Policies().GetByID(ctx, stored.ID()); !errors.Is(err, domain.ErrPolicyDocumentIntegrity) { + t.Errorf("GetByID(changed document) error = %v, want ErrPolicyDocumentIntegrity", err) + } + return errTampered + }) + if !errors.Is(err, errTampered) { + t.Fatalf("WithinTransaction() error = %v, want the rollback marker", err) + } + got, err := fixture.store.Policies().GetByID(ctx, stored.ID()) + if err != nil { + t.Fatalf("GetByID() after rollback error = %v", err) + } + assertSamePolicyVersion(t, got, stored) + _, err = fixture.pool.Exec(ctx, `DELETE FROM policy_versions WHERE id = $1`, stored.ID().UUID()) + assertPolicyImmutable(t, "delete after the rolled-back bypass", err) + }) + + t.Run("CHECK constraints refuse invalid rows from raw SQL", func(t *testing.T) { + fixture := newFixture(t) + demo := fixture.demoDraft(t) + demoHash := demo.DocumentHash() + calibratedDraft := fixture.draft(t, 1, time.Time{}, integrationPolicy(47)) + calibratedHash := calibratedDraft.DocumentHash() + valid := func() []any { + // id, policy_key, version, kind, effective_at, author, document, document_sha256 + return []any{uuid.New(), "product", int32(1), "demo", nil, "system:raw-sql", demo.Document(), demoHash[:]} + } + tests := []struct { + constraint string + mutate func(args []any) + }{ + {constraint: "policy_versions_effective_after_creation", mutate: func(args []any) { + args[4] = time.Date(2000, time.January, 1, 0, 0, 0, 0, time.UTC) + }}, + {constraint: "policy_versions_author_format", mutate: func(args []any) { args[5] = "operator:tester@example.com" }}, + {constraint: "policy_versions_author_format", mutate: func(args []any) { args[5] = "tester" }}, + {constraint: "policy_versions_kind_known", mutate: func(args []any) { args[3] = "draft" }}, + {constraint: "policy_versions_policy_key_known", mutate: func(args []any) { args[1] = "other" }}, + {constraint: "policy_versions_version_positive", mutate: func(args []any) { args[2] = int32(0) }}, + {constraint: "policy_versions_document_object", mutate: func(args []any) { args[6] = []byte(`[]`) }}, + {constraint: "policy_versions_document_sha256_size", mutate: func(args []any) { args[7] = demoHash[:31] }}, + {constraint: "policy_versions_calibrated_kind_matches_document", mutate: func(args []any) { args[3] = "calibrated" }}, + } + for _, test := range tests { + args := valid() + test.mutate(args) + _, err := fixture.pool.Exec(ctx, ` + INSERT INTO policy_versions (id, policy_key, version, kind, effective_at, author, document, document_sha256) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8)`, args...) + var pgError *pgconn.PgError + if !errors.As(err, &pgError) || pgError.Code != checkViolationCode || pgError.ConstraintName != test.constraint { + t.Fatalf("insert violating %s error = %v, want a check violation", test.constraint, err) + } + } + fixture.assertVersionCount(t, 0) + // The kind CHECK accepts a calibrated document under a calibrated kind. + args := valid() + args[3], args[6], args[7] = "calibrated", calibratedDraft.Document(), calibratedHash[:] + if _, err := fixture.pool.Exec(ctx, ` + INSERT INTO policy_versions (id, policy_key, version, kind, effective_at, author, document, document_sha256) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8)`, args...); err != nil { + t.Fatalf("insert of a valid calibrated row: %v", err) + } + }) + + t.Run("a referencing record pins its version", func(t *testing.T) { + fixture := newFixture(t) + stored := fixture.publish(t, fixture.store.Policies(), 1, time.Time{}, integrationPolicy(51)) + tx, err := fixture.pool.Begin(ctx) + if err != nil { + t.Fatalf("begin transaction: %v", err) + } + // The probe table exists only inside this transaction, which is + // always rolled back. A temporary table cannot reference a permanent + // one, so it is an ordinary table in a test-only schema. + defer func() { _ = tx.Rollback(context.WithoutCancel(ctx)) }() + // A future decision table carries policy_version_id the same way. + if _, err := tx.Exec(ctx, ` + CREATE SCHEMA policy_reference_test; + CREATE TABLE policy_reference_test.decisions ( + id uuid PRIMARY KEY, + policy_version_id uuid NOT NULL REFERENCES policy_versions (id) + )`); err != nil { + t.Fatalf("create referencing table: %v", err) + } + if _, err := tx.Exec(ctx, `INSERT INTO policy_reference_test.decisions (id, policy_version_id) VALUES ($1, $2)`, + uuid.New(), stored.ID().UUID()); err != nil { + t.Fatalf("insert record that references the version: %v", err) + } + if _, err := tx.Exec(ctx, `SAVEPOINT unknown_reference`); err != nil { + t.Fatalf("create savepoint: %v", err) + } + _, err = tx.Exec(ctx, `INSERT INTO policy_reference_test.decisions (id, policy_version_id) VALUES ($1, $2)`, uuid.New(), uuid.New()) + var pgError *pgconn.PgError + if !errors.As(err, &pgError) || pgError.Code != foreignKeyViolationState { + t.Fatalf("insert record that references an unknown version error = %v, want a foreign key violation", err) + } + if _, err := tx.Exec(ctx, `ROLLBACK TO SAVEPOINT unknown_reference`); err != nil { + t.Fatalf("roll back to savepoint: %v", err) + } + _, err = tx.Exec(ctx, `DELETE FROM policy_versions WHERE id = $1`, stored.ID().UUID()) + assertPolicyImmutable(t, "delete of a referenced version", err) + }) + + t.Run("concurrent publications get distinct version numbers", func(t *testing.T) { + fixture := newFixture(t) + // One connection per publisher, so they really race. + counting := &conflictCountingPolicies{ + PolicyRepository: postgresadapter.NewPolicyStore(newSizedPoolFor(ctx, t, fixture.databaseURL, concurrentPublishers)).Policies(), + } + publisher := policy.NewPublisher(counting, time.Now) + versions := make([]domain.PolicyVersion, concurrentPublishers) + errs := make([]error, concurrentPublishers) + start := make(chan struct{}) + var group sync.WaitGroup + for index := range concurrentPublishers { + group.Go(func() { + <-start + versions[index], errs[index] = publisher.Publish(ctx, policy.PublishInput{ + Key: domain.ProductPolicyKey, + Kind: domain.PolicyKindCalibrated, + Author: policyTestAuthor, + Policy: integrationPolicy(int32(60 + index)), + }) + }) + } + close(start) + group.Wait() + numbers := make([]int32, 0, concurrentPublishers) + for index, err := range errs { + if err != nil { + t.Fatalf("publisher %d error = %v", index, err) + } + numbers = append(numbers, versions[index].Version()) + } + slices.Sort(numbers) + for index, number := range numbers { + if number != int32(index+1) { + t.Fatalf("published version numbers = %v, want 1 to %d once each", numbers, concurrentPublishers) + } + } + fixture.assertVersionCount(t, concurrentPublishers) + // Whether publishers collide depends on scheduling, so the count is + // reported rather than asserted. + t.Logf("%d version number conflicts were retried", counting.conflicts.Load()) + }) + + t.Run("the demo seed inserts once under concurrent starts", func(t *testing.T) { + fixture := newFixture(t) + publisher := policy.NewPublisher(postgresadapter.NewPolicyStore(newSizedPoolFor(ctx, t, fixture.databaseURL, concurrentSeeders)).Policies(), time.Now) + results := make([]policy.DemoSeedResult, concurrentSeeders) + errs := make([]error, concurrentSeeders) + start := make(chan struct{}) + var group sync.WaitGroup + for index := range concurrentSeeders { + group.Go(func() { + <-start + results[index], errs[index] = publisher.EnsureDemoProductPolicy(ctx) + }) + } + close(start) + group.Wait() + var created domain.PolicyVersion + for index, err := range errs { + if err != nil { + t.Fatalf("seeder %d error = %v", index, err) + } + if results[index].Created { + if !created.IsZero() { + t.Fatal("two seeders reported an insert") + } + created = results[index].Version + } + } + if created.IsZero() { + t.Fatal("no seeder reported an insert") + } + again, err := publisher.EnsureDemoProductPolicy(ctx) + if err != nil || again.Created { + t.Fatalf("repeated seed = %+v, %v; want a skip", again, err) + } + fixture.assertVersionCount(t, 1) + + demo, err := fixture.store.Policies().GetEffective(ctx, domain.ProductPolicyKey, created.CreatedAt()) + if err != nil { + t.Fatalf("GetEffective(product) error = %v", err) + } + assertSamePolicyVersion(t, demo, created) + if demo.Version() != 1 || demo.Kind() != domain.PolicyKindDemo || demo.Author() != domain.DemoPolicySeedAuthor || + demo.DocumentHash() != fixture.demoDraft(t).DocumentHash() || !demo.EffectiveAt().Equal(demo.CreatedAt()) { + t.Fatalf("seeded product policy = v%d %s by %s, want version 1 of the demo policy effective at publication", demo.Version(), demo.Kind(), demo.Author()) + } + }) + + t.Run("the demo seed skips existing versions without decoding them", func(t *testing.T) { + fixture := newFixture(t) + // A row of a future document layout that this build cannot decode. + futureHash := make([]byte, sha256.Size) + if _, err := rand.Read(futureHash); err != nil { + t.Fatalf("generate hash bytes: %v", err) + } + if _, err := fixture.pool.Exec(ctx, ` + INSERT INTO policy_versions (id, policy_key, version, kind, author, document, document_sha256) + VALUES ($1, 'product', 1, 'demo', 'system:future-build', '{"schema_version": 2}', $2)`, + uuid.New(), futureHash); err != nil { + t.Fatalf("insert a row of an unknown schema version: %v", err) + } + if _, err := fixture.store.Policies().GetLatest(ctx, domain.ProductPolicyKey); !errors.Is(err, domain.ErrInvalidPolicy) { + t.Fatalf("GetLatest(future layout) error = %v, want ErrInvalidPolicy", err) + } + result, err := policy.NewPublisher(fixture.store.Policies(), time.Now).EnsureDemoProductPolicy(ctx) + if err != nil || result.Created { + t.Fatalf("EnsureDemoProductPolicy() = %+v, %v; want a skip without error", result, err) + } + fixture.assertVersionCount(t, 1) + }) + + t.Run("a new pool reads the same versions after a restart", func(t *testing.T) { + fixture := newFixture(t) + firstPool := newPoolFor(ctx, t, fixture.databaseURL) + firstStore := postgresadapter.NewPolicyStore(firstPool) + written := []domain.PolicyVersion{ + fixture.publish(t, firstStore.Policies(), 1, time.Time{}, integrationPolicy(81)), + fixture.publish(t, firstStore.Policies(), 2, time.Time{}, integrationPolicy(82)), + } + firstPool.Close() + + restarted := postgresadapter.NewPolicyStore(newPoolFor(ctx, t, fixture.databaseURL)) + for _, want := range written { + got, err := restarted.Policies().GetByID(ctx, want.ID()) + if err != nil { + t.Fatalf("GetByID(%s) after restart error = %v", want.ID(), err) + } + assertSamePolicyVersion(t, got, want) + } + latest, err := restarted.Policies().GetLatest(ctx, domain.ProductPolicyKey) + if err != nil || latest.ID() != written[1].ID() { + t.Fatalf("GetLatest() after restart = v%d, %v; want v2", latest.Version(), err) + } + if result, err := policy.NewPublisher(restarted.Policies(), time.Now).EnsureDemoProductPolicy(ctx); err != nil || result.Created { + t.Fatalf("demo seed after restart = %+v, %v; want no insert", result, err) + } + }) +} + +// integrationPolicy returns a valid calibrated policy for integration +// fixtures. Its values differ from the demo policy, and maxPending tells +// versions apart. +func integrationPolicy(maxPending int32) domain.ProductPolicy { + return domain.ProductPolicy{ + Invitations: domain.InvitationPolicy{ + ResponseDeadlineOptions: []domain.CalendarDays{1, 4, 9}, + DefaultResponseDeadline: 4, + MaxPendingPerNeed: maxPending, + RepeatAfterDecline: 8, + InterviewProposalDeadline: 2, + NoDealPause: 6, + }, + OrganizationQuotas: domain.OrganizationQuotaPolicy{ + InvitationWindow: 2, + CardViewWindow: 6, + TierE0: domain.OrganizationTierQuota{Active: true, InvitationsPerWindow: 1, DistinctCardViewsPerWindow: 2}, + TierE1: domain.OrganizationTierQuota{Active: true, InvitationsPerWindow: 3, DistinctCardViewsPerWindow: 4}, + TierE2: domain.OrganizationTierQuota{Active: true, InvitationsPerWindow: 5, DistinctCardViewsPerWindow: 6}, + }, + Assessment: domain.AssessmentPolicy{ + Calibration: domain.AssessmentCalibrationCalibrated, + SameGradeRetryAfter: 4, + MaxAttemptsPerWindow: 5, + AttemptWindow: 40, + PromotionMinInterval: 20, + ConfirmationThreshold: 7000, + HighStrengthThreshold: 8500, + PracticeRequired: false, + StopRule: domain.AssessmentStopRule{ + MinScoredItems: 4, + MaxScoredItems: 12, + SeedItems: 1, + UpperProbability: 9200, + LowerProbability: 800, + MaxStandardError: 3500, + }, + }, + Identity: domain.IdentityPolicy{ + VerificationTokenLifetime: 6, + UnverifiedAccountLifetime: 2, + SessionIdleTimeout: 3, + SessionAbsoluteLifetime: 1, + }, + SearchStatus: domain.SearchStatusPolicy{SearchingConfirmationInterval: 10}, + } +} + +// draft builds a numbered calibrated test draft; a zero effectiveAt makes it +// effective at publication. +func (fixture policyFixture) draft(t *testing.T, number int32, effectiveAt time.Time, values domain.ProductPolicy) domain.PolicyVersionDraft { + t.Helper() + draft, err := domain.NewPolicyVersionDraft(domain.NewPolicyVersionDraftInput{ + Key: domain.ProductPolicyKey, + Kind: domain.PolicyKindCalibrated, + Author: policyTestAuthor, + EffectiveAt: effectiveAt, + Policy: values, + }) + if err != nil { + t.Fatalf("NewPolicyVersionDraft(v%d) error = %v", number, err) + } + numbered, err := draft.WithVersion(number) + if err != nil { + t.Fatalf("WithVersion(%d) error = %v", number, err) + } + return numbered +} + +// demoDraft builds the draft the seed stores, for comparison only. +func (fixture policyFixture) demoDraft(t *testing.T) domain.PolicyVersionDraft { + t.Helper() + draft, err := domain.NewPolicyVersionDraft(domain.NewPolicyVersionDraftInput{ + Key: domain.ProductPolicyKey, Kind: domain.PolicyKindDemo, Author: domain.DemoPolicySeedAuthor, Policy: domain.DemoProductPolicyV1(), + }) + if err != nil { + t.Fatalf("NewPolicyVersionDraft(demo) error = %v", err) + } + return draft +} + +func (fixture policyFixture) publish( + t *testing.T, + policies outbound.PolicyRepository, + number int32, + effectiveAt time.Time, + values domain.ProductPolicy, +) domain.PolicyVersion { + t.Helper() + stored, err := policies.Create(fixture.ctx, fixture.draft(t, number, effectiveAt, values)) + if err != nil { + t.Fatalf("Create(v%d) error = %v", number, err) + } + return stored +} + +func (fixture policyFixture) assertEffective(t *testing.T, at time.Time, want domain.PolicyVersion) { + t.Helper() + got, err := fixture.store.Policies().GetEffective(fixture.ctx, domain.ProductPolicyKey, at) + if err != nil { + t.Fatalf("GetEffective(%s) error = %v", at, err) + } + if got.ID() != want.ID() { + t.Fatalf("GetEffective(%s) = v%d, want v%d", at, got.Version(), want.Version()) + } +} + +// readMaxPending reads one value from the stored jsonb document directly. +func (fixture policyFixture) readMaxPending(t *testing.T, id domain.PolicyVersionID) int32 { + t.Helper() + var value int32 + err := fixture.pool.QueryRow(fixture.ctx, + `SELECT (document -> 'invitations' ->> 'max_pending_per_need')::integer FROM policy_versions WHERE id = $1`, + id.UUID()).Scan(&value) + if err != nil { + t.Fatalf("read stored max_pending_per_need: %v", err) + } + return value +} + +func (fixture policyFixture) assertVersionCount(t *testing.T, want int) { + t.Helper() + var count int + if err := fixture.pool.QueryRow(fixture.ctx, `SELECT count(*) FROM policy_versions`).Scan(&count); err != nil { + t.Fatalf("count policy versions: %v", err) + } + if count != want { + t.Fatalf("policy_versions has %d rows, want %d", count, want) + } +} + +// newSizedPoolFor opens a pool with maxConns connections to databaseURL, so +// goroutines run at the same time instead of queueing for connections. +func newSizedPoolFor(ctx context.Context, t *testing.T, databaseURL string, maxConns int32) *pgxpool.Pool { + t.Helper() + poolConfig, err := pgxpool.ParseConfig(databaseURL) + if err != nil { + t.Fatalf("parse database URL: %v", err) + } + poolConfig.MaxConns = maxConns + pool, err := pgxpool.NewWithConfig(ctx, poolConfig) + if err != nil { + t.Fatalf("create sized PostgreSQL pool: %v", err) + } + t.Cleanup(pool.Close) + return pool +} + +// assertDatabaseTime checks that a time stamped by PostgreSQL is close to +// the moment the test started the statement. +func assertDatabaseTime(t *testing.T, name string, got, before time.Time) { + t.Helper() + if got.Before(before.Add(-databaseClockTolerance)) || got.After(time.Now().Add(databaseClockTolerance)) { + t.Fatalf("%s = %s, want the database clock near %s", name, got, before) + } +} + +// assertPolicyImmutable checks the raw trigger error and its mapping. +func assertPolicyImmutable(t *testing.T, statement string, err error) { + t.Helper() + var pgError *pgconn.PgError + if !errors.As(err, &pgError) || pgError.Code != policyImmutableSQLState || pgError.ConstraintName != policyImmutableConstraint { + t.Fatalf("%s error = %v, want SQLSTATE %s on %s", statement, err, policyImmutableSQLState, policyImmutableConstraint) + } + if mapped := postgresadapter.MapPolicyErrorForIntegrationTest(err); !errors.Is(mapped, outbound.ErrPolicyVersionImmutable) { + t.Fatalf("%s mapped error = %v, want ErrPolicyVersionImmutable", statement, mapped) + } + if strings.Contains(err.Error(), "operator:") { + t.Fatalf("%s error quotes row values: %v", statement, err) + } +} + +func assertSamePolicyVersion(t *testing.T, got, want domain.PolicyVersion) { + t.Helper() + if got.ID() != want.ID() || got.Key() != want.Key() || got.Version() != want.Version() || got.Kind() != want.Kind() || + got.Author() != want.Author() || !got.EffectiveAt().Equal(want.EffectiveAt()) || !got.CreatedAt().Equal(want.CreatedAt()) || + got.DocumentHash() != want.DocumentHash() || string(got.Document()) != string(want.Document()) { + t.Fatalf("policy version = %s %s v%d, want %s %s v%d with the same metadata and document", + got.ID(), got.Key(), got.Version(), want.ID(), want.Key(), want.Version()) + } +} + +// conflictCountingPolicies counts version number conflicts seen by Create. +type conflictCountingPolicies struct { + outbound.PolicyRepository + + conflicts atomic.Int64 +} + +func (policies *conflictCountingPolicies) Create(ctx context.Context, draft domain.PolicyVersionDraft) (domain.PolicyVersion, error) { + stored, err := policies.PolicyRepository.Create(ctx, draft) + if errors.Is(err, outbound.ErrPolicyVersionConflict) { + policies.conflicts.Add(1) + } + return stored, err +} diff --git a/backend/integration_test/postgres_migrations_test.go b/backend/integration_test/postgres_migrations_test.go index 9e18b5d..f9bef38 100644 --- a/backend/integration_test/postgres_migrations_test.go +++ b/backend/integration_test/postgres_migrations_test.go @@ -19,13 +19,20 @@ const ( concurrentMigrators = 4 ) -// identityMigrationVersion creates identityTableNames. -const identityMigrationVersion = 2 +const ( + // identityMigrationVersion creates identityTableNames. + identityMigrationVersion = 2 + // policyMigrationVersion creates policyTableNames and policyFunctionNames. + policyMigrationVersion = 3 +) var ( - // Tables created by 00001 and by 00002. + // Tables created by 00001, 00002, and 00003. outboxTables = []string{"outbox_events"} identityTableNames = []string{"users", "email_tokens", "sessions"} + policyTableNames = []string{"policy_versions"} + // Trigger functions created by 00003. + policyFunctionNames = []string{"policy_versions_refuse_change()", "policy_versions_stamp_creation()"} ) func TestPostgresMigrations(t *testing.T) { @@ -52,8 +59,10 @@ func TestPostgresMigrations(t *testing.T) { } assertTablesExist(ctx, t, pool, true, outboxTables...) assertTablesExist(ctx, t, pool, true, identityTableNames...) + assertTablesExist(ctx, t, pool, true, policyTableNames...) + assertFunctionsExist(ctx, t, pool, true, policyFunctionNames...) - identityRolledBack := false + identityRolledBack, policyRolledBack := false, false for rolledBack := 0; ; rolledBack++ { result, err := migrator.DownOne(ctx) if errors.Is(err, postgresadapter.ErrNoMigrationToRollBack) { @@ -65,6 +74,14 @@ func TestPostgresMigrations(t *testing.T) { if err != nil { t.Fatalf("DownOne() after %d rollbacks error = %v", rolledBack, err) } + if result.Version == policyMigrationVersion { + // The policy migration rolls back its table, triggers, and + // function and leaves the identity tables. + assertTablesExist(ctx, t, pool, false, policyTableNames...) + assertFunctionsExist(ctx, t, pool, false, policyFunctionNames...) + assertTablesExist(ctx, t, pool, true, identityTableNames...) + policyRolledBack = true + } if result.Version == identityMigrationVersion { // The identity migration rolls back on its own and leaves the // outbox migration before it. @@ -73,11 +90,12 @@ func TestPostgresMigrations(t *testing.T) { identityRolledBack = true } } - if !identityRolledBack { - t.Fatalf("migration %d was not rolled back", identityMigrationVersion) + if !identityRolledBack || !policyRolledBack { + t.Fatalf("migrations %d and %d were not both rolled back", identityMigrationVersion, policyMigrationVersion) } assertTablesExist(ctx, t, pool, false, outboxTables...) assertTablesExist(ctx, t, pool, false, identityTableNames...) + assertTablesExist(ctx, t, pool, false, policyTableNames...) var leftovers int err = pool.QueryRow(ctx, ` SELECT count(*) FROM pg_catalog.pg_class AS c @@ -89,6 +107,17 @@ func TestPostgresMigrations(t *testing.T) { if leftovers != 0 { t.Fatalf("%d relations remain after rolling back every migration", leftovers) } + var leftoverFunctions int + err = pool.QueryRow(ctx, ` + SELECT count(*) FROM pg_catalog.pg_proc AS p + JOIN pg_catalog.pg_namespace AS n ON n.oid = p.pronamespace + WHERE n.nspname = 'public'`).Scan(&leftoverFunctions) + if err != nil { + t.Fatalf("count leftover functions: %v", err) + } + if leftoverFunctions != 0 { + t.Fatalf("%d functions remain after rolling back every migration", leftoverFunctions) + } applied, err = migrator.Up(ctx) if err != nil { @@ -99,6 +128,8 @@ func TestPostgresMigrations(t *testing.T) { } assertTablesExist(ctx, t, pool, true, outboxTables...) assertTablesExist(ctx, t, pool, true, identityTableNames...) + assertTablesExist(ctx, t, pool, true, policyTableNames...) + assertFunctionsExist(ctx, t, pool, true, policyFunctionNames...) assertAllApplied(ctx, t, migrator, total) }) @@ -164,3 +195,16 @@ func assertTablesExist(ctx context.Context, t *testing.T, pool *pgxpool.Pool, wa } } } + +func assertFunctionsExist(ctx context.Context, t *testing.T, pool *pgxpool.Pool, want bool, signatures ...string) { + t.Helper() + for _, signature := range signatures { + var exists bool + if err := pool.QueryRow(ctx, `SELECT to_regprocedure($1) IS NOT NULL`, "public."+signature).Scan(&exists); err != nil { + t.Fatalf("check function %s: %v", signature, err) + } + if exists != want { + t.Fatalf("function %s exists = %t, want %t", signature, exists, want) + } + } +} diff --git a/backend/internal/adapter/secondary/postgres/integration_seam.go b/backend/internal/adapter/secondary/postgres/integration_seam.go index 0454d25..90618b3 100644 --- a/backend/internal/adapter/secondary/postgres/integration_seam.go +++ b/backend/internal/adapter/secondary/postgres/integration_seam.go @@ -18,3 +18,11 @@ func TransactionForIntegrationTest(unit outbound.UnitOfWork) (pgx.Tx, bool) { } return postgresUnit.tx, true } + +// MapPolicyErrorForIntegrationTest applies the policy error mapping to an +// error from a raw statement, so integration tests can prove that the +// database refusal of a policy change becomes the port sentinel. It is +// compiled only with the integration build tag. +func MapPolicyErrorForIntegrationTest(err error) error { + return mapPolicyError(err) +} diff --git a/backend/internal/adapter/secondary/postgres/policy.go b/backend/internal/adapter/secondary/postgres/policy.go new file mode 100644 index 0000000..bf9ed6e --- /dev/null +++ b/backend/internal/adapter/secondary/postgres/policy.go @@ -0,0 +1,187 @@ +package postgres + +import ( + "context" + "errors" + "fmt" + "time" + + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgconn" + "github.com/jackc/pgx/v5/pgtype" + "github.com/jackc/pgx/v5/pgxpool" + + "lincodex/backend/internal/adapter/secondary/postgres/sqlc" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" +) + +const ( + // integrityConstraintViolationCode is the SQLSTATE that the + // policy_versions_refuse_change trigger raises. + integrityConstraintViolationCode = "23000" + checkViolationCode = "23514" + // policyVersionsImmutableConstraint is the constraint name the trigger + // reports. It is not a table constraint; the trigger sets it so the error + // can be matched like one. + policyVersionsImmutableConstraint = "policy_versions_immutable" +) + +// policyConstraintErrors maps policy errors whose cause is a caller-visible +// outcome to port sentinels by SQLSTATE and constraint name, never by text. +// Unique violations do not occur: the insert uses ON CONFLICT DO NOTHING. +var policyConstraintErrors = map[constraintViolation]error{ + {integrityConstraintViolationCode, policyVersionsImmutableConstraint}: outbound.ErrPolicyVersionImmutable, + {checkViolationCode, "policy_versions_effective_after_creation"}: outbound.ErrPolicyVersionBackdated, +} + +// mapPolicyError turns a known policy constraint or trigger error into its +// port sentinel and keeps the constraint name. Any other PostgreSQL error is +// replaced by its SQLSTATE and constraint name, as the identity repositories +// do, so authors and document values never reach error text. Deadlocks and +// serialization failures also match ErrTransactionConflict. A connection +// error loses the pgx prefix that names the database user and database; +// other errors that do not come from PostgreSQL pass through. +func mapPolicyError(err error) error { + var pgError *pgconn.PgError + if !errors.As(err, &pgError) { + return sanitizeConnectError(err) + } + if sentinel, ok := policyConstraintErrors[constraintViolation{code: pgError.Code, constraint: pgError.ConstraintName}]; ok { + return fmt.Errorf("postgres.mapPolicyError - violate constraint %s: %w", pgError.ConstraintName, sentinel) + } + return markTransactionConflict(&databaseError{code: pgError.Code, constraint: pgError.ConstraintName}) +} + +// PolicyStore provides the policy repository outside a transaction. Every +// call runs as its own statement on a pool connection. Called with a context +// that belongs to a Transactor callback, it fails with +// outbound.ErrNestedTransaction; use UnitOfWork.Policies there. +type PolicyStore struct { + queries *sqlc.Queries +} + +func NewPolicyStore(pool *pgxpool.Pool) *PolicyStore { + return &PolicyStore{queries: sqlc.New(standaloneDB{pool: pool})} +} + +func (store *PolicyStore) Policies() outbound.PolicyRepository { + return policyRepository{queries: store.queries} +} + +func (unit *UnitOfWork) Policies() outbound.PolicyRepository { + return policyRepository{queries: unit.queries} +} + +type policyRepository struct { + queries *sqlc.Queries +} + +var _ outbound.PolicyRepository = policyRepository{} + +func (repository policyRepository) Create(ctx context.Context, draft domain.PolicyVersionDraft) (domain.PolicyVersion, error) { + if draft.IsZero() || draft.Version() <= 0 { + return domain.PolicyVersion{}, fmt.Errorf("policyRepository.Create - draft was not built and numbered by domain.NewPolicyVersionDraft: %w", domain.ErrInvalidPolicyVersion) + } + effectiveAt := pgtype.Timestamptz{} + if scheduled, ok := draft.EffectiveAt(); ok { + effectiveAt = pgTime(scheduled) + } + hash := draft.DocumentHash() + row, err := repository.queries.InsertPolicyVersion(ctx, sqlc.InsertPolicyVersionParams{ + ID: pgUUID(draft.ID().UUID()), + PolicyKey: string(draft.Key()), + Version: draft.Version(), + Kind: string(draft.Kind()), + EffectiveAt: effectiveAt, + Author: string(draft.Author()), + Document: draft.Document(), + DocumentSha256: hash[:], + }) + if errors.Is(err, pgx.ErrNoRows) { + return domain.PolicyVersion{}, fmt.Errorf("policyRepository.Create - insert %s version %d: %w", draft.Key(), draft.Version(), outbound.ErrPolicyVersionConflict) + } + if err != nil { + return domain.PolicyVersion{}, fmt.Errorf("policyRepository.Create - insert policy version: %w", mapPolicyError(err)) + } + return policyVersionFromRow(row) +} + +func (repository policyRepository) GetByID(ctx context.Context, id domain.PolicyVersionID) (domain.PolicyVersion, error) { + row, err := repository.queries.GetPolicyVersionByID(ctx, pgUUID(id.UUID())) + if err != nil { + return domain.PolicyVersion{}, fmt.Errorf("policyRepository.GetByID - select policy version: %w", mapPolicyNoRows(err)) + } + return policyVersionFromRow(row) +} + +func (repository policyRepository) GetEffective(ctx context.Context, key domain.PolicyKey, at time.Time) (domain.PolicyVersion, error) { + if err := requireTime("policyRepository.GetEffective", at, domain.ErrInvalidPolicyVersion); err != nil { + return domain.PolicyVersion{}, err + } + if err := requireKnownFamily("policyRepository.GetEffective", key); err != nil { + return domain.PolicyVersion{}, err + } + row, err := repository.queries.GetEffectivePolicyVersion(ctx, sqlc.GetEffectivePolicyVersionParams{ + PolicyKey: string(key), + At: pgTime(at), + }) + if err != nil { + return domain.PolicyVersion{}, fmt.Errorf("policyRepository.GetEffective - select policy version: %w", mapPolicyNoRows(err)) + } + return policyVersionFromRow(row) +} + +func (repository policyRepository) GetLatest(ctx context.Context, key domain.PolicyKey) (domain.PolicyVersion, error) { + if err := requireKnownFamily("policyRepository.GetLatest", key); err != nil { + return domain.PolicyVersion{}, err + } + row, err := repository.queries.GetLatestPolicyVersion(ctx, string(key)) + if err != nil { + return domain.PolicyVersion{}, fmt.Errorf("policyRepository.GetLatest - select policy version: %w", mapPolicyNoRows(err)) + } + return policyVersionFromRow(row) +} + +func (repository policyRepository) HasVersions(ctx context.Context, key domain.PolicyKey) (bool, error) { + if err := requireKnownFamily("policyRepository.HasVersions", key); err != nil { + return false, err + } + present, err := repository.queries.PolicyVersionExists(ctx, string(key)) + if err != nil { + return false, fmt.Errorf("policyRepository.HasVersions - check policy versions: %w", mapPolicyError(err)) + } + return present, nil +} + +func requireKnownFamily(location string, key domain.PolicyKey) error { + if _, err := domain.ParsePolicyKey(string(key)); err != nil { + return fmt.Errorf("%s - validate family: %w", location, err) + } + return nil +} + +func mapPolicyNoRows(err error) error { + if errors.Is(err, pgx.ErrNoRows) { + return outbound.ErrPolicyVersionNotFound + } + return mapPolicyError(err) +} + +func policyVersionFromRow(row sqlc.PolicyVersion) (domain.PolicyVersion, error) { + version, err := domain.RestorePolicyVersion(domain.StoredPolicyVersion{ + ID: domain.PolicyVersionID(row.ID.Bytes), + Key: row.PolicyKey, + Version: row.Version, + Kind: row.Kind, + Author: row.Author, + EffectiveAt: row.EffectiveAt.Time, + CreatedAt: row.CreatedAt.Time, + Document: row.Document, + DocumentHash: row.DocumentSha256, + }) + if err != nil { + return domain.PolicyVersion{}, fmt.Errorf("postgres.policyVersionFromRow - restore policy version: %w", err) + } + return version, nil +} diff --git a/backend/internal/adapter/secondary/postgres/policy_test.go b/backend/internal/adapter/secondary/postgres/policy_test.go new file mode 100644 index 0000000..586ebb5 --- /dev/null +++ b/backend/internal/adapter/secondary/postgres/policy_test.go @@ -0,0 +1,89 @@ +package postgres + +import ( + "context" + "errors" + "strings" + "testing" + "time" + + "github.com/jackc/pgx/v5/pgconn" + + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" +) + +func TestMapPolicyErrorRecognizesPolicyConstraints(t *testing.T) { + tests := []struct { + code string + constraint string + want error + }{ + {code: integrityConstraintViolationCode, constraint: policyVersionsImmutableConstraint, want: outbound.ErrPolicyVersionImmutable}, + {code: checkViolationCode, constraint: "policy_versions_effective_after_creation", want: outbound.ErrPolicyVersionBackdated}, + } + for _, test := range tests { + err := mapPolicyError(&pgconn.PgError{Code: test.code, ConstraintName: test.constraint, Detail: "Key (author)=(operator:secret) already exists."}) + if !errors.Is(err, test.want) { + t.Fatalf("mapPolicyError(%s %s) = %v, want %v", test.code, test.constraint, err, test.want) + } + if !strings.Contains(err.Error(), test.constraint) || strings.Contains(err.Error(), "secret") { + t.Fatalf("mapPolicyError(%s) = %v, want the constraint name and no detail", test.constraint, err) + } + } +} + +func TestMapPolicyErrorMatchesCodeAndConstraintTogether(t *testing.T) { + // The immutability sentinel needs both the trigger's SQLSTATE and its + // constraint name; either one alone is another error. + for _, original := range []*pgconn.PgError{ + {Code: "P0001", ConstraintName: policyVersionsImmutableConstraint, Message: "policy versions are immutable"}, + {Code: integrityConstraintViolationCode, ConstraintName: "other_constraint", Message: "policy versions are immutable"}, + } { + err := mapPolicyError(original) + if errors.Is(err, outbound.ErrPolicyVersionImmutable) { + t.Fatalf("mapPolicyError(%s %s) = %v, want no immutability sentinel", original.Code, original.ConstraintName, err) + } + var stateError sqlStateError + if !errors.As(err, &stateError) || stateError.SQLState() != original.Code || strings.Contains(err.Error(), "are immutable") { + t.Fatalf("mapPolicyError() = %v, want only SQLSTATE %s and the constraint", err, original.Code) + } + } +} + +func TestMapPolicyErrorKeepsOtherErrors(t *testing.T) { + for _, original := range []error{context.Canceled, outbound.ErrNestedTransaction} { + if err := mapPolicyError(original); !errors.Is(err, original) { + t.Fatalf("mapPolicyError(%v) = %v, want the original error", original, err) + } + } +} + +func TestPolicyRepositoryRejectsInvalidInputBeforeQuerying(t *testing.T) { + // A repository without queries proves that no statement runs. + repository := policyRepository{} + if _, err := repository.Create(t.Context(), domain.PolicyVersionDraft{}); !errors.Is(err, domain.ErrInvalidPolicyVersion) { + t.Fatalf("Create(zero draft) error = %v, want ErrInvalidPolicyVersion", err) + } + draft, err := domain.NewPolicyVersionDraft(domain.NewPolicyVersionDraftInput{ + Key: domain.ProductPolicyKey, Kind: domain.PolicyKindDemo, Author: domain.DemoPolicySeedAuthor, Policy: domain.DemoProductPolicyV1(), + }) + if err != nil { + t.Fatalf("NewPolicyVersionDraft() error = %v", err) + } + if _, err := repository.Create(t.Context(), draft); !errors.Is(err, domain.ErrInvalidPolicyVersion) { + t.Fatalf("Create(unnumbered draft) error = %v, want ErrInvalidPolicyVersion", err) + } + if _, err := repository.GetEffective(t.Context(), domain.ProductPolicyKey, time.Time{}); !errors.Is(err, domain.ErrInvalidPolicyVersion) { + t.Fatalf("GetEffective(zero time) error = %v, want ErrInvalidPolicyVersion", err) + } + if _, err := repository.GetEffective(t.Context(), "other", time.Now()); !errors.Is(err, domain.ErrInvalidPolicyVersion) { + t.Fatalf("GetEffective(unknown family) error = %v, want ErrInvalidPolicyVersion", err) + } + if _, err := repository.GetLatest(t.Context(), "other"); !errors.Is(err, domain.ErrInvalidPolicyVersion) { + t.Fatalf("GetLatest(unknown family) error = %v, want ErrInvalidPolicyVersion", err) + } + if _, err := repository.HasVersions(t.Context(), "other"); !errors.Is(err, domain.ErrInvalidPolicyVersion) { + t.Fatalf("HasVersions(unknown family) error = %v, want ErrInvalidPolicyVersion", err) + } +} diff --git a/backend/internal/adapter/secondary/postgres/sqlc/models.go b/backend/internal/adapter/secondary/postgres/sqlc/models.go index 8c5461c..5b96401 100644 --- a/backend/internal/adapter/secondary/postgres/sqlc/models.go +++ b/backend/internal/adapter/secondary/postgres/sqlc/models.go @@ -33,6 +33,18 @@ type OutboxEvent struct { PublishedAt pgtype.Timestamptz } +type PolicyVersion struct { + ID pgtype.UUID + PolicyKey string + Version int32 + Kind string + EffectiveAt pgtype.Timestamptz + Author string + Document []byte + DocumentSha256 []byte + CreatedAt pgtype.Timestamptz +} + type Session struct { ID pgtype.UUID UserID pgtype.UUID diff --git a/backend/internal/adapter/secondary/postgres/sqlc/policy.sql.go b/backend/internal/adapter/secondary/postgres/sqlc/policy.sql.go new file mode 100644 index 0000000..e904340 --- /dev/null +++ b/backend/internal/adapter/secondary/postgres/sqlc/policy.sql.go @@ -0,0 +1,214 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.31.1 +// source: policy.sql + +package sqlc + +import ( + "context" + + "github.com/jackc/pgx/v5/pgtype" +) + +const getEffectivePolicyVersion = `-- name: GetEffectivePolicyVersion :one +SELECT + id, + policy_key, + version, + kind, + effective_at, + author, + document, + document_sha256, + created_at +FROM policy_versions +WHERE + policy_key = $1 + AND effective_at <= $2 +ORDER BY version DESC +LIMIT 1 +` + +type GetEffectivePolicyVersionParams struct { + PolicyKey string + At pgtype.Timestamptz +} + +// Among the versions of a family already effective at a time, the newest +// publication wins. A version scheduled for later therefore never undoes a +// version published after it. The unique (policy_key, version) index serves +// the backward scan. +func (q *Queries) GetEffectivePolicyVersion(ctx context.Context, arg GetEffectivePolicyVersionParams) (PolicyVersion, error) { + row := q.db.QueryRow(ctx, getEffectivePolicyVersion, arg.PolicyKey, arg.At) + var i PolicyVersion + err := row.Scan( + &i.ID, + &i.PolicyKey, + &i.Version, + &i.Kind, + &i.EffectiveAt, + &i.Author, + &i.Document, + &i.DocumentSha256, + &i.CreatedAt, + ) + return i, err +} + +const getLatestPolicyVersion = `-- name: GetLatestPolicyVersion :one +SELECT + id, + policy_key, + version, + kind, + effective_at, + author, + document, + document_sha256, + created_at +FROM policy_versions +WHERE policy_key = $1 +ORDER BY version DESC +LIMIT 1 +` + +func (q *Queries) GetLatestPolicyVersion(ctx context.Context, policyKey string) (PolicyVersion, error) { + row := q.db.QueryRow(ctx, getLatestPolicyVersion, policyKey) + var i PolicyVersion + err := row.Scan( + &i.ID, + &i.PolicyKey, + &i.Version, + &i.Kind, + &i.EffectiveAt, + &i.Author, + &i.Document, + &i.DocumentSha256, + &i.CreatedAt, + ) + return i, err +} + +const getPolicyVersionByID = `-- name: GetPolicyVersionByID :one +SELECT + id, + policy_key, + version, + kind, + effective_at, + author, + document, + document_sha256, + created_at +FROM policy_versions +WHERE id = $1 +` + +func (q *Queries) GetPolicyVersionByID(ctx context.Context, id pgtype.UUID) (PolicyVersion, error) { + row := q.db.QueryRow(ctx, getPolicyVersionByID, id) + var i PolicyVersion + err := row.Scan( + &i.ID, + &i.PolicyKey, + &i.Version, + &i.Kind, + &i.EffectiveAt, + &i.Author, + &i.Document, + &i.DocumentSha256, + &i.CreatedAt, + ) + return i, err +} + +const insertPolicyVersion = `-- name: InsertPolicyVersion :one +INSERT INTO policy_versions ( + id, + policy_key, + version, + kind, + effective_at, + author, + document, + document_sha256 +) VALUES ( + $1, + $2, + $3, + $4, + $5, + $6, + $7, + $8 +) +ON CONFLICT DO NOTHING +RETURNING + id, + policy_key, + version, + kind, + effective_at, + author, + document, + document_sha256, + created_at +` + +type InsertPolicyVersionParams struct { + ID pgtype.UUID + PolicyKey string + Version int32 + Kind string + EffectiveAt pgtype.Timestamptz + Author string + Document []byte + DocumentSha256 []byte +} + +// Stores a version and returns the stored row with the publication time and +// effective time set by the stamp trigger. A taken ID or version number +// returns no row instead of an error, so a conflict does not abort the +// surrounding transaction. created_at is never taken from the caller, and a +// NULL effective_at means "at publication". +func (q *Queries) InsertPolicyVersion(ctx context.Context, arg InsertPolicyVersionParams) (PolicyVersion, error) { + row := q.db.QueryRow(ctx, insertPolicyVersion, + arg.ID, + arg.PolicyKey, + arg.Version, + arg.Kind, + arg.EffectiveAt, + arg.Author, + arg.Document, + arg.DocumentSha256, + ) + var i PolicyVersion + err := row.Scan( + &i.ID, + &i.PolicyKey, + &i.Version, + &i.Kind, + &i.EffectiveAt, + &i.Author, + &i.Document, + &i.DocumentSha256, + &i.CreatedAt, + ) + return i, err +} + +const policyVersionExists = `-- name: PolicyVersionExists :one +SELECT exists( + SELECT 1 FROM policy_versions + WHERE policy_key = $1 +) AS present +` + +// Reports whether a family has any version without reading a document, so a +// caller that only needs presence never depends on decoding. +func (q *Queries) PolicyVersionExists(ctx context.Context, policyKey string) (bool, error) { + row := q.db.QueryRow(ctx, policyVersionExists, policyKey) + var present bool + err := row.Scan(&present) + return present, err +} diff --git a/backend/internal/adapter/secondary/postgres/sqlc/querier.go b/backend/internal/adapter/secondary/postgres/sqlc/querier.go index eef61c1..39ee297 100644 --- a/backend/internal/adapter/secondary/postgres/sqlc/querier.go +++ b/backend/internal/adapter/secondary/postgres/sqlc/querier.go @@ -33,12 +33,25 @@ type Querier interface { // statement was locked above. DeleteUnverifiedUsersRegisteredBefore(ctx context.Context, arg DeleteUnverifiedUsersRegisteredBeforeParams) (int64, error) GetActiveSessionByTokenHash(ctx context.Context, arg GetActiveSessionByTokenHashParams) (Session, error) + // Among the versions of a family already effective at a time, the newest + // publication wins. A version scheduled for later therefore never undoes a + // version published after it. The unique (policy_key, version) index serves + // the backward scan. + GetEffectivePolicyVersion(ctx context.Context, arg GetEffectivePolicyVersionParams) (PolicyVersion, error) // Explains why ConsumeEmailToken matched no row. GetEmailTokenState(ctx context.Context, arg GetEmailTokenStateParams) (GetEmailTokenStateRow, error) + GetLatestPolicyVersion(ctx context.Context, policyKey string) (PolicyVersion, error) + GetPolicyVersionByID(ctx context.Context, id pgtype.UUID) (PolicyVersion, error) GetUserByEmailNormalized(ctx context.Context, emailNormalized string) (User, error) GetUserByID(ctx context.Context, id pgtype.UUID) (User, error) InsertEmailToken(ctx context.Context, arg InsertEmailTokenParams) error InsertOutboxEvent(ctx context.Context, arg InsertOutboxEventParams) error + // Stores a version and returns the stored row with the publication time and + // effective time set by the stamp trigger. A taken ID or version number + // returns no row instead of an error, so a conflict does not abort the + // surrounding transaction. created_at is never taken from the caller, and a + // NULL effective_at means "at publication". + InsertPolicyVersion(ctx context.Context, arg InsertPolicyVersionParams) (PolicyVersion, error) InsertSession(ctx context.Context, arg InsertSessionParams) error InsertUser(ctx context.Context, arg InsertUserParams) error InvalidateActiveEmailTokens(ctx context.Context, arg InvalidateActiveEmailTokensParams) (int64, error) @@ -46,6 +59,9 @@ type Querier interface { // was issued for. MarkUserEmailVerified(ctx context.Context, arg MarkUserEmailVerifiedParams) (User, error) Ping(ctx context.Context) (int32, error) + // Reports whether a family has any version without reading a document, so a + // caller that only needs presence never depends on decoding. + PolicyVersionExists(ctx context.Context, policyKey string) (bool, error) RevokeSession(ctx context.Context, arg RevokeSessionParams) (int64, error) RevokeUserSessions(ctx context.Context, arg RevokeUserSessionsParams) (int64, error) // Records activity on an active session and reports whether it is active. diff --git a/backend/internal/bootstrap/app.go b/backend/internal/bootstrap/app.go index b44e44c..873ab7f 100644 --- a/backend/internal/bootstrap/app.go +++ b/backend/internal/bootstrap/app.go @@ -84,7 +84,8 @@ func run(ctx context.Context, config config.Config, logger *slog.Logger) error { // start prepares the application without opening listeners. The mail // transport is selected before migrations, so a configuration that cannot -// start never changes the database. +// start never changes the database. The demo policy seed runs after the +// migrations that create its table. func start(ctx context.Context, config config.Config, logger *slog.Logger) (*Application, func(), error) { if err := config.Validate(); err != nil { return nil, nil, fmt.Errorf("bootstrap.start - validate configuration: %w", err) @@ -96,6 +97,9 @@ func start(ctx context.Context, config config.Config, logger *slog.Logger) (*App if err := migrateDatabase(ctx, config, logger); err != nil { return nil, nil, fmt.Errorf("bootstrap.start - migrate database: %w", err) } + if err := seedDemoPolicy(ctx, config, logger); err != nil { + return nil, nil, fmt.Errorf("bootstrap.start - seed demo policy: %w", err) + } application, cleanup, err := initialize(ctx, config, logger, mailSender) if err != nil { return nil, nil, fmt.Errorf("bootstrap.start - initialize application: %w", err) diff --git a/backend/internal/bootstrap/policy.go b/backend/internal/bootstrap/policy.go new file mode 100644 index 0000000..0f5fc03 --- /dev/null +++ b/backend/internal/bootstrap/policy.go @@ -0,0 +1,57 @@ +package bootstrap + +import ( + "context" + "fmt" + "log/slog" + "time" + + "lincodex/backend/config" + "lincodex/backend/internal/adapter/secondary/postgres" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/usecase/policy" +) + +// startupPolicySeedTimeout bounds the demo policy seed, which reads one row +// and inserts at most one. +const startupPolicySeedTimeout = 30 * time.Second + +// seedDemoPolicy publishes the demo product policy as version 1 when the +// product family has no version yet, so a fresh database has an effective +// policy as soon as the service starts. It runs right after the startup +// migrations and under the same switch: it is skipped when +// DATABASE_MIGRATE_ON_START is false or DATABASE_URL is unset, and then a +// developer who migrates by hand also starts without a seeded policy. It +// checks presence only, so an existing version, even one this build cannot +// decode, is left alone and does not block startup. A database error stops +// startup, like a failed migration. +func seedDemoPolicy(ctx context.Context, settings config.Config, logger *slog.Logger) error { + if !settings.DatabaseMigrateOnStart || settings.DatabaseURL == "" { + return nil + } + pool, err := postgres.NewPool(ctx, settings.DatabaseURL) + if err != nil { + return fmt.Errorf("bootstrap.seedDemoPolicy - create pool: %w", err) + } + defer pool.Close() + ctx, cancel := context.WithTimeout(ctx, startupPolicySeedTimeout) + defer cancel() + publisher := policy.NewPublisher(postgres.NewPolicyStore(pool).Policies(), time.Now) + result, err := publisher.EnsureDemoProductPolicy(ctx) + if err != nil { + return fmt.Errorf("bootstrap.seedDemoPolicy - ensure demo product policy: %w", err) + } + if !result.Created { + logger.Info("product policy already present; demo seed skipped", + slog.String("policy_key", string(domain.ProductPolicyKey)), + ) + return nil + } + logger.Info("demo product policy published", + slog.String("policy_key", string(result.Version.Key())), + slog.Int("policy_version", int(result.Version.Version())), + slog.String("policy_kind", string(result.Version.Kind())), + slog.String("policy_version_id", result.Version.ID().String()), + ) + return nil +} diff --git a/backend/internal/bootstrap/policy_test.go b/backend/internal/bootstrap/policy_test.go new file mode 100644 index 0000000..c3a5600 --- /dev/null +++ b/backend/internal/bootstrap/policy_test.go @@ -0,0 +1,42 @@ +package bootstrap + +import ( + "log/slog" + "strings" + "testing" + + "lincodex/backend/config" +) + +func TestSeedDemoPolicySkipsWithoutStartupMigrations(t *testing.T) { + tests := []struct { + name string + settings config.Config + }{ + // An unreachable address proves that no connection is attempted. + {name: "startup migrations disabled", settings: config.Config{DatabaseMigrateOnStart: false, DatabaseURL: "postgres://app@db:not-a-port/app"}}, + {name: "database not configured", settings: config.Config{DatabaseMigrateOnStart: true}}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + if err := seedDemoPolicy(t.Context(), test.settings, slog.New(slog.DiscardHandler)); err != nil { + t.Fatalf("seedDemoPolicy() error = %v", err) + } + }) + } +} + +func TestSeedDemoPolicyHidesConnectionStringOnFailure(t *testing.T) { + const password = "seed-secret-password" + settings := config.Config{ + DatabaseMigrateOnStart: true, + DatabaseURL: "postgres://app:" + password + "@db:not-a-port/app", + } + err := seedDemoPolicy(t.Context(), settings, slog.New(slog.DiscardHandler)) + if err == nil { + t.Fatal("seedDemoPolicy() accepted an invalid DATABASE_URL") + } + if strings.Contains(err.Error(), password) || strings.Contains(err.Error(), "db:not-a-port") { + t.Fatalf("seedDemoPolicy() error exposes the connection string: %v", err) + } +} diff --git a/backend/internal/domain/policy.go b/backend/internal/domain/policy.go new file mode 100644 index 0000000..79d9f85 --- /dev/null +++ b/backend/internal/domain/policy.go @@ -0,0 +1,415 @@ +package domain + +import ( + "errors" + "fmt" + "slices" + "time" +) + +// ErrInvalidPolicy reports a policy value that is missing, out of range, or +// inconsistent with another value of the same policy. +var ErrInvalidPolicy = errors.New("invalid policy") + +// Units of policy values. Every value carries its unit in its type and in its +// document field name, so a number never changes meaning between code and +// storage. +type ( + // CalendarDays counts whole days of 24 hours. Duration does not follow + // daylight saving shifts; deadlines are computed in UTC. + CalendarDays int32 + + // BusinessDays counts working days. Converting it to a deadline needs a + // business calendar, which the consuming feature defines, so it has no + // Duration method. + BusinessDays int32 + + // Hours counts whole hours. + Hours int32 + + // BasisPoints is a non-negative decimal with four fractional digits, + // stored as an integer count of 0.0001 units: 0.80 is 8000. Thresholds + // compare exactly, without the drift of binary floating point, and the + // document keeps an integer that every JSON reader decodes the same way. + BasisPoints int32 +) + +// basisPointsPerUnit is the BasisPoints value of 1.0. +const basisPointsPerUnit BasisPoints = 10000 + +func (days CalendarDays) Duration() time.Duration { return time.Duration(days) * 24 * time.Hour } + +func (hours Hours) Duration() time.Duration { return time.Duration(hours) * time.Hour } + +// String formats the value as a decimal, for example "0.8000". +func (points BasisPoints) String() string { + return fmt.Sprintf("%d.%04d", points/basisPointsPerUnit, points%basisPointsPerUnit) +} + +// Sanity bounds of policy values. They reject typing mistakes such as a +// value in the wrong unit; they are not product decisions, which the policy +// values themselves record. +const ( + maxResponseDeadlineOptions = 5 + maxResponseDeadline = CalendarDays(30) + maxPendingInvitationsPerNeed = 1000 + maxRepeatAfterDecline = CalendarDays(365) + maxInterviewProposalDeadline = BusinessDays(30) + maxNoDealPause = CalendarDays(365) + maxInvitationQuotaWindow = CalendarDays(31) + maxCardViewQuotaWindow = Hours(7 * 24) + maxTierQuotaLimit = 100000 + maxSameGradeRetryInterval = CalendarDays(365) + maxAssessmentAttemptsPerWindow = 20 + maxAssessmentAttemptWindow = CalendarDays(730) + maxPromotionInterval = CalendarDays(730) + maxScoredItems = 200 + maxSeedItems = 20 + maxVerificationTokenLifetime = Hours(7 * 24) + maxUnverifiedAccountLifetime = CalendarDays(90) + maxSessionIdleTimeout = Hours(30 * 24) + maxSessionAbsoluteLifetime = CalendarDays(90) + maxSearchingConfirmationInterval = CalendarDays(365) + minExclusiveProbabilityBasisPoints = BasisPoints(1) + maxExclusiveProbabilityBasisPoints = basisPointsPerUnit - 1 + minPositiveStandardErrorBasisPoints = BasisPoints(1) +) + +// ProductPolicy holds the deadlines, quotas, thresholds, and coefficients +// that product rules read. A stored policy is immutable: a change is a new +// PolicyVersion, and records built under a policy keep the version they used. +type ProductPolicy struct { + Invitations InvitationPolicy + OrganizationQuotas OrganizationQuotaPolicy + Assessment AssessmentPolicy + Identity IdentityPolicy + SearchStatus SearchStatusPolicy +} + +// Validate checks every section. A zero value is never valid, so a section +// that was left out fails instead of silently meaning zero. +func (policy ProductPolicy) Validate() error { + for _, validate := range []func() error{ + policy.Invitations.Validate, + policy.OrganizationQuotas.Validate, + policy.Assessment.Validate, + policy.Identity.Validate, + policy.SearchStatus.Validate, + } { + if err := validate(); err != nil { + return err + } + } + return nil +} + +// clone copies the slices, so a caller cannot change a stored version through +// a returned policy. +func (policy ProductPolicy) clone() ProductPolicy { + copied := policy + copied.Invitations.ResponseDeadlineOptions = slices.Clone(policy.Invitations.ResponseDeadlineOptions) + return copied +} + +// InvitationPolicy governs salary offers sent to candidates. +type InvitationPolicy struct { + // ResponseDeadlineOptions are the response deadlines an employer may + // choose, in strictly increasing order. + ResponseDeadlineOptions []CalendarDays + // DefaultResponseDeadline is one of ResponseDeadlineOptions. + DefaultResponseDeadline CalendarDays + // MaxPendingPerNeed limits unanswered invitations for one employer need. + MaxPendingPerNeed int32 + // RepeatAfterDecline is the pause before the same company may invite a + // candidate who declined. + RepeatAfterDecline CalendarDays + // InterviewProposalDeadline is the time the employer has to propose an + // interview after acceptance. + InterviewProposalDeadline BusinessDays + // NoDealPause is the pause after a contact that ended without a deal. + NoDealPause CalendarDays +} + +func (policy InvitationPolicy) Validate() error { + const location = "InvitationPolicy.Validate" + options := policy.ResponseDeadlineOptions + if len(options) == 0 || len(options) > maxResponseDeadlineOptions { + return invalidPolicy(location, fmt.Sprintf("invitations.response_deadline_options_days must have 1 to %d values", maxResponseDeadlineOptions)) + } + for index, option := range options { + if err := checkRange(location, "invitations.response_deadline_options_days", option, 1, maxResponseDeadline); err != nil { + return err + } + if index > 0 && option <= options[index-1] { + return invalidPolicy(location, "invitations.response_deadline_options_days must be strictly increasing") + } + } + if !slices.Contains(options, policy.DefaultResponseDeadline) { + return invalidPolicy(location, "invitations.default_response_deadline_days must be one of the response deadline options") + } + return firstError( + checkRange(location, "invitations.max_pending_per_need", policy.MaxPendingPerNeed, 1, maxPendingInvitationsPerNeed), + checkRange(location, "invitations.repeat_after_decline_days", policy.RepeatAfterDecline, 1, maxRepeatAfterDecline), + checkRange(location, "invitations.interview_proposal_deadline_business_days", policy.InterviewProposalDeadline, 1, maxInterviewProposalDeadline), + checkRange(location, "invitations.no_deal_pause_days", policy.NoDealPause, 1, maxNoDealPause), + ) +} + +// OrganizationTier is an employer trust level. Levels are ordered E0 < E1 < +// E2; the rules that move an organization between them belong to the quota +// feature, not to the policy. E0 is the level every organization starts at. +type OrganizationTier string + +const ( + OrganizationTierE0 OrganizationTier = "e0" + OrganizationTierE1 OrganizationTier = "e1" + OrganizationTierE2 OrganizationTier = "e2" +) + +// ParseOrganizationTier accepts e0, e1, or e2. +func ParseOrganizationTier(value string) (OrganizationTier, error) { + tier := OrganizationTier(value) + switch tier { + case OrganizationTierE0, OrganizationTierE1, OrganizationTierE2: + return tier, nil + default: + return "", invalidPolicy("domain.ParseOrganizationTier", "tier must be e0, e1, or e2") + } +} + +// OrganizationQuotaPolicy limits employer activity per trust level. Limits +// apply per rolling window. +type OrganizationQuotaPolicy struct { + InvitationWindow CalendarDays + CardViewWindow Hours + TierE0 OrganizationTierQuota + TierE1 OrganizationTierQuota + TierE2 OrganizationTierQuota +} + +// OrganizationTierQuota is the quota of one level. An inactive level keeps +// its limits for the time it is enabled, but no organization can hold it +// before that. E0 is always active, and the active levels form a prefix: a +// level is active only when every lower level is. +type OrganizationTierQuota struct { + Active bool + InvitationsPerWindow int32 + DistinctCardViewsPerWindow int32 +} + +// Tier returns the quota of a level. An unknown level returns +// ErrInvalidPolicy; callers check Active before assigning a level. +func (policy OrganizationQuotaPolicy) Tier(tier OrganizationTier) (OrganizationTierQuota, error) { + switch tier { + case OrganizationTierE0: + return policy.TierE0, nil + case OrganizationTierE1: + return policy.TierE1, nil + case OrganizationTierE2: + return policy.TierE2, nil + default: + return OrganizationTierQuota{}, invalidPolicy("OrganizationQuotaPolicy.Tier", "tier must be e0, e1, or e2") + } +} + +func (policy OrganizationQuotaPolicy) Validate() error { + const location = "OrganizationQuotaPolicy.Validate" + if err := firstError( + checkRange(location, "organization_quotas.invitation_window_days", policy.InvitationWindow, 1, maxInvitationQuotaWindow), + checkRange(location, "organization_quotas.card_view_window_hours", policy.CardViewWindow, 1, maxCardViewQuotaWindow), + ); err != nil { + return err + } + if !policy.TierE0.Active { + return invalidPolicy(location, "organization_quotas.tiers.e0 must be active, because every organization starts there") + } + tiers := []struct { + name OrganizationTier + quota OrganizationTierQuota + }{ + {name: OrganizationTierE0, quota: policy.TierE0}, + {name: OrganizationTierE1, quota: policy.TierE1}, + {name: OrganizationTierE2, quota: policy.TierE2}, + } + // The zero quota is below every valid limit and counts as active, so the + // lowest level passes the ordering checks. + lower := OrganizationTierQuota{Active: true} + for _, tier := range tiers { + prefix := "organization_quotas.tiers." + string(tier.name) + if err := firstError( + checkRange(location, prefix+".invitations_per_window", tier.quota.InvitationsPerWindow, 1, maxTierQuotaLimit), + checkRange(location, prefix+".distinct_card_views_per_window", tier.quota.DistinctCardViewsPerWindow, 1, maxTierQuotaLimit), + ); err != nil { + return err + } + if tier.quota.Active && !lower.Active { + return invalidPolicy(location, prefix+" cannot be active while a lower tier is inactive") + } + // A higher level is granted after more trust, so it never has a + // smaller limit than the level below it. + if tier.quota.InvitationsPerWindow < lower.InvitationsPerWindow || + tier.quota.DistinctCardViewsPerWindow < lower.DistinctCardViewsPerWindow { + return invalidPolicy(location, prefix+" limits must not be lower than the tier below") + } + lower = tier.quota + } + return nil +} + +// AssessmentCalibration records whether assessment thresholds come from a +// calibration study. +type AssessmentCalibration string + +const ( + // AssessmentCalibrationUncalibratedInitial marks initial values chosen for + // verification of the product flow. They make no psychometric claim. + AssessmentCalibrationUncalibratedInitial AssessmentCalibration = "uncalibrated_initial" + // AssessmentCalibrationCalibrated marks values backed by a pilot and a + // documented calibration. + AssessmentCalibrationCalibrated AssessmentCalibration = "calibrated" +) + +// AssessmentPolicy governs grade assessment attempts and decisions. P_G is +// the estimated probability that the candidate meets the claimed grade. +type AssessmentPolicy struct { + Calibration AssessmentCalibration + // SameGradeRetryAfter is the pause before another attempt at the same + // grade. + SameGradeRetryAfter CalendarDays + // MaxAttemptsPerWindow limits attempts in any AttemptWindow. Whether the + // limit counts per grade, per specialty, or across all assessments of a + // candidate is an open question for the attempt tasks (TASK-157 and + // TASK-158); the policy stores only the number. + MaxAttemptsPerWindow int32 + AttemptWindow CalendarDays + // PromotionMinInterval is the minimum time between grade promotions. + PromotionMinInterval CalendarDays + // ConfirmationThreshold is the lowest P_G that confirms the grade. + ConfirmationThreshold BasisPoints + // HighStrengthThreshold is the lowest P_G reported as a strong result. + HighStrengthThreshold BasisPoints + // PracticeRequired makes the unscored practice block mandatory before a + // scored attempt. + PracticeRequired bool + StopRule AssessmentStopRule +} + +// AssessmentStopRule ends an adaptive attempt. After MinScoredItems the +// attempt stops when P_G reaches UpperProbability or falls to +// LowerProbability, or when the standard error is at most MaxStandardError; +// it always stops after MaxScoredItems. SeedItems are unscored items for +// collecting statistics on new tasks and come on top of the scored ones. +type AssessmentStopRule struct { + MinScoredItems int32 + MaxScoredItems int32 + SeedItems int32 + UpperProbability BasisPoints + LowerProbability BasisPoints + MaxStandardError BasisPoints +} + +func (policy AssessmentPolicy) Validate() error { + const location = "AssessmentPolicy.Validate" + switch policy.Calibration { + case AssessmentCalibrationUncalibratedInitial, AssessmentCalibrationCalibrated: + default: + return invalidPolicy(location, "assessment.calibration must be uncalibrated_initial or calibrated") + } + if err := firstError( + checkRange(location, "assessment.same_grade_retry_after_days", policy.SameGradeRetryAfter, 1, maxSameGradeRetryInterval), + checkRange(location, "assessment.max_attempts_per_window", policy.MaxAttemptsPerWindow, 1, maxAssessmentAttemptsPerWindow), + checkRange(location, "assessment.attempt_window_days", policy.AttemptWindow, 1, maxAssessmentAttemptWindow), + checkRange(location, "assessment.promotion_min_interval_days", policy.PromotionMinInterval, 1, maxPromotionInterval), + checkProbability(location, "assessment.confirmation_threshold_bp", policy.ConfirmationThreshold), + checkProbability(location, "assessment.high_strength_threshold_bp", policy.HighStrengthThreshold), + ); err != nil { + return err + } + if policy.HighStrengthThreshold < policy.ConfirmationThreshold { + return invalidPolicy(location, "assessment.high_strength_threshold_bp must not be below the confirmation threshold") + } + return policy.StopRule.validate(location, policy.ConfirmationThreshold) +} + +func (rule AssessmentStopRule) validate(location string, confirmation BasisPoints) error { + if err := firstError( + checkRange(location, "assessment.stop_rule.min_scored_items", rule.MinScoredItems, 1, maxScoredItems), + checkRange(location, "assessment.stop_rule.max_scored_items", rule.MaxScoredItems, rule.MinScoredItems, maxScoredItems), + checkRange(location, "assessment.stop_rule.seed_items", rule.SeedItems, 0, maxSeedItems), + checkProbability(location, "assessment.stop_rule.upper_probability_bp", rule.UpperProbability), + checkProbability(location, "assessment.stop_rule.lower_probability_bp", rule.LowerProbability), + checkRange(location, "assessment.stop_rule.max_standard_error_bp", rule.MaxStandardError, minPositiveStandardErrorBasisPoints, basisPointsPerUnit), + ); err != nil { + return err + } + // An attempt must be able to stop above the confirmation threshold and + // below it; otherwise an early stop could never confirm or never reject. + if rule.LowerProbability >= confirmation || rule.UpperProbability < confirmation { + return invalidPolicy(location, "assessment.stop_rule probabilities must satisfy lower < confirmation threshold <= upper") + } + return nil +} + +// IdentityPolicy holds the account and session lifetimes of the identity +// contract. +type IdentityPolicy struct { + VerificationTokenLifetime Hours + // UnverifiedAccountLifetime counts from the latest registration. + UnverifiedAccountLifetime CalendarDays + SessionIdleTimeout Hours + SessionAbsoluteLifetime CalendarDays +} + +func (policy IdentityPolicy) Validate() error { + const location = "IdentityPolicy.Validate" + if err := firstError( + checkRange(location, "identity.verification_token_lifetime_hours", policy.VerificationTokenLifetime, 1, maxVerificationTokenLifetime), + checkRange(location, "identity.unverified_account_lifetime_days", policy.UnverifiedAccountLifetime, 1, maxUnverifiedAccountLifetime), + checkRange(location, "identity.session_idle_timeout_hours", policy.SessionIdleTimeout, 1, maxSessionIdleTimeout), + checkRange(location, "identity.session_absolute_lifetime_days", policy.SessionAbsoluteLifetime, 1, maxSessionAbsoluteLifetime), + ); err != nil { + return err + } + if policy.SessionIdleTimeout.Duration() > policy.SessionAbsoluteLifetime.Duration() { + return invalidPolicy(location, "identity.session_idle_timeout_hours must not exceed the absolute session lifetime") + } + return nil +} + +// SearchStatusPolicy governs the candidate "searching" status. +type SearchStatusPolicy struct { + // SearchingConfirmationInterval is how often a candidate confirms that + // the "searching" status is still current. + SearchingConfirmationInterval CalendarDays +} + +func (policy SearchStatusPolicy) Validate() error { + return checkRange("SearchStatusPolicy.Validate", "search_status.searching_confirmation_interval_days", + policy.SearchingConfirmationInterval, 1, maxSearchingConfirmationInterval) +} + +func checkRange[T ~int32](location, field string, value, minimum, maximum T) error { + if value < minimum || value > maximum { + return invalidPolicy(location, fmt.Sprintf("%s must be between %d and %d", field, minimum, maximum)) + } + return nil +} + +// checkProbability accepts a probability strictly between 0 and 1: a +// threshold of 0 or 1 would make a rule always or never apply. +func checkProbability(location, field string, value BasisPoints) error { + return checkRange(location, field, value, minExclusiveProbabilityBasisPoints, maxExclusiveProbabilityBasisPoints) +} + +func invalidPolicy(location, reason string) error { + return fmt.Errorf("%s - %s: %w", location, reason, ErrInvalidPolicy) +} + +func firstError(errs ...error) error { + for _, err := range errs { + if err != nil { + return err + } + } + return nil +} diff --git a/backend/internal/domain/policy_demo.go b/backend/internal/domain/policy_demo.go new file mode 100644 index 0000000..d89943a --- /dev/null +++ b/backend/internal/domain/policy_demo.go @@ -0,0 +1,62 @@ +package domain + +// DemoProductPolicyV1 returns the initial product policy that is published as +// version 1 of ProductPolicyKey with PolicyKindDemo. Its values are the agreed +// starting rules for verifying the product flow, not results of a study: the +// assessment section is marked AssessmentCalibrationUncalibratedInitial, and +// its thresholds and stop rule make no psychometric or quality claim until a +// pilot calibrates them and a calibrated version is published. +// +// The policy holds rules only. Assessment content, such as the task bank, +// blueprints, and variants, is separate work and is not part of it. +// +// Tests must not use this policy as a fixture for other values; they build +// their own policies under their own keys. +func DemoProductPolicyV1() ProductPolicy { + return ProductPolicy{ + Invitations: InvitationPolicy{ + ResponseDeadlineOptions: []CalendarDays{3, 7, 14}, + DefaultResponseDeadline: 7, + MaxPendingPerNeed: 20, + RepeatAfterDecline: 30, + InterviewProposalDeadline: 5, + NoDealPause: 30, + }, + OrganizationQuotas: OrganizationQuotaPolicy{ + InvitationWindow: 7, + CardViewWindow: 24, + TierE0: OrganizationTierQuota{Active: true, InvitationsPerWindow: 10, DistinctCardViewsPerWindow: 50}, + TierE1: OrganizationTierQuota{Active: true, InvitationsPerWindow: 40, DistinctCardViewsPerWindow: 150}, + // E2 stays inactive until the organization verification that + // grants it exists. + TierE2: OrganizationTierQuota{Active: false, InvitationsPerWindow: 100, DistinctCardViewsPerWindow: 400}, + }, + Assessment: AssessmentPolicy{ + Calibration: AssessmentCalibrationUncalibratedInitial, + SameGradeRetryAfter: 30, + MaxAttemptsPerWindow: 3, + AttemptWindow: 180, + PromotionMinInterval: 90, + ConfirmationThreshold: 8000, + HighStrengthThreshold: 9000, + PracticeRequired: true, + StopRule: AssessmentStopRule{ + MinScoredItems: 8, + MaxScoredItems: 23, + SeedItems: 2, + UpperProbability: 9000, + LowerProbability: 1000, + MaxStandardError: 2500, + }, + }, + Identity: IdentityPolicy{ + VerificationTokenLifetime: 24, + UnverifiedAccountLifetime: 7, + SessionIdleTimeout: 24, + SessionAbsoluteLifetime: 7, + }, + SearchStatus: SearchStatusPolicy{ + SearchingConfirmationInterval: 30, + }, + } +} diff --git a/backend/internal/domain/policy_document.go b/backend/internal/domain/policy_document.go new file mode 100644 index 0000000..05430eb --- /dev/null +++ b/backend/internal/domain/policy_document.go @@ -0,0 +1,275 @@ +package domain + +import ( + "bytes" + "crypto/sha256" + "encoding/json" + "errors" + "fmt" + "io" +) + +const ( + // productPolicySchemaVersion is the layout of the stored document. A new + // layout adds a decoder for its version; stored versions are never + // rewritten. + productPolicySchemaVersion = 1 + // maxPolicyDocumentBytes bounds a document before decoding. The current + // layout encodes to well under 2 KiB. + maxPolicyDocumentBytes = 64 << 10 +) + +// PolicyDocumentHash is the SHA-256 of the canonical policy document. +type PolicyDocumentHash [sha256.Size]byte + +// The document types mirror ProductPolicy field by field. Every field is a +// pointer, so the decoder can tell a missing field from a zero value: a +// missing field is an error, never a default. Field names carry their unit. +type productPolicyDocument struct { + SchemaVersion *int32 `json:"schema_version"` + Invitations *invitationPolicyDocument `json:"invitations"` + OrganizationQuotas *organizationQuotaDocument `json:"organization_quotas"` + Assessment *assessmentPolicyDocument `json:"assessment"` + Identity *identityPolicyDocument `json:"identity"` + SearchStatus *searchStatusDocument `json:"search_status"` +} + +type invitationPolicyDocument struct { + ResponseDeadlineOptionsDays *[]CalendarDays `json:"response_deadline_options_days"` + DefaultResponseDeadlineDays *CalendarDays `json:"default_response_deadline_days"` + MaxPendingPerNeed *int32 `json:"max_pending_per_need"` + RepeatAfterDeclineDays *CalendarDays `json:"repeat_after_decline_days"` + InterviewProposalDeadlineBusinessDays *BusinessDays `json:"interview_proposal_deadline_business_days"` + NoDealPauseDays *CalendarDays `json:"no_deal_pause_days"` +} + +type organizationQuotaDocument struct { + InvitationWindowDays *CalendarDays `json:"invitation_window_days"` + CardViewWindowHours *Hours `json:"card_view_window_hours"` + Tiers *organizationTiersDocument `json:"tiers"` +} + +type organizationTiersDocument struct { + E0 *organizationTierQuotaDocument `json:"e0"` + E1 *organizationTierQuotaDocument `json:"e1"` + E2 *organizationTierQuotaDocument `json:"e2"` +} + +type organizationTierQuotaDocument struct { + Active *bool `json:"active"` + InvitationsPerWindow *int32 `json:"invitations_per_window"` + DistinctCardViewsPerWindow *int32 `json:"distinct_card_views_per_window"` +} + +type assessmentPolicyDocument struct { + Calibration *AssessmentCalibration `json:"calibration"` + SameGradeRetryAfterDays *CalendarDays `json:"same_grade_retry_after_days"` + MaxAttemptsPerWindow *int32 `json:"max_attempts_per_window"` + AttemptWindowDays *CalendarDays `json:"attempt_window_days"` + PromotionMinIntervalDays *CalendarDays `json:"promotion_min_interval_days"` + ConfirmationThresholdBP *BasisPoints `json:"confirmation_threshold_bp"` + HighStrengthThresholdBP *BasisPoints `json:"high_strength_threshold_bp"` + PracticeRequired *bool `json:"practice_required"` + StopRule *assessmentStopDocument `json:"stop_rule"` +} + +type assessmentStopDocument struct { + MinScoredItems *int32 `json:"min_scored_items"` + MaxScoredItems *int32 `json:"max_scored_items"` + SeedItems *int32 `json:"seed_items"` + UpperProbabilityBP *BasisPoints `json:"upper_probability_bp"` + LowerProbabilityBP *BasisPoints `json:"lower_probability_bp"` + MaxStandardErrorBP *BasisPoints `json:"max_standard_error_bp"` +} + +type identityPolicyDocument struct { + VerificationTokenLifetimeHours *Hours `json:"verification_token_lifetime_hours"` + UnverifiedAccountLifetimeDays *CalendarDays `json:"unverified_account_lifetime_days"` + SessionIdleTimeoutHours *Hours `json:"session_idle_timeout_hours"` + SessionAbsoluteLifetimeDays *CalendarDays `json:"session_absolute_lifetime_days"` +} + +type searchStatusDocument struct { + SearchingConfirmationIntervalDays *CalendarDays `json:"searching_confirmation_interval_days"` +} + +// encodeProductPolicy returns the canonical document: compact JSON with the +// fields in declaration order. The same policy always encodes to the same +// bytes, which makes the document hash deterministic. +func encodeProductPolicy(policy ProductPolicy) ([]byte, PolicyDocumentHash, error) { + invitations := policy.Invitations + quotas := policy.OrganizationQuotas + assessment := policy.Assessment + identity := policy.Identity + document := productPolicyDocument{ + SchemaVersion: pointer(int32(productPolicySchemaVersion)), + Invitations: &invitationPolicyDocument{ + ResponseDeadlineOptionsDays: pointer(invitations.ResponseDeadlineOptions), + DefaultResponseDeadlineDays: pointer(invitations.DefaultResponseDeadline), + MaxPendingPerNeed: pointer(invitations.MaxPendingPerNeed), + RepeatAfterDeclineDays: pointer(invitations.RepeatAfterDecline), + InterviewProposalDeadlineBusinessDays: pointer(invitations.InterviewProposalDeadline), + NoDealPauseDays: pointer(invitations.NoDealPause), + }, + OrganizationQuotas: &organizationQuotaDocument{ + InvitationWindowDays: pointer(quotas.InvitationWindow), + CardViewWindowHours: pointer(quotas.CardViewWindow), + Tiers: &organizationTiersDocument{ + E0: encodeTierQuota(quotas.TierE0), + E1: encodeTierQuota(quotas.TierE1), + E2: encodeTierQuota(quotas.TierE2), + }, + }, + Assessment: &assessmentPolicyDocument{ + Calibration: pointer(assessment.Calibration), + SameGradeRetryAfterDays: pointer(assessment.SameGradeRetryAfter), + MaxAttemptsPerWindow: pointer(assessment.MaxAttemptsPerWindow), + AttemptWindowDays: pointer(assessment.AttemptWindow), + PromotionMinIntervalDays: pointer(assessment.PromotionMinInterval), + ConfirmationThresholdBP: pointer(assessment.ConfirmationThreshold), + HighStrengthThresholdBP: pointer(assessment.HighStrengthThreshold), + PracticeRequired: pointer(assessment.PracticeRequired), + StopRule: &assessmentStopDocument{ + MinScoredItems: pointer(assessment.StopRule.MinScoredItems), + MaxScoredItems: pointer(assessment.StopRule.MaxScoredItems), + SeedItems: pointer(assessment.StopRule.SeedItems), + UpperProbabilityBP: pointer(assessment.StopRule.UpperProbability), + LowerProbabilityBP: pointer(assessment.StopRule.LowerProbability), + MaxStandardErrorBP: pointer(assessment.StopRule.MaxStandardError), + }, + }, + Identity: &identityPolicyDocument{ + VerificationTokenLifetimeHours: pointer(identity.VerificationTokenLifetime), + UnverifiedAccountLifetimeDays: pointer(identity.UnverifiedAccountLifetime), + SessionIdleTimeoutHours: pointer(identity.SessionIdleTimeout), + SessionAbsoluteLifetimeDays: pointer(identity.SessionAbsoluteLifetime), + }, + SearchStatus: &searchStatusDocument{ + SearchingConfirmationIntervalDays: pointer(policy.SearchStatus.SearchingConfirmationInterval), + }, + } + encoded, err := json.Marshal(document) + if err != nil { + return nil, PolicyDocumentHash{}, fmt.Errorf("domain.encodeProductPolicy - marshal document: %w", err) + } + return encoded, sha256.Sum256(encoded), nil +} + +func encodeTierQuota(quota OrganizationTierQuota) *organizationTierQuotaDocument { + return &organizationTierQuotaDocument{ + Active: pointer(quota.Active), + InvitationsPerWindow: pointer(quota.InvitationsPerWindow), + DistinctCardViewsPerWindow: pointer(quota.DistinctCardViewsPerWindow), + } +} + +// decodeProductPolicy reads a document strictly: it rejects unknown fields, +// missing fields, null values, values of the wrong type or out of the int32 +// range, an unknown schema version, and trailing data. It checks structure +// only; ProductPolicy.Validate checks the values. encoding/json matches field +// names without regard to letter case and keeps the last of duplicate keys; +// the document hash, computed over the canonical re-encoding, is what pins +// the content. +func decodeProductPolicy(document []byte) (ProductPolicy, error) { + const location = "domain.decodeProductPolicy" + if len(document) > maxPolicyDocumentBytes { + return ProductPolicy{}, invalidPolicy(location, fmt.Sprintf("document must have at most %d bytes", maxPolicyDocumentBytes)) + } + decoder := json.NewDecoder(bytes.NewReader(document)) + decoder.DisallowUnknownFields() + var parsed productPolicyDocument + if err := decoder.Decode(&parsed); err != nil { + return ProductPolicy{}, fmt.Errorf("%s - decode document: %w: %w", location, ErrInvalidPolicy, err) + } + if _, err := decoder.Token(); !errors.Is(err, io.EOF) { + return ProductPolicy{}, invalidPolicy(location, "document must contain one JSON object") + } + reader := documentReader{} + if version := require(&reader, "schema_version", parsed.SchemaVersion); reader.missing == "" && version != productPolicySchemaVersion { + return ProductPolicy{}, invalidPolicy(location, fmt.Sprintf("schema_version must be %d", productPolicySchemaVersion)) + } + invitations := require(&reader, "invitations", parsed.Invitations) + quotas := require(&reader, "organization_quotas", parsed.OrganizationQuotas) + tiers := require(&reader, "organization_quotas.tiers", quotas.Tiers) + assessment := require(&reader, "assessment", parsed.Assessment) + stopRule := require(&reader, "assessment.stop_rule", assessment.StopRule) + identity := require(&reader, "identity", parsed.Identity) + searchStatus := require(&reader, "search_status", parsed.SearchStatus) + policy := ProductPolicy{ + Invitations: InvitationPolicy{ + ResponseDeadlineOptions: require(&reader, "invitations.response_deadline_options_days", invitations.ResponseDeadlineOptionsDays), + DefaultResponseDeadline: require(&reader, "invitations.default_response_deadline_days", invitations.DefaultResponseDeadlineDays), + MaxPendingPerNeed: require(&reader, "invitations.max_pending_per_need", invitations.MaxPendingPerNeed), + RepeatAfterDecline: require(&reader, "invitations.repeat_after_decline_days", invitations.RepeatAfterDeclineDays), + InterviewProposalDeadline: require(&reader, "invitations.interview_proposal_deadline_business_days", invitations.InterviewProposalDeadlineBusinessDays), + NoDealPause: require(&reader, "invitations.no_deal_pause_days", invitations.NoDealPauseDays), + }, + OrganizationQuotas: OrganizationQuotaPolicy{ + InvitationWindow: require(&reader, "organization_quotas.invitation_window_days", quotas.InvitationWindowDays), + CardViewWindow: require(&reader, "organization_quotas.card_view_window_hours", quotas.CardViewWindowHours), + TierE0: decodeTierQuota(&reader, "organization_quotas.tiers.e0", tiers.E0), + TierE1: decodeTierQuota(&reader, "organization_quotas.tiers.e1", tiers.E1), + TierE2: decodeTierQuota(&reader, "organization_quotas.tiers.e2", tiers.E2), + }, + Assessment: AssessmentPolicy{ + Calibration: require(&reader, "assessment.calibration", assessment.Calibration), + SameGradeRetryAfter: require(&reader, "assessment.same_grade_retry_after_days", assessment.SameGradeRetryAfterDays), + MaxAttemptsPerWindow: require(&reader, "assessment.max_attempts_per_window", assessment.MaxAttemptsPerWindow), + AttemptWindow: require(&reader, "assessment.attempt_window_days", assessment.AttemptWindowDays), + PromotionMinInterval: require(&reader, "assessment.promotion_min_interval_days", assessment.PromotionMinIntervalDays), + ConfirmationThreshold: require(&reader, "assessment.confirmation_threshold_bp", assessment.ConfirmationThresholdBP), + HighStrengthThreshold: require(&reader, "assessment.high_strength_threshold_bp", assessment.HighStrengthThresholdBP), + PracticeRequired: require(&reader, "assessment.practice_required", assessment.PracticeRequired), + StopRule: AssessmentStopRule{ + MinScoredItems: require(&reader, "assessment.stop_rule.min_scored_items", stopRule.MinScoredItems), + MaxScoredItems: require(&reader, "assessment.stop_rule.max_scored_items", stopRule.MaxScoredItems), + SeedItems: require(&reader, "assessment.stop_rule.seed_items", stopRule.SeedItems), + UpperProbability: require(&reader, "assessment.stop_rule.upper_probability_bp", stopRule.UpperProbabilityBP), + LowerProbability: require(&reader, "assessment.stop_rule.lower_probability_bp", stopRule.LowerProbabilityBP), + MaxStandardError: require(&reader, "assessment.stop_rule.max_standard_error_bp", stopRule.MaxStandardErrorBP), + }, + }, + Identity: IdentityPolicy{ + VerificationTokenLifetime: require(&reader, "identity.verification_token_lifetime_hours", identity.VerificationTokenLifetimeHours), + UnverifiedAccountLifetime: require(&reader, "identity.unverified_account_lifetime_days", identity.UnverifiedAccountLifetimeDays), + SessionIdleTimeout: require(&reader, "identity.session_idle_timeout_hours", identity.SessionIdleTimeoutHours), + SessionAbsoluteLifetime: require(&reader, "identity.session_absolute_lifetime_days", identity.SessionAbsoluteLifetimeDays), + }, + SearchStatus: SearchStatusPolicy{ + SearchingConfirmationInterval: require(&reader, "search_status.searching_confirmation_interval_days", searchStatus.SearchingConfirmationIntervalDays), + }, + } + if reader.missing != "" { + return ProductPolicy{}, invalidPolicy(location, reader.missing+" is required") + } + return policy, nil +} + +func decodeTierQuota(reader *documentReader, field string, document *organizationTierQuotaDocument) OrganizationTierQuota { + tier := require(reader, field, document) + return OrganizationTierQuota{ + Active: require(reader, field+".active", tier.Active), + InvitationsPerWindow: require(reader, field+".invitations_per_window", tier.InvitationsPerWindow), + DistinctCardViewsPerWindow: require(reader, field+".distinct_card_views_per_window", tier.DistinctCardViewsPerWindow), + } +} + +// documentReader remembers the first missing field while a document is read. +type documentReader struct { + missing string +} + +// require returns the value behind a document pointer, or the zero value +// after recording field as missing. +func require[T any](reader *documentReader, field string, value *T) T { + if value == nil { + if reader.missing == "" { + reader.missing = field + } + var zero T + return zero + } + return *value +} + +func pointer[T any](value T) *T { return &value } diff --git a/backend/internal/domain/policy_test.go b/backend/internal/domain/policy_test.go new file mode 100644 index 0000000..afc1d04 --- /dev/null +++ b/backend/internal/domain/policy_test.go @@ -0,0 +1,480 @@ +package domain + +import ( + "bytes" + "crypto/sha256" + "encoding/json" + "errors" + "strings" + "testing" + "time" +) + +// demoProductPolicyV1Document is the canonical document of the demo policy. +// Stored versions are verified by hashing the canonical re-encoding of their +// document, so any change to field order, names, or encoding would make +// every stored version fail its integrity check. A new layout needs a new +// schema version and decoder, not an edit here. +const demoProductPolicyV1Document = `{"schema_version":1,` + + `"invitations":{"response_deadline_options_days":[3,7,14],"default_response_deadline_days":7,` + + `"max_pending_per_need":20,"repeat_after_decline_days":30,"interview_proposal_deadline_business_days":5,` + + `"no_deal_pause_days":30},` + + `"organization_quotas":{"invitation_window_days":7,"card_view_window_hours":24,"tiers":{` + + `"e0":{"active":true,"invitations_per_window":10,"distinct_card_views_per_window":50},` + + `"e1":{"active":true,"invitations_per_window":40,"distinct_card_views_per_window":150},` + + `"e2":{"active":false,"invitations_per_window":100,"distinct_card_views_per_window":400}}},` + + `"assessment":{"calibration":"uncalibrated_initial","same_grade_retry_after_days":30,` + + `"max_attempts_per_window":3,"attempt_window_days":180,"promotion_min_interval_days":90,` + + `"confirmation_threshold_bp":8000,"high_strength_threshold_bp":9000,"practice_required":true,` + + `"stop_rule":{"min_scored_items":8,"max_scored_items":23,"seed_items":2,"upper_probability_bp":9000,` + + `"lower_probability_bp":1000,"max_standard_error_bp":2500}},` + + `"identity":{"verification_token_lifetime_hours":24,"unverified_account_lifetime_days":7,` + + `"session_idle_timeout_hours":24,"session_absolute_lifetime_days":7},` + + `"search_status":{"searching_confirmation_interval_days":30}}` + +var ( + testPolicyCreatedAt = time.Date(2026, time.October, 6, 9, 0, 0, 0, time.UTC) + testPolicyEffectiveAt = testPolicyCreatedAt.Add(time.Hour) +) + +// testPolicy returns a valid policy whose values differ from the demo policy, +// so a test never relies on demo values by accident. +func testPolicy() ProductPolicy { + return ProductPolicy{ + Invitations: InvitationPolicy{ + ResponseDeadlineOptions: []CalendarDays{2, 5}, + DefaultResponseDeadline: 5, + MaxPendingPerNeed: 4, + RepeatAfterDecline: 11, + InterviewProposalDeadline: 3, + NoDealPause: 12, + }, + OrganizationQuotas: OrganizationQuotaPolicy{ + InvitationWindow: 3, + CardViewWindow: 12, + TierE0: OrganizationTierQuota{Active: true, InvitationsPerWindow: 2, DistinctCardViewsPerWindow: 5}, + TierE1: OrganizationTierQuota{Active: true, InvitationsPerWindow: 3, DistinctCardViewsPerWindow: 6}, + TierE2: OrganizationTierQuota{Active: true, InvitationsPerWindow: 3, DistinctCardViewsPerWindow: 7}, + }, + Assessment: AssessmentPolicy{ + Calibration: AssessmentCalibrationCalibrated, + SameGradeRetryAfter: 10, + MaxAttemptsPerWindow: 2, + AttemptWindow: 60, + PromotionMinInterval: 45, + ConfirmationThreshold: 7500, + HighStrengthThreshold: 8800, + PracticeRequired: false, + StopRule: AssessmentStopRule{ + MinScoredItems: 5, + MaxScoredItems: 15, + SeedItems: 0, + UpperProbability: 9500, + LowerProbability: 500, + MaxStandardError: 3000, + }, + }, + Identity: IdentityPolicy{ + VerificationTokenLifetime: 12, + UnverifiedAccountLifetime: 3, + SessionIdleTimeout: 6, + SessionAbsoluteLifetime: 2, + }, + SearchStatus: SearchStatusPolicy{SearchingConfirmationInterval: 14}, + } +} + +func testDraftInput() NewPolicyVersionDraftInput { + return NewPolicyVersionDraftInput{ + Key: ProductPolicyKey, + Kind: PolicyKindCalibrated, + Author: "operator:policy-tester", + EffectiveAt: testPolicyEffectiveAt, + Policy: testPolicy(), + } +} + +func mustDraft(t *testing.T, input NewPolicyVersionDraftInput, number int32) PolicyVersionDraft { + t.Helper() + draft, err := NewPolicyVersionDraft(input) + if err != nil { + t.Fatalf("NewPolicyVersionDraft() error = %v", err) + } + numbered, err := draft.WithVersion(number) + if err != nil { + t.Fatalf("WithVersion(%d) error = %v", number, err) + } + return numbered +} + +// storedFrom returns the row storage would hold for the draft. +func storedFrom(draft PolicyVersionDraft) StoredPolicyVersion { + hash := draft.DocumentHash() + effectiveAt, scheduled := draft.EffectiveAt() + if !scheduled { + effectiveAt = testPolicyCreatedAt + } + return StoredPolicyVersion{ + ID: draft.ID(), + Key: string(draft.Key()), + Version: draft.Version(), + Kind: string(draft.Kind()), + Author: string(draft.Author()), + EffectiveAt: effectiveAt, + CreatedAt: testPolicyCreatedAt, + Document: draft.Document(), + DocumentHash: hash[:], + } +} + +func mustRestore(t *testing.T, stored StoredPolicyVersion) PolicyVersion { + t.Helper() + version, err := RestorePolicyVersion(stored) + if err != nil { + t.Fatalf("RestorePolicyVersion() error = %v", err) + } + return version +} + +func TestDemoProductPolicyV1IsValidDemoAndUncalibrated(t *testing.T) { + demo := DemoProductPolicyV1() + if err := demo.Validate(); err != nil { + t.Fatalf("DemoProductPolicyV1().Validate() error = %v", err) + } + if demo.Assessment.Calibration != AssessmentCalibrationUncalibratedInitial { + t.Fatalf("demo assessment calibration = %q, want uncalibrated_initial", demo.Assessment.Calibration) + } + if demo.OrganizationQuotas.TierE2.Active { + t.Fatal("demo tier E2 is active before organization verification exists") + } + draft := mustDraft(t, NewPolicyVersionDraftInput{ + Key: ProductPolicyKey, Kind: PolicyKindDemo, Author: DemoPolicySeedAuthor, Policy: demo, + }, 1) + if got := string(draft.Document()); got != demoProductPolicyV1Document { + t.Fatalf("demo canonical document =\n%s\nwant\n%s", got, demoProductPolicyV1Document) + } + if draft.DocumentHash() != sha256.Sum256([]byte(demoProductPolicyV1Document)) { + t.Fatal("demo document hash is not the SHA-256 of the canonical document") + } + if _, scheduled := draft.EffectiveAt(); scheduled { + t.Fatal("a draft without an effective time reports a schedule") + } + calibrated := NewPolicyVersionDraftInput{Key: ProductPolicyKey, Kind: PolicyKindCalibrated, Author: DemoPolicySeedAuthor, Policy: demo} + if _, err := NewPolicyVersionDraft(calibrated); !errors.Is(err, ErrInvalidPolicyVersion) { + t.Fatalf("NewPolicyVersionDraft(demo values as calibrated) error = %v, want ErrInvalidPolicyVersion", err) + } +} + +func TestProductPolicyValidateRejectsEachSection(t *testing.T) { + tests := map[string]func(*ProductPolicy){ + "zero policy": func(policy *ProductPolicy) { *policy = ProductPolicy{} }, + "no deadline options": func(policy *ProductPolicy) { policy.Invitations.ResponseDeadlineOptions = nil }, + "too many deadline options": func(policy *ProductPolicy) { + policy.Invitations.ResponseDeadlineOptions = []CalendarDays{1, 2, 3, 4, 5, 6} + }, + "deadline option out of range": func(policy *ProductPolicy) { policy.Invitations.ResponseDeadlineOptions = []CalendarDays{2, 31} }, + "deadline options not increasing": func(policy *ProductPolicy) { policy.Invitations.ResponseDeadlineOptions = []CalendarDays{5, 5} }, + "default deadline not an option": func(policy *ProductPolicy) { policy.Invitations.DefaultResponseDeadline = 3 }, + "zero pending limit": func(policy *ProductPolicy) { policy.Invitations.MaxPendingPerNeed = 0 }, + "negative repeat after decline": func(policy *ProductPolicy) { policy.Invitations.RepeatAfterDecline = -1 }, + "zero interview deadline": func(policy *ProductPolicy) { policy.Invitations.InterviewProposalDeadline = 0 }, + "no-deal pause over a year": func(policy *ProductPolicy) { policy.Invitations.NoDealPause = 366 }, + "zero invitation window": func(policy *ProductPolicy) { policy.OrganizationQuotas.InvitationWindow = 0 }, + "card view window over a week": func(policy *ProductPolicy) { policy.OrganizationQuotas.CardViewWindow = 169 }, + "zero tier limit": func(policy *ProductPolicy) { policy.OrganizationQuotas.TierE0.InvitationsPerWindow = 0 }, + "inactive E0": func(policy *ProductPolicy) { policy.OrganizationQuotas.TierE0.Active = false }, + "active E2 above inactive E1": func(policy *ProductPolicy) { policy.OrganizationQuotas.TierE1.Active = false }, + "higher tier below lower tier": func(policy *ProductPolicy) { + policy.OrganizationQuotas.TierE2.DistinctCardViewsPerWindow = policy.OrganizationQuotas.TierE1.DistinctCardViewsPerWindow - 1 + }, + "unknown calibration": func(policy *ProductPolicy) { policy.Assessment.Calibration = "pilot" }, + "zero retry interval": func(policy *ProductPolicy) { policy.Assessment.SameGradeRetryAfter = 0 }, + "zero attempts per window": func(policy *ProductPolicy) { policy.Assessment.MaxAttemptsPerWindow = 0 }, + "zero attempt window": func(policy *ProductPolicy) { policy.Assessment.AttemptWindow = 0 }, + "zero promotion interval": func(policy *ProductPolicy) { policy.Assessment.PromotionMinInterval = 0 }, + "confirmation threshold of one": func(policy *ProductPolicy) { policy.Assessment.ConfirmationThreshold = 10000 }, + "confirmation threshold of zero": func(policy *ProductPolicy) { policy.Assessment.ConfirmationThreshold = 0 }, + "high strength below confirmation": func(policy *ProductPolicy) { policy.Assessment.HighStrengthThreshold = 7000 }, + "zero minimum scored items": func(policy *ProductPolicy) { policy.Assessment.StopRule.MinScoredItems = 0 }, + "maximum below minimum scored items": func(policy *ProductPolicy) { policy.Assessment.StopRule.MaxScoredItems = 4 }, + "negative seed items": func(policy *ProductPolicy) { policy.Assessment.StopRule.SeedItems = -1 }, + "lower stop at confirmation": func(policy *ProductPolicy) { policy.Assessment.StopRule.LowerProbability = 7500 }, + "upper stop below confirmation": func(policy *ProductPolicy) { policy.Assessment.StopRule.UpperProbability = 7000 }, + "zero standard error": func(policy *ProductPolicy) { policy.Assessment.StopRule.MaxStandardError = 0 }, + "standard error above one": func(policy *ProductPolicy) { policy.Assessment.StopRule.MaxStandardError = 10001 }, + "zero token lifetime": func(policy *ProductPolicy) { policy.Identity.VerificationTokenLifetime = 0 }, + "zero unverified account lifetime": func(policy *ProductPolicy) { policy.Identity.UnverifiedAccountLifetime = 0 }, + "zero idle timeout": func(policy *ProductPolicy) { policy.Identity.SessionIdleTimeout = 0 }, + "absolute lifetime over limit": func(policy *ProductPolicy) { policy.Identity.SessionAbsoluteLifetime = 91 }, + "idle timeout above absolute": func(policy *ProductPolicy) { policy.Identity.SessionIdleTimeout = 49 }, + "zero searching confirmation": func(policy *ProductPolicy) { policy.SearchStatus.SearchingConfirmationInterval = 0 }, + "searching confirmation over a year": func(policy *ProductPolicy) { policy.SearchStatus.SearchingConfirmationInterval = 366 }, + "negative searching confirmation": func(policy *ProductPolicy) { policy.SearchStatus.SearchingConfirmationInterval = -30 }, + "tier invitations above sanity bound": func(policy *ProductPolicy) { + policy.OrganizationQuotas.TierE2.InvitationsPerWindow = maxTierQuotaLimit + 1 + }, + } + if err := testPolicy().Validate(); err != nil { + t.Fatalf("testPolicy().Validate() error = %v", err) + } + for name, mutate := range tests { + t.Run(name, func(t *testing.T) { + policy := testPolicy() + mutate(&policy) + if err := policy.Validate(); !errors.Is(err, ErrInvalidPolicy) { + t.Fatalf("Validate() error = %v, want ErrInvalidPolicy", err) + } + input := testDraftInput() + input.Policy = policy + if _, err := NewPolicyVersionDraft(input); !errors.Is(err, ErrInvalidPolicy) { + t.Fatalf("NewPolicyVersionDraft() error = %v, want ErrInvalidPolicy", err) + } + }) + } +} + +func TestNewPolicyVersionDraftRejectsInvalidMetadata(t *testing.T) { + tests := map[string]func(*NewPolicyVersionDraftInput){ + "empty family": func(input *NewPolicyVersionDraftInput) { input.Key = "" }, + "unknown family": func(input *NewPolicyVersionDraftInput) { input.Key = "test_policy" }, + "unknown kind": func(input *NewPolicyVersionDraftInput) { input.Kind = "draft" }, + "author without prefix": func(input *NewPolicyVersionDraftInput) { input.Author = "policy-tester" }, + "author with an email": func(input *NewPolicyVersionDraftInput) { input.Author = "operator:tester@example.com" }, + "author over 128 bytes": func(input *NewPolicyVersionDraftInput) { + input.Author = PolicyAuthor("operator:" + strings.Repeat("a", 120)) + }, + "calibrated without calibration": func(input *NewPolicyVersionDraftInput) { + input.Policy.Assessment.Calibration = AssessmentCalibrationUncalibratedInitial + }, + } + for name, mutate := range tests { + t.Run(name, func(t *testing.T) { + input := testDraftInput() + mutate(&input) + if _, err := NewPolicyVersionDraft(input); !errors.Is(err, ErrInvalidPolicyVersion) { + t.Fatalf("NewPolicyVersionDraft() error = %v, want ErrInvalidPolicyVersion", err) + } + }) + } + draft, err := NewPolicyVersionDraft(testDraftInput()) + if err != nil { + t.Fatalf("NewPolicyVersionDraft() error = %v", err) + } + if draft.Version() != 0 { + t.Fatalf("new draft version = %d, want unnumbered", draft.Version()) + } + if _, err := draft.WithVersion(0); !errors.Is(err, ErrInvalidPolicyVersion) { + t.Fatalf("WithVersion(0) error = %v, want ErrInvalidPolicyVersion", err) + } + if _, err := (PolicyVersionDraft{}).WithVersion(1); !errors.Is(err, ErrInvalidPolicyVersion) { + t.Fatalf("zero draft WithVersion(1) error = %v, want ErrInvalidPolicyVersion", err) + } +} + +func TestPolicyVersionRoundTripAndHashDeterminism(t *testing.T) { + input := testDraftInput() + first := mustDraft(t, input, 3) + second := mustDraft(t, input, 3) + if first.ID() == second.ID() || first.ID().UUID().Version() != 7 { + t.Fatalf("IDs = %s and %s, want distinct UUIDv7 values", first.ID(), second.ID()) + } + if string(first.Document()) != string(second.Document()) || first.DocumentHash() != second.DocumentHash() { + t.Fatal("the same policy encoded to different documents or hashes") + } + if first.DocumentHash() != sha256.Sum256(first.Document()) { + t.Fatal("document hash is not the SHA-256 of the canonical document") + } + changed := input + changed.Policy = testPolicy() + changed.Policy.Invitations.MaxPendingPerNeed++ + if mustDraft(t, changed, 3).DocumentHash() == first.DocumentHash() { + t.Fatal("a different policy produced the same hash") + } + + restored := mustRestore(t, storedFrom(first)) + assertRestoredFromDraft(t, restored, first) + + // jsonb returns the document with other key order and whitespace; the + // hash is checked against the canonical re-encoding, not the bytes. + var generic map[string]any + if err := json.Unmarshal(first.Document(), &generic); err != nil { + t.Fatalf("unmarshal document: %v", err) + } + reordered, err := json.MarshalIndent(generic, "", " ") + if err != nil { + t.Fatalf("marshal reordered document: %v", err) + } + stored := storedFrom(first) + stored.Document = reordered + assertRestoredFromDraft(t, mustRestore(t, stored), first) +} + +func TestPolicyVersionAccessorsReturnCopies(t *testing.T) { + draft := mustDraft(t, testDraftInput(), 1) + version := mustRestore(t, storedFrom(draft)) + for _, values := range []struct { + policy ProductPolicy + document []byte + }{ + {policy: draft.Policy(), document: draft.Document()}, + {policy: version.Policy(), document: version.Document()}, + } { + values.policy.Invitations.ResponseDeadlineOptions[0] = 99 + values.document[0] = '[' + } + if draft.Policy().Invitations.ResponseDeadlineOptions[0] == 99 || draft.Document()[0] != '{' || + version.Policy().Invitations.ResponseDeadlineOptions[0] == 99 || version.Document()[0] != '{' { + t.Fatal("changing a returned value changed the draft or the stored version") + } +} + +func TestOrganizationTierLookup(t *testing.T) { + quotas := DemoProductPolicyV1().OrganizationQuotas + for value, want := range map[string]OrganizationTierQuota{"e0": quotas.TierE0, "e1": quotas.TierE1, "e2": quotas.TierE2} { + tier, err := ParseOrganizationTier(value) + if err != nil { + t.Fatalf("ParseOrganizationTier(%q) error = %v", value, err) + } + if got, err := quotas.Tier(tier); err != nil || got != want { + t.Fatalf("Tier(%s) = %+v, %v; want %+v", tier, got, err, want) + } + } + if _, err := ParseOrganizationTier("E0"); !errors.Is(err, ErrInvalidPolicy) { + t.Fatalf("ParseOrganizationTier(E0) error = %v, want ErrInvalidPolicy", err) + } + if _, err := quotas.Tier("e3"); !errors.Is(err, ErrInvalidPolicy) { + t.Fatalf("Tier(e3) error = %v, want ErrInvalidPolicy", err) + } +} + +func TestRestorePolicyVersionRejectsInvalidDocuments(t *testing.T) { + version := mustDraft(t, testDraftInput(), 1) + editDocument := func(edit func(map[string]any)) []byte { + var generic map[string]any + if err := json.Unmarshal(version.Document(), &generic); err != nil { + t.Fatalf("unmarshal document: %v", err) + } + edit(generic) + encoded, err := json.Marshal(generic) + if err != nil { + t.Fatalf("marshal document: %v", err) + } + return encoded + } + section := func(document map[string]any, name string) map[string]any { + value, ok := document[name].(map[string]any) + if !ok { + t.Fatalf("document has no %s object", name) + } + return value + } + tests := []struct { + name string + document []byte + want error + }{ + {name: "unknown top-level field", want: ErrInvalidPolicy, document: editDocument(func(document map[string]any) { document["notes"] = "x" })}, + {name: "unknown nested field", want: ErrInvalidPolicy, document: editDocument(func(document map[string]any) { + section(document, "identity")["password_reset_hours"] = 1 + })}, + {name: "missing section", want: ErrInvalidPolicy, document: editDocument(func(document map[string]any) { delete(document, "search_status") })}, + {name: "missing nested field", want: ErrInvalidPolicy, document: editDocument(func(document map[string]any) { + delete(section(document, "assessment"), "practice_required") + })}, + {name: "null field", want: ErrInvalidPolicy, document: editDocument(func(document map[string]any) { + section(document, "invitations")["max_pending_per_need"] = nil + })}, + {name: "fractional number", want: ErrInvalidPolicy, document: editDocument(func(document map[string]any) { + section(document, "invitations")["max_pending_per_need"] = 4.5 + })}, + {name: "number as string", want: ErrInvalidPolicy, document: editDocument(func(document map[string]any) { + section(document, "invitations")["max_pending_per_need"] = "4" + })}, + {name: "number above int32", want: ErrInvalidPolicy, document: editDocument(func(document map[string]any) { + section(document, "invitations")["max_pending_per_need"] = 1 << 40 + })}, + {name: "unknown schema version", want: ErrInvalidPolicy, document: editDocument(func(document map[string]any) { document["schema_version"] = 2 })}, + {name: "missing schema version", want: ErrInvalidPolicy, document: editDocument(func(document map[string]any) { delete(document, "schema_version") })}, + {name: "out-of-range value", want: ErrInvalidPolicy, document: editDocument(func(document map[string]any) { + section(document, "search_status")["searching_confirmation_interval_days"] = 0 + })}, + {name: "trailing data", want: ErrInvalidPolicy, document: append(version.Document(), []byte(` {}`)...)}, + {name: "array instead of object", want: ErrInvalidPolicy, document: []byte(`[]`)}, + {name: "oversized document", want: ErrInvalidPolicy, document: padDocument(version.Document(), maxPolicyDocumentBytes+1)}, + {name: "valid change without a new hash", want: ErrPolicyDocumentIntegrity, document: editDocument(func(document map[string]any) { + section(document, "invitations")["max_pending_per_need"] = 5 + })}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + stored := storedFrom(version) + stored.Document = test.document + if _, err := RestorePolicyVersion(stored); !errors.Is(err, test.want) { + t.Fatalf("RestorePolicyVersion() error = %v, want %v", err, test.want) + } + }) + } + + t.Run("whitespace up to the size limit is accepted", func(t *testing.T) { + // The oversized case above fails on size alone: the same padding + // that ends at the limit restores. + stored := storedFrom(version) + stored.Document = padDocument(version.Document(), maxPolicyDocumentBytes) + assertRestoredFromDraft(t, mustRestore(t, stored), version) + }) + t.Run("hash of the wrong size", func(t *testing.T) { + stored := storedFrom(version) + stored.DocumentHash = stored.DocumentHash[:16] + if _, err := RestorePolicyVersion(stored); !errors.Is(err, ErrPolicyDocumentIntegrity) { + t.Fatalf("RestorePolicyVersion() error = %v, want ErrPolicyDocumentIntegrity", err) + } + }) + t.Run("invalid metadata", func(t *testing.T) { + for name, mutate := range map[string]func(*StoredPolicyVersion){ + "nil ID": func(stored *StoredPolicyVersion) { stored.ID = PolicyVersionID{} }, + "unknown kind": func(stored *StoredPolicyVersion) { stored.Kind = "draft" }, + "invalid author": func(stored *StoredPolicyVersion) { stored.Author = "someone" }, + "unknown family": func(stored *StoredPolicyVersion) { stored.Key = "other" }, + "zero version": func(stored *StoredPolicyVersion) { stored.Version = 0 }, + "zero creation": func(stored *StoredPolicyVersion) { stored.CreatedAt = time.Time{} }, + "backdated": func(stored *StoredPolicyVersion) { stored.EffectiveAt = stored.CreatedAt.Add(-time.Second) }, + } { + stored := storedFrom(version) + mutate(&stored) + if _, err := RestorePolicyVersion(stored); !errors.Is(err, ErrInvalidPolicyVersion) { + t.Fatalf("%s: RestorePolicyVersion() error = %v, want ErrInvalidPolicyVersion", name, err) + } + } + }) +} + +func TestPolicyUnits(t *testing.T) { + if got := CalendarDays(7).Duration(); got != 7*24*time.Hour { + t.Fatalf("CalendarDays(7).Duration() = %s", got) + } + if got := Hours(24).Duration(); got != 24*time.Hour { + t.Fatalf("Hours(24).Duration() = %s", got) + } + for points, want := range map[BasisPoints]string{8000: "0.8000", 2500: "0.2500", 1: "0.0001", 10000: "1.0000"} { + if got := points.String(); got != want { + t.Fatalf("BasisPoints(%d).String() = %q, want %q", int32(points), got, want) + } + } +} + +// padDocument appends JSON whitespace until the document has size bytes, so +// it stays a valid document of the same content. +func padDocument(document []byte, size int) []byte { + padded := append([]byte(nil), document...) + return append(padded, bytes.Repeat([]byte(" "), size-len(document))...) +} + +func assertRestoredFromDraft(t *testing.T, got PolicyVersion, draft PolicyVersionDraft) { + t.Helper() + want := storedFrom(draft) + if got.ID() != draft.ID() || got.Key() != draft.Key() || got.Version() != draft.Version() || got.Kind() != draft.Kind() || + got.Author() != draft.Author() || !got.EffectiveAt().Equal(want.EffectiveAt) || !got.CreatedAt().Equal(want.CreatedAt) || + got.DocumentHash() != draft.DocumentHash() || string(got.Document()) != string(draft.Document()) { + t.Fatalf("restored version = %+v, want the draft %+v", got, draft) + } +} diff --git a/backend/internal/domain/policy_version.go b/backend/internal/domain/policy_version.go new file mode 100644 index 0000000..b17353b --- /dev/null +++ b/backend/internal/domain/policy_version.go @@ -0,0 +1,352 @@ +package domain + +import ( + "crypto/subtle" + "errors" + "fmt" + "regexp" + "time" + + "github.com/google/uuid" +) + +const maxPolicyAuthorLength = 128 + +var ( + // ErrInvalidPolicyVersion reports version metadata that is missing or + // malformed: the family, number, kind, author, or times. + ErrInvalidPolicyVersion = errors.New("invalid policy version") + + // ErrPolicyDocumentIntegrity reports a stored document whose canonical + // form no longer matches the stored SHA-256. The row was changed outside + // the application. + ErrPolicyDocumentIntegrity = errors.New("policy document does not match its hash") + + // "system:" or "operator:", as in the + // policy_versions_author_format CHECK. The character set excludes "@", so + // an email address cannot be stored as an author. + policyAuthorPattern = regexp.MustCompile(`^(system|operator):[a-z0-9][a-z0-9._-]*$`) +) + +// PolicyVersionID identifies one stored policy version. Records built under +// a policy, such as grade decisions, selection snapshots, and invitations, +// store it in a policy_version_id column that references policy_versions.id. +type PolicyVersionID uuid.UUID + +// NewPolicyVersionID returns a time-ordered UUIDv7. +func NewPolicyVersionID() (PolicyVersionID, error) { + id, err := uuid.NewV7() + if err != nil { + return PolicyVersionID{}, fmt.Errorf("domain.NewPolicyVersionID - generate ID: %w", err) + } + return PolicyVersionID(id), nil +} + +func (id PolicyVersionID) UUID() uuid.UUID { return uuid.UUID(id) } + +func (id PolicyVersionID) String() string { return uuid.UUID(id).String() } + +func (id PolicyVersionID) IsZero() bool { return uuid.UUID(id) == uuid.Nil } + +// PolicyKey names a policy family. Each family has exactly one document +// layout and decoder; ProductPolicyKey, decoded as ProductPolicy, is the only +// family. A new family adds its type and decoder here and to the +// policy_versions_policy_key_known CHECK. +type PolicyKey string + +// ProductPolicyKey is the family of the product policy that product rules +// read. +const ProductPolicyKey PolicyKey = "product" + +// ParsePolicyKey accepts a known family. +func ParsePolicyKey(value string) (PolicyKey, error) { + if PolicyKey(value) != ProductPolicyKey { + return "", invalidPolicyVersion("domain.ParsePolicyKey", "unknown policy family") + } + return ProductPolicyKey, nil +} + +// PolicyKind is the calibration state of a whole version. +type PolicyKind string + +const ( + // PolicyKindDemo marks an initial policy for verification of the product + // flow. Its values make no calibrated quality claim. + PolicyKindDemo PolicyKind = "demo" + // PolicyKindCalibrated marks a policy whose assessment section is backed + // by a calibration. A calibrated version cannot carry an uncalibrated + // assessment section. + PolicyKindCalibrated PolicyKind = "calibrated" +) + +func ParsePolicyKind(value string) (PolicyKind, error) { + kind := PolicyKind(value) + switch kind { + case PolicyKindDemo, PolicyKindCalibrated: + return kind, nil + default: + return "", invalidPolicyVersion("domain.ParsePolicyKind", "kind must be demo or calibrated") + } +} + +// PolicyAuthor identifies who published a version: "system:" for an +// automated publisher or "operator:" for a person. It is an operator +// identity, never contact data. It is not a reference to users, because a +// version must outlive the account and the seed has no account. +type PolicyAuthor string + +// DemoPolicySeedAuthor publishes the demo product policy. +const DemoPolicySeedAuthor PolicyAuthor = "system:demo-seed" + +func ParsePolicyAuthor(value string) (PolicyAuthor, error) { + if len(value) > maxPolicyAuthorLength || !policyAuthorPattern.MatchString(value) { + return "", invalidPolicyVersion("domain.ParsePolicyAuthor", + "author must be system: or operator: of at most 128 bytes in lowercase letters, digits, '.', '_', or '-'") + } + return PolicyAuthor(value), nil +} + +// PolicyVersionDraft is a version that is not stored yet. It has an ID, a +// validated policy, and its canonical document, but no publication time: +// the database sets that when it stores the draft. Its number is assigned +// with WithVersion before it is stored. +type PolicyVersionDraft struct { + id PolicyVersionID + key PolicyKey + version int32 + kind PolicyKind + author PolicyAuthor + effectiveAt time.Time + policy ProductPolicy + document []byte + documentHash PolicyDocumentHash +} + +// NewPolicyVersionDraftInput describes a version to publish. A zero +// EffectiveAt makes the version effective at publication; a set one schedules +// it and must not be earlier than the publication time, which storage +// enforces. +type NewPolicyVersionDraftInput struct { + Key PolicyKey + Kind PolicyKind + Author PolicyAuthor + EffectiveAt time.Time + Policy ProductPolicy +} + +// NewPolicyVersionDraft validates input, encodes the canonical document with +// its hash, and assigns a UUIDv7. The draft has no number yet. +func NewPolicyVersionDraft(input NewPolicyVersionDraftInput) (PolicyVersionDraft, error) { + const location = "domain.NewPolicyVersionDraft" + if err := validateVersionIdentity(location, input.Key, input.Kind, input.Author); err != nil { + return PolicyVersionDraft{}, err + } + if err := input.Policy.Validate(); err != nil { + return PolicyVersionDraft{}, fmt.Errorf("%s - validate policy: %w", location, err) + } + if err := checkKindMatchesCalibration(location, input.Kind, input.Policy); err != nil { + return PolicyVersionDraft{}, err + } + document, hash, err := encodeProductPolicy(input.Policy) + if err != nil { + return PolicyVersionDraft{}, err + } + id, err := NewPolicyVersionID() + if err != nil { + return PolicyVersionDraft{}, fmt.Errorf("%s - assign ID: %w", location, err) + } + return PolicyVersionDraft{ + id: id, + key: input.Key, + kind: input.Kind, + author: input.Author, + effectiveAt: input.EffectiveAt, + policy: input.Policy.clone(), + document: document, + documentHash: hash, + }, nil +} + +// WithVersion returns a copy of the draft with its number in the family. +func (draft PolicyVersionDraft) WithVersion(number int32) (PolicyVersionDraft, error) { + if draft.IsZero() { + return PolicyVersionDraft{}, invalidPolicyVersion("PolicyVersionDraft.WithVersion", "draft was not built by NewPolicyVersionDraft") + } + if number <= 0 { + return PolicyVersionDraft{}, invalidPolicyVersion("PolicyVersionDraft.WithVersion", "version must be positive") + } + numbered := draft + numbered.version = number + return numbered, nil +} + +func (draft PolicyVersionDraft) ID() PolicyVersionID { return draft.id } + +func (draft PolicyVersionDraft) Key() PolicyKey { return draft.key } + +// Version is zero until WithVersion assigns the number. +func (draft PolicyVersionDraft) Version() int32 { return draft.version } + +func (draft PolicyVersionDraft) Kind() PolicyKind { return draft.kind } + +func (draft PolicyVersionDraft) Author() PolicyAuthor { return draft.author } + +// EffectiveAt returns the scheduled effective time, or false when the +// version becomes effective at publication. +func (draft PolicyVersionDraft) EffectiveAt() (time.Time, bool) { + return draft.effectiveAt, !draft.effectiveAt.IsZero() +} + +// Policy returns a copy of the typed policy. +func (draft PolicyVersionDraft) Policy() ProductPolicy { return draft.policy.clone() } + +// Document returns a copy of the canonical document. +func (draft PolicyVersionDraft) Document() []byte { return append([]byte(nil), draft.document...) } + +func (draft PolicyVersionDraft) DocumentHash() PolicyDocumentHash { return draft.documentHash } + +// IsZero reports a draft not built by NewPolicyVersionDraft. +func (draft PolicyVersionDraft) IsZero() bool { return draft.id.IsZero() } + +// PolicyVersion is one stored, immutable version of a policy family. Only +// RestorePolicyVersion builds it; accessors return copies. +type PolicyVersion struct { + id PolicyVersionID + key PolicyKey + version int32 + kind PolicyKind + author PolicyAuthor + effectiveAt time.Time + createdAt time.Time + policy ProductPolicy + document []byte + documentHash PolicyDocumentHash +} + +// StoredPolicyVersion is a policy_versions row as storage reads it. +type StoredPolicyVersion struct { + ID PolicyVersionID + Key string + Version int32 + Kind string + Author string + EffectiveAt time.Time + CreatedAt time.Time + Document []byte + DocumentHash []byte +} + +// RestorePolicyVersion rebuilds a stored version. It decodes the document +// strictly, validates it like NewPolicyVersionDraft, and requires the SHA-256 +// of its canonical re-encoding to equal the stored hash; otherwise it returns +// ErrPolicyDocumentIntegrity. jsonb normalizes the stored text, so the hash +// is never compared with the stored bytes directly. +func RestorePolicyVersion(stored StoredPolicyVersion) (PolicyVersion, error) { + const location = "domain.RestorePolicyVersion" + if stored.ID.IsZero() { + return PolicyVersion{}, invalidPolicyVersion(location, "ID must not be nil") + } + key, err := ParsePolicyKey(stored.Key) + if err != nil { + return PolicyVersion{}, fmt.Errorf("%s - parse key: %w", location, err) + } + kind, err := ParsePolicyKind(stored.Kind) + if err != nil { + return PolicyVersion{}, fmt.Errorf("%s - parse kind: %w", location, err) + } + author, err := ParsePolicyAuthor(stored.Author) + if err != nil { + return PolicyVersion{}, fmt.Errorf("%s - parse author: %w", location, err) + } + switch { + case stored.Version <= 0: + return PolicyVersion{}, invalidPolicyVersion(location, "version must be positive") + case stored.CreatedAt.IsZero() || stored.EffectiveAt.IsZero(): + return PolicyVersion{}, invalidPolicyVersion(location, "creation and effective times must be set") + case stored.EffectiveAt.Before(stored.CreatedAt): + return PolicyVersion{}, invalidPolicyVersion(location, "effective time must not be earlier than the creation time") + } + policy, err := decodeProductPolicy(stored.Document) + if err != nil { + return PolicyVersion{}, fmt.Errorf("%s - decode document: %w", location, err) + } + if err := policy.Validate(); err != nil { + return PolicyVersion{}, fmt.Errorf("%s - validate policy: %w", location, err) + } + if err := checkKindMatchesCalibration(location, kind, policy); err != nil { + return PolicyVersion{}, err + } + document, hash, err := encodeProductPolicy(policy) + if err != nil { + return PolicyVersion{}, err + } + if len(stored.DocumentHash) != len(hash) || subtle.ConstantTimeCompare(stored.DocumentHash, hash[:]) != 1 { + return PolicyVersion{}, fmt.Errorf("%s - verify document hash: %w", location, ErrPolicyDocumentIntegrity) + } + return PolicyVersion{ + id: stored.ID, + key: key, + version: stored.Version, + kind: kind, + author: author, + effectiveAt: stored.EffectiveAt, + createdAt: stored.CreatedAt, + policy: policy, + document: document, + documentHash: hash, + }, nil +} + +func validateVersionIdentity(location string, key PolicyKey, kind PolicyKind, author PolicyAuthor) error { + if _, err := ParsePolicyKey(string(key)); err != nil { + return fmt.Errorf("%s - validate key: %w", location, err) + } + if _, err := ParsePolicyKind(string(kind)); err != nil { + return fmt.Errorf("%s - validate kind: %w", location, err) + } + if _, err := ParsePolicyAuthor(string(author)); err != nil { + return fmt.Errorf("%s - validate author: %w", location, err) + } + return nil +} + +func checkKindMatchesCalibration(location string, kind PolicyKind, policy ProductPolicy) error { + if kind == PolicyKindCalibrated && policy.Assessment.Calibration != AssessmentCalibrationCalibrated { + return invalidPolicyVersion(location, "a calibrated version requires a calibrated assessment section") + } + return nil +} + +func invalidPolicyVersion(location, reason string) error { + return fmt.Errorf("%s - %s: %w", location, reason, ErrInvalidPolicyVersion) +} + +func (version PolicyVersion) ID() PolicyVersionID { return version.id } + +func (version PolicyVersion) Key() PolicyKey { return version.key } + +// Version is the number of the version within its family, starting at 1. +func (version PolicyVersion) Version() int32 { return version.version } + +// Kind is the calibration state of the whole version. Consumers that make or +// report a quality claim read this flag; the assessment section's own marker +// always agrees with it for calibrated versions. +func (version PolicyVersion) Kind() PolicyKind { return version.kind } + +func (version PolicyVersion) Author() PolicyAuthor { return version.author } + +func (version PolicyVersion) EffectiveAt() time.Time { return version.effectiveAt } + +// CreatedAt is the publication time from the database clock. +func (version PolicyVersion) CreatedAt() time.Time { return version.createdAt } + +// Policy returns a copy of the typed policy. +func (version PolicyVersion) Policy() ProductPolicy { return version.policy.clone() } + +// Document returns a copy of the canonical document. +func (version PolicyVersion) Document() []byte { return append([]byte(nil), version.document...) } + +func (version PolicyVersion) DocumentHash() PolicyDocumentHash { return version.documentHash } + +// IsZero reports a PolicyVersion not built by RestorePolicyVersion. +func (version PolicyVersion) IsZero() bool { return version.id.IsZero() } diff --git a/backend/internal/port/outbound/policy.go b/backend/internal/port/outbound/policy.go new file mode 100644 index 0000000..5bb5d35 --- /dev/null +++ b/backend/internal/port/outbound/policy.go @@ -0,0 +1,74 @@ +package outbound + +import ( + "context" + "errors" + "time" + + "lincodex/backend/internal/domain" +) + +var ( + // ErrPolicyVersionNotFound reports that no version matches: an unknown + // ID, a family without versions, or no version effective at the time. + ErrPolicyVersionNotFound = errors.New("policy version not found") + + // ErrPolicyVersionConflict reports that the family already has a version + // with the same number, or the ID is taken. Nothing was stored and the + // surrounding transaction stays usable; a publisher computes the next + // number again and retries. + ErrPolicyVersionConflict = errors.New("policy version already exists") + + // ErrPolicyVersionBackdated reports a scheduled effective time earlier + // than the publication time that the database assigned. + ErrPolicyVersionBackdated = errors.New("policy version effective time precedes its publication") + + // ErrPolicyVersionImmutable reports an attempt to change or remove a + // stored version. The database refuses every UPDATE, DELETE, and + // TRUNCATE of policy versions; publish a new version instead. + ErrPolicyVersionImmutable = errors.New("policy version is immutable") +) + +// PolicyRepository stores immutable policy versions. It has no update or +// delete method. UnitOfWork binds it to a transaction; an adapter may also +// provide it outside a transaction, where every call is its own statement. +// Every method that takes a time rejects the zero time, and every method +// that takes a family rejects an unknown one with +// domain.ErrInvalidPolicyVersion before it reads storage. A returned version +// passed domain.RestorePolicyVersion, including its document hash check, so +// a row changed outside the application fails with +// domain.ErrPolicyDocumentIntegrity and a row of an unknown document layout +// fails with domain.ErrInvalidPolicy. +// +// A record built under a policy stores the ID of the version it used and +// reads that version with GetByID later. It never recomputes the version +// with GetEffective, whose answer for a past time changes when a version +// scheduled for that time is superseded by a later publication. +type PolicyRepository interface { + // Create stores a numbered draft and returns the stored version with the + // publication time from the database clock. A draft without an effective + // time becomes effective at publication. It returns an error wrapping + // ErrPolicyVersionConflict when the family already has that number or the + // ID exists, without aborting a surrounding transaction, and + // ErrPolicyVersionBackdated when the scheduled effective time precedes + // the publication time. + Create(ctx context.Context, draft domain.PolicyVersionDraft) (domain.PolicyVersion, error) + + // GetByID returns ErrPolicyVersionNotFound when no version has the ID. + GetByID(ctx context.Context, id domain.PolicyVersionID) (domain.PolicyVersion, error) + + // GetEffective returns the newest publication among the versions of the + // family whose effective time is not after at: the highest number, not + // the latest effective time. A version scheduled for later therefore + // never undoes a version published after it. It returns + // ErrPolicyVersionNotFound when no version is effective yet. + GetEffective(ctx context.Context, key domain.PolicyKey, at time.Time) (domain.PolicyVersion, error) + + // GetLatest returns the version with the highest number in the family, + // whether or not it is effective yet, or ErrPolicyVersionNotFound. + GetLatest(ctx context.Context, key domain.PolicyKey) (domain.PolicyVersion, error) + + // HasVersions reports whether the family has any version. It reads no + // document, so it works even when a stored document cannot be decoded. + HasVersions(ctx context.Context, key domain.PolicyKey) (bool, error) +} diff --git a/backend/internal/port/outbound/transaction.go b/backend/internal/port/outbound/transaction.go index 3b4d3f0..8988e97 100644 --- a/backend/internal/port/outbound/transaction.go +++ b/backend/internal/port/outbound/transaction.go @@ -49,6 +49,7 @@ type Transactor interface { // repositories are added here as their usecases appear. type UnitOfWork interface { IdentityRepositories + Policies() PolicyRepository Outbox() OutboxWriter } diff --git a/backend/internal/usecase/policy/publisher.go b/backend/internal/usecase/policy/publisher.go new file mode 100644 index 0000000..7d24c53 --- /dev/null +++ b/backend/internal/usecase/policy/publisher.go @@ -0,0 +1,148 @@ +// Package policy publishes immutable versions of product policies. +package policy + +import ( + "context" + "errors" + "fmt" + "math" + "time" + + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" +) + +// maxPublishAttempts bounds retries after a concurrent publication took the +// computed version number. Each round lets at least one contender commit, so +// a publisher racing with fewer than this many others always succeeds. +const maxPublishAttempts = 10 + +// ErrPublishContended reports that every attempt lost the version number to +// a concurrent publication of the same family. Nothing was stored. +var ErrPublishContended = errors.New("policy publication contended") + +// Publisher stores new policy versions with the next free number of their +// family. The repository may be standalone or bound to a transaction: a +// number conflict does not abort the transaction, and under READ COMMITTED +// every retry reads the numbers committed in the meantime. +type Publisher struct { + policies outbound.PolicyRepository + clock func() time.Time +} + +// NewPublisher takes the application clock, which it uses only to refuse a +// scheduled effective time that has already passed before storage is +// touched. The publication time itself comes from the database. +func NewPublisher(policies outbound.PolicyRepository, clock func() time.Time) *Publisher { + return &Publisher{policies: policies, clock: clock} +} + +// PublishInput describes a version to publish. A zero EffectiveAt makes the +// version effective at publication. +type PublishInput struct { + Key domain.PolicyKey + Kind domain.PolicyKind + Author domain.PolicyAuthor + EffectiveAt time.Time + Policy domain.ProductPolicy +} + +// Publish validates the input, then stores the policy as the next version of +// its family. The number is the highest stored number plus one; when a +// concurrent publication takes it first, Publish reads the highest number +// again, up to maxPublishAttempts times. +func (publisher *Publisher) Publish(ctx context.Context, input PublishInput) (domain.PolicyVersion, error) { + if !input.EffectiveAt.IsZero() && input.EffectiveAt.Before(publisher.clock()) { + return domain.PolicyVersion{}, fmt.Errorf("Publisher.Publish - scheduled effective time has passed: %w", domain.ErrInvalidPolicyVersion) + } + draft, err := domain.NewPolicyVersionDraft(domain.NewPolicyVersionDraftInput{ + Key: input.Key, + Kind: input.Kind, + Author: input.Author, + EffectiveAt: input.EffectiveAt, + Policy: input.Policy, + }) + if err != nil { + return domain.PolicyVersion{}, fmt.Errorf("Publisher.Publish - build draft: %w", err) + } + for range maxPublishAttempts { + if err := ctx.Err(); err != nil { + return domain.PolicyVersion{}, fmt.Errorf("Publisher.Publish - wait for next attempt: %w", err) + } + number, err := publisher.nextVersionNumber(ctx, input.Key) + if err != nil { + return domain.PolicyVersion{}, err + } + numbered, err := draft.WithVersion(number) + if err != nil { + return domain.PolicyVersion{}, fmt.Errorf("Publisher.Publish - number draft: %w", err) + } + stored, err := publisher.policies.Create(ctx, numbered) + if errors.Is(err, outbound.ErrPolicyVersionConflict) { + continue + } + if err != nil { + return domain.PolicyVersion{}, fmt.Errorf("Publisher.Publish - store version: %w", err) + } + return stored, nil + } + return domain.PolicyVersion{}, fmt.Errorf("Publisher.Publish - store version after %d attempts: %w", maxPublishAttempts, ErrPublishContended) +} + +func (publisher *Publisher) nextVersionNumber(ctx context.Context, key domain.PolicyKey) (int32, error) { + latest, err := publisher.policies.GetLatest(ctx, key) + if errors.Is(err, outbound.ErrPolicyVersionNotFound) { + return 1, nil + } + if err != nil { + return 0, fmt.Errorf("Publisher.nextVersionNumber - read latest version: %w", err) + } + if latest.Version() == math.MaxInt32 { + return 0, fmt.Errorf("Publisher.nextVersionNumber - version numbers are exhausted: %w", domain.ErrInvalidPolicyVersion) + } + return latest.Version() + 1, nil +} + +// DemoSeedResult reports what EnsureDemoProductPolicy did. Version is set only +// when this call stored the demo version. +type DemoSeedResult struct { + Created bool + Version domain.PolicyVersion +} + +// EnsureDemoProductPolicy publishes domain.DemoProductPolicyV1 as version 1 +// of domain.ProductPolicyKey, effective at publication, when the family has +// no version yet. It checks presence only and never decodes a stored +// version, so a row of a newer or unknown document layout cannot block it. +// It is idempotent, also when several instances run it at once: the loser of +// the race for version 1 reports that nothing was created. +func (publisher *Publisher) EnsureDemoProductPolicy(ctx context.Context) (DemoSeedResult, error) { + draft, err := domain.NewPolicyVersionDraft(domain.NewPolicyVersionDraftInput{ + Key: domain.ProductPolicyKey, + Kind: domain.PolicyKindDemo, + Author: domain.DemoPolicySeedAuthor, + Policy: domain.DemoProductPolicyV1(), + }) + if err != nil { + return DemoSeedResult{}, fmt.Errorf("Publisher.EnsureDemoProductPolicy - build demo draft: %w", err) + } + numbered, err := draft.WithVersion(1) + if err != nil { + return DemoSeedResult{}, fmt.Errorf("Publisher.EnsureDemoProductPolicy - number demo draft: %w", err) + } + present, err := publisher.policies.HasVersions(ctx, domain.ProductPolicyKey) + if err != nil { + return DemoSeedResult{}, fmt.Errorf("Publisher.EnsureDemoProductPolicy - check existing versions: %w", err) + } + if present { + return DemoSeedResult{}, nil + } + stored, err := publisher.policies.Create(ctx, numbered) + if errors.Is(err, outbound.ErrPolicyVersionConflict) { + return DemoSeedResult{}, nil + } + if err != nil { + return DemoSeedResult{}, fmt.Errorf("Publisher.EnsureDemoProductPolicy - store demo version: %w", err) + } + return DemoSeedResult{Created: true, Version: stored}, nil +} diff --git a/backend/internal/usecase/policy/publisher_test.go b/backend/internal/usecase/policy/publisher_test.go new file mode 100644 index 0000000..93cc1e1 --- /dev/null +++ b/backend/internal/usecase/policy/publisher_test.go @@ -0,0 +1,316 @@ +package policy + +import ( + "context" + "errors" + "sync" + "testing" + "time" + + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" +) + +var testNow = time.Date(2026, time.October, 6, 12, 0, 0, 0, time.UTC) + +func testClock() time.Time { return testNow } + +// memoryPolicies is an in-memory PolicyRepository that stamps publication +// times like the database. beforeCreate runs before each Create and lets a +// test simulate a concurrent publication. +type memoryPolicies struct { + mu sync.Mutex + versions []domain.PolicyVersion + beforeCreate func(draft domain.PolicyVersionDraft) + createCalls int + readCalls int + getLatestErr error + hasVersionErr error +} + +var _ outbound.PolicyRepository = (*memoryPolicies)(nil) + +func (store *memoryPolicies) Create(_ context.Context, draft domain.PolicyVersionDraft) (domain.PolicyVersion, error) { + store.mu.Lock() + store.createCalls++ + hook := store.beforeCreate + store.mu.Unlock() + if hook != nil { + hook(draft) + } + store.mu.Lock() + defer store.mu.Unlock() + for _, stored := range store.versions { + if stored.Key() == draft.Key() && stored.Version() == draft.Version() { + return domain.PolicyVersion{}, outbound.ErrPolicyVersionConflict + } + } + stored, err := restoreDraft(draft, testNow) + if err != nil { + return domain.PolicyVersion{}, err + } + store.versions = append(store.versions, stored) + return stored, nil +} + +func restoreDraft(draft domain.PolicyVersionDraft, createdAt time.Time) (domain.PolicyVersion, error) { + effectiveAt, scheduled := draft.EffectiveAt() + if !scheduled { + effectiveAt = createdAt + } + hash := draft.DocumentHash() + return domain.RestorePolicyVersion(domain.StoredPolicyVersion{ + ID: draft.ID(), Key: string(draft.Key()), Version: draft.Version(), Kind: string(draft.Kind()), + Author: string(draft.Author()), EffectiveAt: effectiveAt, CreatedAt: createdAt, + Document: draft.Document(), DocumentHash: hash[:], + }) +} + +func (store *memoryPolicies) GetByID(context.Context, domain.PolicyVersionID) (domain.PolicyVersion, error) { + return domain.PolicyVersion{}, errors.New("memoryPolicies.GetByID - not used by the publisher") +} + +func (store *memoryPolicies) GetEffective(context.Context, domain.PolicyKey, time.Time) (domain.PolicyVersion, error) { + return domain.PolicyVersion{}, errors.New("memoryPolicies.GetEffective - not used by the publisher") +} + +func (store *memoryPolicies) GetLatest(_ context.Context, key domain.PolicyKey) (domain.PolicyVersion, error) { + store.mu.Lock() + defer store.mu.Unlock() + store.readCalls++ + if store.getLatestErr != nil { + return domain.PolicyVersion{}, store.getLatestErr + } + var latest domain.PolicyVersion + for _, stored := range store.versions { + if stored.Key() == key && stored.Version() > latest.Version() { + latest = stored + } + } + if latest.IsZero() { + return domain.PolicyVersion{}, outbound.ErrPolicyVersionNotFound + } + return latest, nil +} + +func (store *memoryPolicies) HasVersions(_ context.Context, key domain.PolicyKey) (bool, error) { + store.mu.Lock() + defer store.mu.Unlock() + store.readCalls++ + if store.hasVersionErr != nil { + return false, store.hasVersionErr + } + for _, stored := range store.versions { + if stored.Key() == key { + return true, nil + } + } + return false, nil +} + +// insertDirect stores a version as a concurrent publisher would. +func (store *memoryPolicies) insertDirect(t *testing.T, number int32) { + t.Helper() + draft, err := domain.NewPolicyVersionDraft(domain.NewPolicyVersionDraftInput{ + Key: domain.ProductPolicyKey, Kind: domain.PolicyKindCalibrated, Author: "operator:concurrent", Policy: publisherTestPolicy(), + }) + if err == nil { + draft, err = draft.WithVersion(number) + } + var stored domain.PolicyVersion + if err == nil { + stored, err = restoreDraft(draft, testNow) + } + if err != nil { + t.Errorf("build concurrent version: %v", err) + return + } + store.mu.Lock() + defer store.mu.Unlock() + store.versions = append(store.versions, stored) +} + +// publisherTestPolicy is a valid policy built independently of the demo +// policy, so these tests never stand in for the agreed demo values. +func publisherTestPolicy() domain.ProductPolicy { + return domain.ProductPolicy{ + Invitations: domain.InvitationPolicy{ + ResponseDeadlineOptions: []domain.CalendarDays{2, 6}, DefaultResponseDeadline: 2, + MaxPendingPerNeed: 9, RepeatAfterDecline: 9, InterviewProposalDeadline: 4, NoDealPause: 9, + }, + OrganizationQuotas: domain.OrganizationQuotaPolicy{ + InvitationWindow: 5, CardViewWindow: 10, + TierE0: domain.OrganizationTierQuota{Active: true, InvitationsPerWindow: 3, DistinctCardViewsPerWindow: 9}, + TierE1: domain.OrganizationTierQuota{Active: false, InvitationsPerWindow: 4, DistinctCardViewsPerWindow: 9}, + TierE2: domain.OrganizationTierQuota{Active: false, InvitationsPerWindow: 5, DistinctCardViewsPerWindow: 9}, + }, + Assessment: domain.AssessmentPolicy{ + Calibration: domain.AssessmentCalibrationCalibrated, SameGradeRetryAfter: 9, MaxAttemptsPerWindow: 4, + AttemptWindow: 90, PromotionMinInterval: 60, ConfirmationThreshold: 7700, HighStrengthThreshold: 9100, + PracticeRequired: true, + StopRule: domain.AssessmentStopRule{ + MinScoredItems: 6, MaxScoredItems: 18, SeedItems: 3, + UpperProbability: 9300, LowerProbability: 1200, MaxStandardError: 2700, + }, + }, + Identity: domain.IdentityPolicy{ + VerificationTokenLifetime: 9, UnverifiedAccountLifetime: 4, SessionIdleTimeout: 9, SessionAbsoluteLifetime: 4, + }, + SearchStatus: domain.SearchStatusPolicy{SearchingConfirmationInterval: 9}, + } +} + +func publishInput() PublishInput { + return PublishInput{ + Key: domain.ProductPolicyKey, + Kind: domain.PolicyKindCalibrated, + Author: "operator:publisher-test", + Policy: publisherTestPolicy(), + } +} + +func TestPublishNumbersVersionsAndAppliesSchedule(t *testing.T) { + store := &memoryPolicies{} + publisher := NewPublisher(store, testClock) + for want := int32(1); want <= 3; want++ { + version, err := publisher.Publish(t.Context(), publishInput()) + if err != nil { + t.Fatalf("Publish() error = %v", err) + } + if version.Version() != want || !version.EffectiveAt().Equal(version.CreatedAt()) { + t.Fatalf("Publish() = v%d effective %s, want v%d effective at publication", version.Version(), version.EffectiveAt(), want) + } + } + scheduled := publishInput() + scheduled.EffectiveAt = testNow.Add(time.Hour) + version, err := publisher.Publish(t.Context(), scheduled) + if err != nil || !version.EffectiveAt().Equal(scheduled.EffectiveAt) { + t.Fatalf("Publish(scheduled) = effective %s, %v; want %s", version.EffectiveAt(), err, scheduled.EffectiveAt) + } +} + +func TestPublishRetriesAfterAConcurrentPublication(t *testing.T) { + store := &memoryPolicies{} + raced := false + store.beforeCreate = func(draft domain.PolicyVersionDraft) { + if !raced { + raced = true + store.insertDirect(t, draft.Version()) + } + } + version, err := NewPublisher(store, testClock).Publish(t.Context(), publishInput()) + if err != nil { + t.Fatalf("Publish() error = %v", err) + } + if version.Version() != 2 || store.createCalls != 2 { + t.Fatalf("Publish() = v%d after %d attempts, want v2 after 2", version.Version(), store.createCalls) + } +} + +func TestPublishGivesUpAfterBoundedAttempts(t *testing.T) { + store := &memoryPolicies{} + store.beforeCreate = func(draft domain.PolicyVersionDraft) { store.insertDirect(t, draft.Version()) } + _, err := NewPublisher(store, testClock).Publish(t.Context(), publishInput()) + if !errors.Is(err, ErrPublishContended) { + t.Fatalf("Publish() error = %v, want ErrPublishContended", err) + } + if store.createCalls != maxPublishAttempts { + t.Fatalf("Publish() made %d attempts, want %d", store.createCalls, maxPublishAttempts) + } +} + +func TestPublishValidatesBeforeReadingStorage(t *testing.T) { + tests := map[string]struct { + mutate func(*PublishInput) + want error + }{ + "effective time in the past": { + mutate: func(input *PublishInput) { input.EffectiveAt = testNow.Add(-time.Second) }, + want: domain.ErrInvalidPolicyVersion, + }, + "unknown family": {mutate: func(input *PublishInput) { input.Key = "other" }, want: domain.ErrInvalidPolicyVersion}, + "invalid author": {mutate: func(input *PublishInput) { input.Author = "tester@example.com" }, want: domain.ErrInvalidPolicyVersion}, + "invalid policy": {mutate: func(input *PublishInput) { input.Policy.Assessment.StopRule.MinScoredItems = 0 }, want: domain.ErrInvalidPolicy}, + "calibration flag": {mutate: func(input *PublishInput) { + input.Policy.Assessment.Calibration = domain.AssessmentCalibrationUncalibratedInitial + }, want: domain.ErrInvalidPolicyVersion}, + } + for name, test := range tests { + t.Run(name, func(t *testing.T) { + store := &memoryPolicies{} + input := publishInput() + test.mutate(&input) + if _, err := NewPublisher(store, testClock).Publish(t.Context(), input); !errors.Is(err, test.want) { + t.Fatalf("Publish() error = %v, want %v", err, test.want) + } + if store.readCalls != 0 || store.createCalls != 0 { + t.Fatalf("Publish() touched storage %d reads and %d creates for refused input", store.readCalls, store.createCalls) + } + }) + } +} + +func TestPublishReturnsStorageErrorsWithoutRetry(t *testing.T) { + unavailable := errors.New("database unavailable") + store := &memoryPolicies{getLatestErr: unavailable} + if _, err := NewPublisher(store, testClock).Publish(t.Context(), publishInput()); !errors.Is(err, unavailable) { + t.Fatalf("Publish() error = %v, want the storage error", err) + } + if store.readCalls != 1 || store.createCalls != 0 { + t.Fatalf("Publish() made %d reads and %d creates, want one read", store.readCalls, store.createCalls) + } +} + +func TestEnsureDemoProductPolicyInsertsOnce(t *testing.T) { + store := &memoryPolicies{} + publisher := NewPublisher(store, testClock) + + first, err := publisher.EnsureDemoProductPolicy(t.Context()) + if err != nil || !first.Created { + t.Fatalf("EnsureDemoProductPolicy() = %+v, %v; want a created version", first, err) + } + version := first.Version + if version.Key() != domain.ProductPolicyKey || version.Version() != 1 || version.Kind() != domain.PolicyKindDemo || + version.Author() != domain.DemoPolicySeedAuthor || !version.EffectiveAt().Equal(version.CreatedAt()) { + t.Fatalf("demo version = %s v%d %s by %s effective %s", version.Key(), version.Version(), version.Kind(), version.Author(), version.EffectiveAt()) + } + if version.Policy().Assessment.Calibration != domain.AssessmentCalibrationUncalibratedInitial { + t.Fatal("demo version carries a calibrated assessment section") + } + + second, err := publisher.EnsureDemoProductPolicy(t.Context()) + if err != nil || second.Created || !second.Version.IsZero() { + t.Fatalf("second EnsureDemoProductPolicy() = %+v, %v; want a skip", second, err) + } + if len(store.versions) != 1 || store.createCalls != 1 { + t.Fatalf("store holds %d versions after %d creates, want one", len(store.versions), store.createCalls) + } +} + +func TestEnsureDemoProductPolicySkipsAnyExistingVersion(t *testing.T) { + store := &memoryPolicies{} + store.insertDirect(t, 4) + // A presence check only: the stored version is never read. + store.getLatestErr = errors.New("memoryPolicies.GetLatest - must not be called by the seed") + result, err := NewPublisher(store, testClock).EnsureDemoProductPolicy(t.Context()) + if err != nil || result.Created || store.createCalls != 0 { + t.Fatalf("EnsureDemoProductPolicy() = %+v, %v after %d creates; want a skip", result, err, store.createCalls) + } +} + +func TestEnsureDemoProductPolicyTreatsAConcurrentSeedAsPresent(t *testing.T) { + store := &memoryPolicies{} + store.beforeCreate = func(draft domain.PolicyVersionDraft) { store.insertDirect(t, draft.Version()) } + result, err := NewPublisher(store, testClock).EnsureDemoProductPolicy(t.Context()) + if err != nil || result.Created || len(store.versions) != 1 { + t.Fatalf("EnsureDemoProductPolicy() = %+v, %v with %d stored versions; want a skip", result, err, len(store.versions)) + } +} + +func TestEnsureDemoProductPolicyReturnsPresenceErrors(t *testing.T) { + unavailable := errors.New("database unavailable") + store := &memoryPolicies{hasVersionErr: unavailable} + if _, err := NewPublisher(store, testClock).EnsureDemoProductPolicy(t.Context()); !errors.Is(err, unavailable) { + t.Fatalf("EnsureDemoProductPolicy() error = %v, want the storage error", err) + } +} diff --git a/docs/en/ARCHITECTURE.md b/docs/en/ARCHITECTURE.md index 4a6916e..5cc992b 100644 --- a/docs/en/ARCHITECTURE.md +++ b/docs/en/ARCHITECTURE.md @@ -89,6 +89,57 @@ Implemented: the outbound `MailSender` port (`backend/internal/port/outbound/mai A non-nil error means the message certainly did not leave the process: `ErrMailChannelUnavailable` in `disabled` mode, `ErrInvalidOutgoingMail` for an invalid message, or the context error. Retries, backoff, and recording outcomes belong to a single planned delivery layer, not to the transport. The verification flows (TASK-053, TASK-054) must treat `ErrMailChannelUnavailable` as not sent: it never confirms an address or replaces an account check. `OutgoingMail` redacts itself in `fmt` and `slog` output, and transport errors and logs never contain recipients, subjects, bodies, credentials, or raw provider responses. +### Product policy versions + +Implemented as storage, a publisher, and a startup seed (TASK-005): migration `backend/db/migrations/00003_create_policy_versions.sql`, queries in `backend/db/queries/policy.sql`, the typed policy in `backend/internal/domain/` (`policy.go`, `policy_document.go`, `policy_version.go`, `policy_demo.go`), the `outbound.PolicyRepository` port (`port/outbound/policy.go`), the sqlc-backed adapter in `backend/internal/adapter/secondary/postgres/policy.go`, and the publisher in `backend/internal/usecase/policy/`. No product rule reads the policy yet; invitations, quotas, assessment, sessions, and the search status will read it as their tasks are implemented. + +`policy_versions` columns: + +- `id`: uuid primary key, a UUIDv7 generated in Go (`domain.PolicyVersionID`). +- `policy_key`: the policy family. Each family has one document layout and one decoder; `product`, decoded as `domain.ProductPolicy`, is the only family, and both the domain and the `policy_versions_policy_key_known` CHECK reject any other. `version`: an integer above zero, unique within the family (`policy_versions_policy_key_version_key`); the newest publication has the highest number. +- `kind`: `demo` or `calibrated`, the calibration state of the whole version. Consumers read this flag. The `policy_versions_calibrated_kind_matches_document` CHECK and the domain refuse a `calibrated` version whose document marks the assessment section as uncalibrated. +- `created_at`: the publication time from the database clock. The BEFORE INSERT trigger `policy_versions_stamp_creation` sets it to `clock_timestamp()` on every insert and ignores a value from the caller. +- `effective_at`: when the version can start to apply. A NULL in the insert means "at publication", and the same trigger sets it to `created_at`; a scheduled time must not be earlier (`policy_versions_effective_after_creation`, mapped to `outbound.ErrPolicyVersionBackdated`). +- `author`: `system:` or `operator:`, at most 128 bytes of lowercase letters, digits, `.`, `_`, and `-`. It excludes `@`, so it cannot hold an email address. It is text rather than a reference to `users`: the seed has no account, admin roles do not exist yet, and a version must outlive any account, while a cascading or nulling foreign key would conflict with immutability. An admin editor can add an account reference in an additive migration. +- `document`: a jsonb object with the typed policy. `document_sha256`: the SHA-256 of the canonical document, 32 raw bytes. + +The database enforces immutability. The trigger function `policy_versions_refuse_change` refuses every UPDATE and DELETE (row trigger) and TRUNCATE (statement trigger) with SQLSTATE 23000 and the constraint name `policy_versions_immutable`; the adapter maps exactly that pair to `outbound.ErrPolicyVersionImmutable`, never the message. The port has no update or delete method, so a change is always a new version. The guarantee covers application statements and manual SQL; a role that owns the table can still disable the trigger or drop the table, so a least-privilege runtime role remains future work. + +Typed policy, `domain.ProductPolicy`: every value is a named field whose type carries the unit: `CalendarDays`, `BusinessDays` (no conversion to a duration; the consuming feature supplies the business calendar), `Hours`, and `BasisPoints` for probabilities and the standard error, an integer count of 0.0001 (0.80 is 8000). Basis points compare exactly, without floating-point drift, and keep integers in the document. The `Validate` method of each section rejects zero, missing, and out-of-range values and inconsistent combinations, such as a default deadline outside the options, a higher quota tier with a lower limit, an inactive E0, an active tier above an inactive one, or stop probabilities that do not surround the confirmation threshold. The ranges are sanity bounds against unit mistakes, not product decisions. Quota tiers E0 < E1 < E2 are looked up with `OrganizationQuotaPolicy.Tier(domain.OrganizationTier)` (for TASK-087); every organization starts at E0, and the rules that move it between tiers belong to the quota feature. + +Open question for the attempt tasks (TASK-157 and TASK-158): `MaxAttemptsPerWindow` stores only the number. Whether the limit counts per grade, per specialty, or across all assessments of a candidate is not decided. + +The document has `schema_version` 1 and the sections `invitations`, `organization_quotas`, `assessment`, `identity`, and `search_status`; field names carry their unit (`_days`, `_business_days`, `_hours`, `_bp`). Decoding is strict: it rejects unknown fields, missing or null fields, wrong types, fractions, values outside int32, an unknown schema version, trailing data, and documents over 64 KiB. The canonical form is the compact Go encoding in field declaration order. jsonb normalizes key order, so `domain.RestorePolicyVersion` decodes the stored document, validates it, encodes it again, and compares its SHA-256 with `document_sha256`; a mismatch returns `domain.ErrPolicyDocumentIntegrity`. A golden test pins the canonical form, because a change would make every stored version fail this check; a new layout needs a new schema version and decoder. + +The port `outbound.PolicyRepository` is available through `UnitOfWork.Policies()` and outside a transaction through `postgres.PolicyStore`. Methods that take a family reject an unknown one before reading storage. + +- `Create` stores a numbered `domain.PolicyVersionDraft` and returns the stored `domain.PolicyVersion` with the database times. The insert uses `ON CONFLICT DO NOTHING`, so a taken number or ID returns `ErrPolicyVersionConflict` without aborting a surrounding transaction. +- `GetByID` reads one version. +- `GetEffective(key, at)` returns the newest publication, the highest number, among the versions whose `effective_at` is not after `at`. A version scheduled for later therefore never undoes a version published after it: an urgent correction stays in effect when an earlier scheduled version reaches its time, and the scheduled version is superseded. The unique `(policy_key, version)` index serves this lookup. +- `GetLatest(key)` returns the highest number, effective or not. +- `HasVersions(key)` reports presence without reading a document. +- Misses return `ErrPolicyVersionNotFound`. + +`policy.Publisher` validates the whole input before it reads storage. It takes the application clock only to refuse a scheduled effective time that has already passed; the publication time comes from the database. `Publish` assigns the highest stored number plus one; when a concurrent publication takes the number, it reads again and retries up to 10 times, then returns `policy.ErrPublishContended`. It works on a standalone repository or inside a unit of work. + +Demo and calibrated policy: `domain.DemoProductPolicyV1()` is the accepted initial policy for verifying the product flow. It is published as version 1 of `product` with kind `demo` and author `system:demo-seed`, and its assessment section is marked `uncalibrated_initial`. These values make no calibrated quality claim. The policy holds rules only; assessment content (the task bank, blueprints, and variants) is a separate task. Demo version 1: + +| Section | Values | +| --- | --- | +| `invitations` | response deadline options 3, 7, and 14 days, default 7; at most 20 pending invitations per need; repeat after a decline in 30 days; interview proposal within 5 business days; 30-day pause after no deal | +| `organization_quotas` | rolling windows of 7 days for invitations and 24 hours for distinct card views; E0 10 invitations and 50 views, E1 40 and 150, E2 100 and 400; E2 is inactive until the organization verification that grants it exists | +| `assessment`, uncalibrated initial | same-grade retry after 30 days; at most 3 attempts per 180 days; at most one promotion per 90 days; confirmation at P_G >= 0.80, high strength from 0.90; after at least 8 scored items stop at P_G >= 0.90 or <= 0.10 or SE <= 0.25; at most 23 scored items plus 2 seed items; practice is mandatory | +| `identity` | verification token 24 hours; unverified account deleted 7 days after the latest registration; session idle timeout 24 hours, absolute lifetime 7 days | +| `search_status` | the "searching" status is confirmed every 30 days | + +The identity lifetimes in this table are the values of the identity contract ([api/README.en.md](../../api/README.en.md#identity-sessions-cookie-and-csrf)). They come from the versioned product policy, not from configuration: the registration, verification, and session usecases will read them from the effective policy version. The grade rules in [Assessment and grade verification](#assessment-and-grade-verification) use the same assessment values. + +Seeding: at startup, after migrations and under the same condition (`DATABASE_MIGRATE_ON_START` is true and `DATABASE_URL` is set), bootstrap calls `Publisher.EnsureDemoProductPolicy`. It checks only whether `product` has any version and never decodes one, so a stored version of a newer or unknown layout cannot block startup. When the family is empty, it publishes demo version 1 effective at publication; otherwise it changes nothing and logs that the seed was skipped. Instances that start together race for version 1, and the loser skips. The log line names only the key, number, kind, and ID. A database error stops startup. The seed is not a data insert in a migration, so the schema and the policy values change independently. + +Referencing a version (planned): tables that record a decision built under a policy, such as grade decisions, selection snapshots, and invitations, carry `policy_version_id uuid NOT NULL REFERENCES policy_versions (id)` and store the version used when the decision was made. An existing decision reads that version with `GetByID` and is never recomputed through `GetEffective`, whose answer for a given time changes when a scheduled version is superseded. A referenced version cannot be deleted, by the foreign key and by the trigger, and a new version never rewrites past decisions. + +Test fixtures use their own values. Since `product` is the only family, the integration tests give every case its own database, and no fixture stands in for the demo policy. + ## Repository map and package purpose ```text @@ -119,11 +170,12 @@ backend/ cmd/app/main.go calls bootstrap.Run and reports errors config/ shared runtime configuration internal/ - domain/ flat package; DomainEvent, identity types + domain/ flat package; DomainEvent, identity types, product policy usecase/health/ operational readiness usecase port/inbound/ readiness input boundary usecase/identity/ password validation before hashing (Credentials) - port/outbound/ readiness, cache, object storage, transaction, outbox, identity, password hashing, and mail boundaries + usecase/policy/ publication of policy versions and the demo policy seed + port/outbound/ readiness, cache, object storage, transaction, outbox, identity, policy, password hashing, and mail boundaries adapter/primary/http/ api/ generated ogen handler middleware/ request metrics @@ -134,22 +186,22 @@ backend/ argon2id/ Argon2id password hasher with a memory budget mail/disabled/ mail transport that sends nothing and reports the channel unavailable ml/api/ generated client from backend/codegen/ogen-ml.yml - postgres/ pool, migrator, transactor, outbox writer, identity repositories, health check + postgres/ pool, migrator, transactor, outbox writer, identity and policy repositories, health check postgres/sqlc/ generated SQL adapter redis/ cache adapter and Redis check seaweedfs/ S3 adapter and bucket check prometheus/ bounded Go/process and request metrics bootstrap/ configuration, wiring, lifecycle, shutdown - db/ embedded migrations and SQL queries; outbox and identity tables + db/ embedded migrations and SQL queries; outbox, identity, and policy tables codegen/ ogen and sqlc configs pkg/ reserved for justified shared technical helpers ``` -Domain types live directly in `backend/internal/domain/`: `user.go`, `candidate.go`, and other files as their models are defined. Do not nest directories by entity or feature. The first type is `DomainEvent` in `domain_event.go`, the validated event that a transaction writes to the outbox. Identity storage types live in `email_address.go`, `secret_token.go`, `user.go`, `email_token.go`, and `session.go`; the normalized password is in `password.go`. +Domain types live directly in `backend/internal/domain/`: `user.go`, `candidate.go`, and other files as their models are defined. Do not nest directories by entity or feature. The first type is `DomainEvent` in `domain_event.go`, the validated event that a transaction writes to the outbox. Identity storage types live in `email_address.go`, `secret_token.go`, `user.go`, `email_token.go`, and `session.go`; the normalized password is in `password.go`. The product policy and its versions live in `policy.go`, `policy_document.go`, `policy_version.go`, and `policy_demo.go`. Product domain types and usecase modules, the Resend, SMTP, and FSP adapters, and the worker are reserved areas; their business behavior is not implemented. Keep `main.go` limited to starting bootstrap and handling process errors. The public generated transport uses ogen v1.24.0 and the contracts declare OpenAPI 3.2.0. Verify only the feature subset used by the repository, not every specification feature. -This is a compact map, not a claim that every planned product package exists. Current Go code includes health usecases and adapters, generated API clients, bootstrap with startup migrations, a PostgreSQL health query, the transactional outbox writer, identity repositories without the usecases that will use them, the `PasswordHasher` port with the Argon2id adapter and the password check that registration will call, a Redis cache adapter, a SeaweedFS S3 adapter, and the `MailSender` port with the `disabled` transport. Account behavior (registration, verification, login, sessions), resumes, assessments, invitations, worker jobs, file workflows, mail delivery, the Resend and SMTP transports, and FSP adapters remain planned. Do not create empty module directories before a real use case exists. +This is a compact map, not a claim that every planned product package exists. Current Go code includes health usecases and adapters, generated API clients, bootstrap with startup migrations, a PostgreSQL health query, the transactional outbox writer, identity repositories without the usecases that will use them, the versioned policy store with its publisher and the demo policy seed at startup, the `PasswordHasher` port with the Argon2id adapter and the password check that registration will call, a Redis cache adapter, a SeaweedFS S3 adapter, and the `MailSender` port with the `disabled` transport. Account behavior (registration, verification, login, sessions), resumes, assessments, invitations, worker jobs, file workflows, mail delivery, the Resend and SMTP transports, and FSP adapters remain planned. Do not create empty module directories before a real use case exists. `backend/pkg/` is reserved for small technical packages with a justified shared boundary, not product usecases or domain types. Candidate future packages are `emailtemplate`, `mailer`, and test helpers. Keep the S3 client in the SeaweedFS adapter. Keep service-specific behavior private under `internal/`. @@ -196,11 +248,11 @@ Grade state rules: - Before the first passing assessment, status is unverified and a claimed grade does not grant verified category access. - A failed attempt never lowers an existing verified grade. - After an initial failure, the candidate may choose a lower-level test; the system does not assign it automatically. -- Changes after a successful qualification are rate limited; 90 days is the initial proposal. -- The first lower-level test after failure is outside that interval. Repeating the same level may use a separate cooldown, initially proposed at 24 hours. +- A promotion after a successful qualification is allowed at most once per 90 days. +- The first lower-level test after failure is outside that interval. A retry of the same grade waits 30 days, and a candidate takes at most 3 attempts in any 180 days. - A strong result may suggest a higher-level test. Keep the grade history available. -Thresholds and intervals are pilot proposals, not a validated psychometric model. Task rotation and attempt limits reduce the value of leaked answers but do not prove resistance to hints or LLMs. Difficulty comparability needs measurement. +These intervals are the accepted initial policy, stored as demo version 1 of the [product policy](#product-policy-versions); its thresholds are uncalibrated and are not a validated psychometric model. Task rotation and attempt limits reduce the value of leaked answers but do not prove resistance to hints or LLMs. Difficulty comparability needs measurement. ## Matching and explanations @@ -369,7 +421,7 @@ These are proposed acceptance targets, not results: 30 concurrent users; p95 pro - No contact data appears before a grant in API, search, PDF, errors, or employer-facing ML explanations. Another company never receives it after acceptance. - Candidates cannot read other users' invitations, documents, jobs, or attempts. Companies cannot read other companies' needs or search runs. -- Failure never lowers grade; first lower-level retry is permitted; concurrent requests cannot bypass the proposed 90-day limit. +- Failure never lowers grade; first lower-level retry is permitted; concurrent requests cannot bypass the 90-day promotion limit. - Repeated submit/accept does not create duplicate results; concurrent state transitions are consistent. - The manual path works when ML is off; a worker recovers an expired lease; an old response cannot overwrite a newer document version. - Empty FSP history differs from an integration error and does not exclude a candidate. diff --git a/docs/en/DEPLOY.md b/docs/en/DEPLOY.md index 494c981..692df20 100644 --- a/docs/en/DEPLOY.md +++ b/docs/en/DEPLOY.md @@ -11,7 +11,7 @@ Install Docker Engine and the Docker Compose plugin. At the repository root, cop deploy/docker/docker-compose.yml starts PostgreSQL, Redis, SeaweedFS, Kafka, the Go backend, and the frontend container. Nginx in the frontend container serves static assets and proxies /api to Go. PostgreSQL, Redis, SeaweedFS, Kafka, Go, and Nginx communicate on the Compose network. -Before it opens its listeners, the backend applies the database migrations embedded in its binary; a migration error stops the container. Compose does not pass `DATABASE_MIGRATE_ON_START`, so the deployed backend always migrates at startup, and the PostgreSQL role in `DATABASE_URL` needs DDL rights on the application schema. That flag is a local development option; a separate least-privilege migration role is future work. See [DEVELOPMENT.md](DEVELOPMENT.md#database-migrations). +Before it opens its listeners, the backend applies the database migrations embedded in its binary; a migration error stops the container. Compose does not pass `DATABASE_MIGRATE_ON_START`, so the deployed backend always migrates at startup, and the PostgreSQL role in `DATABASE_URL` needs DDL rights on the application schema. That flag is a local development option; a separate least-privilege migration role is future work. Right after the migrations, and only when they run, the backend seeds the demo product policy: when the `product` policy family has no version, it publishes version 1 and logs `demo product policy published`; otherwise it logs that the seed was skipped and changes nothing. With `DATABASE_MIGRATE_ON_START=false` the seed is skipped too. A database error during the seed stops the container like a migration error. See [DEVELOPMENT.md](DEVELOPMENT.md#database-migrations) and [ARCHITECTURE.md](ARCHITECTURE.md#product-policy-versions). The backend build context is `backend/`, so Docker applies `backend/.dockerignore`. Local tools, caches, environment files, and build outputs are excluded from that context. diff --git a/docs/en/DEVELOPMENT.md b/docs/en/DEVELOPMENT.md index efe9ff0..687f834 100644 --- a/docs/en/DEVELOPMENT.md +++ b/docs/en/DEVELOPMENT.md @@ -48,7 +48,7 @@ The repository contains a verifiable technical scaffold, not a product. Values b What exists now: - Health and readiness routes. Nginx answers `GET /healthz` itself and proxies only `/api/` to Go (deploy/nginx/conf.d/app.conf). Go serves `GET /healthz` (`ok`) and `GET /readyz` (`ready` or 503 `not_ready` after checking PostgreSQL, Redis, and SeaweedFS) on its internal port 8080 outside the OpenAPI contract, plus `GET /api/v1/healthz` from api/core/routes/healthz.yml through the ogen handler (backend/internal/adapter/primary/http). The Go metrics listener uses port 9090 (`METRICS_ADDR`) and Prometheus scrapes `/metrics`. ML serves `GET /healthz`, `GET /readyz` (always 503 `not_ready` because no model is connected), and `/metrics` (ml/src/lincodex_ml, api/ml/routes). deploy/scripts/smoke.sh checks Nginx `/healthz`, `/api/v1/healthz`, Go `/readyz` from inside the Compose network, a 404 for an unknown API route, and that the backend started with `EMAIL_PROVIDER=disabled`; it does not start ML or send mail. -- Adapters: PostgreSQL through pgxpool with a generated `SELECT 1` query, a goose migration runner applied at startup, a transactor with the transactional outbox writer, and sqlc-backed identity repositories for accounts, email tokens, and sessions; Redis through go-cachekit, and SeaweedFS through the S3 API. The Argon2id password hasher and the `identity.Credentials` password check exist and are tested but are not wired into bootstrap. A generated Go client for the ML contract exists but is not wired into bootstrap. +- Adapters: PostgreSQL through pgxpool with a generated `SELECT 1` query, a goose migration runner applied at startup, a transactor with the transactional outbox writer, sqlc-backed identity repositories for accounts, email tokens, and sessions, and the versioned policy repository with the demo policy seed at startup; Redis through go-cachekit, and SeaweedFS through the S3 API. The Argon2id password hasher and the `identity.Credentials` password check exist and are tested but are not wired into bootstrap. A generated Go client for the ML contract exists but is not wired into bootstrap. - Mail: the outbound `MailSender` port, the `disabled` transport, and the `EMAIL_PROVIDER` selection in bootstrap. Only `disabled` works in this build; `resend` and `smtp` fail startup after their settings are validated. Nothing sends mail yet. See [DEPLOY.md](DEPLOY.md#mail) and [ARCHITECTURE.md](ARCHITECTURE.md#mail-transport). - OpenAPI contracts api/core/ and api/ml/ with schema merge, bundles, lint, and generation for Go (ogen), TypeScript (Orval), and Python (datamodel-code-generator). The SPA has an interface scaffold with placeholder screens, a generated API client, and MSW handlers. - Compose projects: core (`deploy/docker/docker-compose.yml`: PostgreSQL, Redis, SeaweedFS, Kafka, backend, frontend), ML (`docker-compose.ml.yml`), and monitoring (`docker-compose.monitoring.yml`). @@ -56,7 +56,7 @@ What exists now: - CI jobs in .github/workflows/ci.yml: `api`, `backend`, `integration` (matrix of two shards), `frontend`, `ml`, `codegen`, `infrastructure`, `security`, `security-images`, `smoke`, and the required `aggregate` result. See [TESTING.md](TESTING.md) for sharding. - Observability: Prometheus, Loki, Alloy, Grafana with provisioned datasources and dashboards, and PostgreSQL, Redis, and node exporters. The React app does not send telemetry yet. -Not implemented yet: registration and login (their contract is declared; the operations answer 501 or 401), consents, profiles, the questionnaire and assessment, the company cabinet, needs and matching, invitations and contacts, the Resend and SMTP transports and mail delivery, the Go Kafka client, the outbox relay, notifications, support, and an end-to-end business suite. backend/db/migrations/ contains the outbox table and the identity storage tables (`users`, `email_tokens`, `sessions`) and no other business schema; registration, verification, and session behavior on top of that storage comes in later tasks, product usecase and adapter directories other than the password hashing pieces contain only placeholders, and `make -C deploy test-e2e` is a deferred placeholder that exits with an error. The target design is in [ARCHITECTURE.md](ARCHITECTURE.md). +Not implemented yet: registration and login (their contract is declared; the operations answer 501 or 401), consents, profiles, the questionnaire and assessment, the company cabinet, needs and matching, invitations and contacts, the Resend and SMTP transports and mail delivery, the Go Kafka client, the outbox relay, notifications, support, and an end-to-end business suite. backend/db/migrations/ contains the outbox table, the identity storage tables (`users`, `email_tokens`, `sessions`), and the `policy_versions` table and no other business schema; no product rule reads the policy yet; registration, verification, and session behavior on top of that storage comes in later tasks, product usecase and adapter directories other than the password hashing and policy pieces contain only placeholders, and `make -C deploy test-e2e` is a deferred placeholder that exits with an error. The target design is in [ARCHITECTURE.md](ARCHITECTURE.md). ## Install and work loop @@ -170,6 +170,14 @@ The database never receives a password, a raw email token, or a raw session toke Passwords enter the backend only as `domain.Password`: `domain.NewPassword` for a new password (15 to 128 code points after NFKC) and `domain.ParseLoginPassword` at login (1 to 128). Raw input over 512 bytes or with invalid UTF-8 is rejected before normalization, and every length check runs before hashing. The `argon2id` adapter implements `outbound.PasswordHasher` with m=65536 KiB, t=3, p=4, a memory budget of `PASSWORD_HASH_CONCURRENCY` derivations (1 to 4; unset means the smaller of 2 and GOMAXPROCS), `ErrPasswordMismatch` for a wrong password, `ErrPasswordHashCorrupt` for a malformed or out-of-bounds stored hash, a `needsRehash` result for older parameters, and `VerifyDummy` for unknown accounts. A stored hash that fails parsing or bounds wraps both `ErrPasswordHashCorrupt` and `domain.ErrInvalidPasswordHash`. Unit tests use cheap parameters; the 64 MiB reference vector is skipped with `-short`; `go test -run '^$' -bench . ./internal/adapter/secondary/argon2id/` in `backend/` measures one hash with the production parameters. See [ARCHITECTURE.md](ARCHITECTURE.md#password-hashing). +### Product policy store + +Migration `00003_create_policy_versions.sql` creates `policy_versions`, the trigger that stamps `created_at` from the database clock, and the triggers that refuse UPDATE, DELETE, and TRUNCATE; the queries are in `backend/db/queries/policy.sql`. `outbound.PolicyRepository` is available through `UnitOfWork.Policies()` and through `postgres.PolicyStore` outside a transaction; `policy.Publisher` publishes a version under the next free number and seeds the demo policy. To change a value, publish a new version; a stored version is never edited. `product` is the only policy family. + +At startup the backend publishes `domain.DemoProductPolicyV1()` as version 1 of `product` when that family has no version. The seed runs right after the startup migrations and only when they run (`DATABASE_MIGRATE_ON_START` is true and `DATABASE_URL` is set). With startup migrations disabled, nothing seeds the policy. The seed checks presence only, never changes or decodes an existing version, and logs only the key, number, kind, and ID. The demo values are the accepted initial policy, not calibrated values. + +A record that depends on policy values adds `policy_version_id uuid NOT NULL REFERENCES policy_versions (id)`, stores the version it used, and reads it back by ID; do not recompute an existing record through `GetEffective`. Tests use their own values and do not stand in for the demo policy. Since `product` is the only family and the table refuses TRUNCATE, the integration tests give every case its own database. A new document layout needs a new `schema_version` and decoder; do not edit the golden document in `backend/internal/domain/policy_test.go` to accept a changed canonical form. See [ARCHITECTURE.md](ARCHITECTURE.md#product-policy-versions). + ## Go readability - Extract repeated parsing, setup, and cleanup into small typed helpers near their consumers. Move code to `pkg/` when several packages actually reuse it. Avoid wrappers that only rename a call. diff --git a/docs/ru/ARCHITECTURE.md b/docs/ru/ARCHITECTURE.md index 72fa4fd..c5c7257 100644 --- a/docs/ru/ARCHITECTURE.md +++ b/docs/ru/ARCHITECTURE.md @@ -89,6 +89,57 @@ Usecase пишет через outbound-порты. `Transactor.WithinTransaction Ненулевая ошибка значит, что письмо точно не покинуло процесс: `ErrMailChannelUnavailable` в режиме `disabled`, `ErrInvalidOutgoingMail` для некорректного письма или ошибка контекста. Повторы, backoff и учет результатов относятся к единому запланированному слою доставки, а не к транспорту. Сценарии подтверждения (TASK-053, TASK-054) обязаны считать `ErrMailChannelUnavailable` неотправкой: он никогда не подтверждает адрес и не заменяет проверку аккаунта. `OutgoingMail` скрывает себя в выводе `fmt` и `slog`, а ошибки и логи транспорта никогда не содержат получателей, темы, тела писем, учетные данные или сырые ответы провайдера. +### Версии продуктовой политики + +Реализованы хранение, публикация и начальное заполнение при старте (TASK-005): миграция `backend/db/migrations/00003_create_policy_versions.sql`, запросы в `backend/db/queries/policy.sql`, типизированная политика в `backend/internal/domain/` (`policy.go`, `policy_document.go`, `policy_version.go`, `policy_demo.go`), порт `outbound.PolicyRepository` (`port/outbound/policy.go`), адаптер на sqlc в `backend/internal/adapter/secondary/postgres/policy.go` и публикация в `backend/internal/usecase/policy/`. Ни одно продуктовое правило пока не читает политику; приглашения, квоты, оценивание, сессии и статус поиска начнут читать ее по мере реализации своих задач. + +Колонки `policy_versions`: + +- `id`: первичный ключ uuid, UUIDv7 из Go (`domain.PolicyVersionID`). +- `policy_key`: семейство политики. У каждого семейства одна структура документа и один декодер; `product`, который разбирается как `domain.ProductPolicy`, - единственное семейство, и любое другое отклоняют и домен, и CHECK `policy_versions_policy_key_known`. `version`: целое больше нуля, уникальное внутри семейства (`policy_versions_policy_key_version_key`); у самой новой публикации наибольший номер. +- `kind`: `demo` или `calibrated`, состояние калибровки всей версии. Потребители читают именно этот признак. CHECK `policy_versions_calibrated_kind_matches_document` и домен отклоняют версию `calibrated`, в документе которой раздел оценивания помечен некалиброванным. +- `created_at`: время публикации по часам базы данных. Триггер BEFORE INSERT `policy_versions_stamp_creation` ставит в него `clock_timestamp()` при каждой вставке и игнорирует значение вызывающего кода. +- `effective_at`: момент, с которого версия может применяться. NULL во вставке означает "с момента публикации", и тот же триггер ставит в него `created_at`; запланированное время не может быть раньше (`policy_versions_effective_after_creation`, сопоставляется с `outbound.ErrPolicyVersionBackdated`). +- `author`: `system:` или `operator:`, не более 128 байт из строчных букв, цифр, `.`, `_` и `-`. Символ `@` не допускается, поэтому email-адрес сюда не попадет. Это текст, а не ссылка на `users`: у начального заполнения нет аккаунта, ролей администратора еще нет, а версия должна пережить любой аккаунт, тогда как каскадный или обнуляемый внешний ключ противоречил бы неизменяемости. Редактор администратора сможет добавить ссылку на аккаунт аддитивной миграцией. +- `document`: jsonb-объект с типизированной политикой. `document_sha256`: SHA-256 канонического документа, 32 байта. + +Неизменяемость обеспечивает база данных. Функция триггера `policy_versions_refuse_change` отклоняет каждый UPDATE и DELETE (строчный триггер) и TRUNCATE (триггер на оператор) с SQLSTATE 23000 и именем ограничения `policy_versions_immutable`; адаптер сопоставляет с `outbound.ErrPolicyVersionImmutable` именно эту пару, а не текст сообщения. В порту нет методов изменения и удаления, поэтому изменение - всегда новая версия. Гарантия покрывает запросы приложения и ручной SQL; роль-владелец таблицы все еще может отключить триггер или удалить таблицу, поэтому runtime-роль с минимальными правами остается будущей работой. + +Типизированная политика `domain.ProductPolicy`: каждое значение - именованное поле, тип которого несет единицу измерения: `CalendarDays`, `BusinessDays` (без перевода в длительность; производственный календарь задает использующая функция), `Hours` и `BasisPoints` для вероятностей и стандартной ошибки - целое число долей 0.0001 (0.80 - это 8000). Базисные пункты сравниваются точно, без погрешности чисел с плавающей точкой, и оставляют в документе целые числа. Метод `Validate` каждого раздела отклоняет нулевые, отсутствующие и выходящие за диапазон значения и несогласованные сочетания, например срок по умолчанию вне списка вариантов, более высокий уровень квоты с меньшим лимитом, неактивный E0, активный уровень над неактивным или вероятности остановки, которые не охватывают порог подтверждения. Диапазоны - защита от ошибок в единицах, а не продуктовые решения. Уровни квот E0 < E1 < E2 доступны через `OrganizationQuotaPolicy.Tier(domain.OrganizationTier)` (для TASK-087); каждая организация начинает с E0, а правила перехода между уровнями относятся к функции квот. + +Открытый вопрос для задач попыток (TASK-157 и TASK-158): `MaxAttemptsPerWindow` хранит только число. Считается ли лимит по грейду, по специальности или по всем оцениваниям кандидата, не решено. + +У документа `schema_version` 1 и разделы `invitations`, `organization_quotas`, `assessment`, `identity` и `search_status`; имена полей несут единицу (`_days`, `_business_days`, `_hours`, `_bp`). Разбор строгий: отклоняются неизвестные поля, отсутствующие поля и null, неверные типы, дробные числа, значения вне int32, неизвестная версия схемы, данные после объекта и документы больше 64 KiB. Каноническая форма - компактная кодировка Go в порядке объявления полей. jsonb нормализует порядок ключей, поэтому `domain.RestorePolicyVersion` разбирает сохраненный документ, проверяет его, кодирует заново и сравнивает SHA-256 с `document_sha256`; при расхождении возвращается `domain.ErrPolicyDocumentIntegrity`. Golden-тест фиксирует каноническую форму, потому что ее изменение сломало бы проверку всех сохраненных версий; новой структуре нужны новая версия схемы и свой декодер. + +Порт `outbound.PolicyRepository` доступен через `UnitOfWork.Policies()` и вне транзакции через `postgres.PolicyStore`. Методы, принимающие семейство, отклоняют неизвестное до обращения к хранилищу. + +- `Create` сохраняет пронумерованный `domain.PolicyVersionDraft` и возвращает сохраненную `domain.PolicyVersion` со временем из базы данных. Вставка использует `ON CONFLICT DO NOTHING`, поэтому занятый номер или ID дает `ErrPolicyVersionConflict` и не прерывает окружающую транзакцию. +- `GetByID` читает одну версию. +- `GetEffective(key, at)` возвращает самую новую публикацию, то есть наибольший номер, среди версий, у которых `effective_at` не позже `at`. Поэтому версия, запланированная на будущее, никогда не отменяет версию, опубликованную после нее: срочное исправление остается в силе, когда наступает время более ранней запланированной версии, а запланированная версия оказывается замененной. Этот поиск обслуживает уникальный индекс `(policy_key, version)`. +- `GetLatest(key)` возвращает наибольший номер, действует версия или нет. +- `HasVersions(key)` сообщает о наличии версий, не читая документ. +- При отсутствии возвращается `ErrPolicyVersionNotFound`. + +`policy.Publisher` проверяет весь ввод до обращения к хранилищу. Часы приложения он использует только для отказа в запланированном времени, которое уже прошло; время публикации берется из базы данных. `Publish` назначает наибольший сохраненный номер плюс один; если параллельная публикация заняла номер, он перечитывает его и повторяет до 10 раз, после чего возвращает `policy.ErrPublishContended`. Он работает и с репозиторием вне транзакции, и внутри unit of work. + +Демонстрационная и калиброванная политика: `domain.DemoProductPolicyV1()` - принятая начальная политика для проверки продуктового сценария. Она публикуется как версия 1 семейства `product` с видом `demo` и автором `system:demo-seed`, а ее раздел оценивания помечен `uncalibrated_initial`. Эти значения не являются калиброванными утверждениями о качестве. Политика содержит только правила; содержание оценивания (банк заданий, blueprints и варианты) - отдельная задача. Демонстрационная версия 1: + +| Раздел | Значения | +| --- | --- | +| `invitations` | варианты срока ответа 3, 7 и 14 дней, по умолчанию 7; не более 20 ожидающих приглашений на одну потребность; повтор после отказа через 30 дней; предложение интервью в течение 5 рабочих дней; пауза 30 дней после контакта без сделки | +| `organization_quotas` | скользящие окна 7 дней для приглашений и 24 часа для просмотров разных карточек; E0 10 приглашений и 50 просмотров, E1 40 и 150, E2 100 и 400; E2 неактивен, пока нет верификации организаций, которая его дает | +| `assessment`, начальные некалиброванные значения | повтор того же грейда через 30 дней; не более 3 попыток за 180 дней; повышение не чаще одного раза в 90 дней; подтверждение при P_G >= 0.80, высокая уверенность от 0.90; после не менее 8 оцениваемых заданий остановка при P_G >= 0.90 или <= 0.10 или SE <= 0.25; не более 23 оцениваемых заданий плюс 2 seed-задания; практика обязательна | +| `identity` | токен подтверждения 24 часа; неподтвержденный аккаунт удаляется через 7 дней после последней регистрации; сессия без активности 24 часа, абсолютный срок 7 дней | +| `search_status` | статус "ищу работу" подтверждается каждые 30 дней | + +Сроки identity в этой таблице - значения контракта identity ([api/README.md](../../api/README.md#identity-сессии-cookie-и-csrf)). Они берутся из версионированной продуктовой политики, а не из конфигурации: usecase регистрации, подтверждения и сессий будут читать их из действующей версии политики. Правила грейда в разделе [Оценивание и подтверждение грейда](#оценивание-и-подтверждение-грейда) используют те же значения оценивания. + +Начальное заполнение: при старте, после миграций и при том же условии (`DATABASE_MIGRATE_ON_START` равен true и задан `DATABASE_URL`), bootstrap вызывает `Publisher.EnsureDemoProductPolicy`. Он проверяет только, есть ли у `product` хотя бы одна версия, и никогда не разбирает ее, поэтому сохраненная версия более новой или неизвестной структуры не может остановить запуск. Если семейство пусто, он публикует демонстрационную версию 1, действующую с момента публикации; иначе ничего не меняет и пишет в лог, что заполнение пропущено. Экземпляры, стартующие одновременно, состязаются за версию 1, и проигравший пропускает заполнение. Строка лога содержит только ключ, номер, вид и ID. Ошибка базы данных останавливает запуск. Заполнение не является вставкой данных в миграции, поэтому схема и значения политики меняются независимо. + +Ссылка на версию (запланировано): таблицы, которые фиксируют решение по политике, например решения о грейде, снимки подбора и приглашения, получают `policy_version_id uuid NOT NULL REFERENCES policy_versions (id)` и хранят версию, использованную в момент решения. Существующее решение читает эту версию через `GetByID` и никогда не пересчитывается через `GetEffective`, ответ которого для заданного момента меняется, когда запланированную версию заменяет более новая. Удалить версию, на которую есть ссылка, нельзя ни через внешний ключ, ни через триггер, и новая версия не переписывает прошлые решения. + +Тестовые фикстуры используют собственные значения. Поскольку `product` - единственное семейство, интеграционные тесты дают каждому случаю отдельную базу данных, и ни одна фикстура не подменяет демонстрационную политику. + ## Структура репозитория и назначение пакетов ```text @@ -119,11 +170,12 @@ backend/ cmd/app/main.go вызывает bootstrap.Run и обрабатывает ошибку config/ общая конфигурация runtime internal/ - domain/ плоский пакет; DomainEvent, типы identity + domain/ плоский пакет; DomainEvent, типы identity, продуктовая политика usecase/health/ operational readiness usecase port/inbound/ inbound граница readiness usecase/identity/ проверка пароля до хеширования (Credentials) - port/outbound/ границы readiness, кеша, объектного хранилища, транзакции, outbox, identity, хеширования паролей и почты + usecase/policy/ публикация версий политики и начальное заполнение демонстрационной политики + port/outbound/ границы readiness, кеша, объектного хранилища, транзакции, outbox, identity, политики, хеширования паролей и почты adapter/primary/http/ api/ generated ogen handler middleware/ метрики запросов @@ -134,22 +186,22 @@ backend/ argon2id/ hasher паролей Argon2id с бюджетом памяти mail/disabled/ почтовый транспорт, который ничего не отправляет и сообщает о недоступности канала ml/api/ generated client из backend/codegen/ogen-ml.yml - postgres/ pool, migrator, transactor, запись outbox, репозитории identity, health check + postgres/ pool, migrator, transactor, запись outbox, репозитории identity и политики, health check postgres/sqlc/ generated SQL adapter redis/ адаптер кеша и проверка Redis seaweedfs/ S3-адаптер и проверка bucket prometheus/ ограниченные Go/process и request metrics bootstrap/ конфигурация, wiring, lifecycle, shutdown - db/ встроенные миграции и SQL-запросы; таблицы outbox и identity + db/ встроенные миграции и SQL-запросы; таблицы outbox, identity и политики codegen/ конфигурация ogen и sqlc pkg/ резерв для обоснованных общих технических helpers ``` -Доменные типы лежат непосредственно в `backend/internal/domain/`: `user.go`, `candidate.go` и другие файлы по мере определения моделей. Вложенных каталогов по сущностям или модулям здесь нет. Первый тип - `DomainEvent` в `domain_event.go`: проверенное событие, которое транзакция записывает в outbox. Типы хранения identity лежат в `email_address.go`, `secret_token.go`, `user.go`, `email_token.go` и `session.go`; нормализованный пароль - в `password.go`. +Доменные типы лежат непосредственно в `backend/internal/domain/`: `user.go`, `candidate.go` и другие файлы по мере определения моделей. Вложенных каталогов по сущностям или модулям здесь нет. Первый тип - `DomainEvent` в `domain_event.go`: проверенное событие, которое транзакция записывает в outbox. Типы хранения identity лежат в `email_address.go`, `secret_token.go`, `user.go`, `email_token.go` и `session.go`; нормализованный пароль - в `password.go`. Продуктовая политика и ее версии лежат в `policy.go`, `policy_document.go`, `policy_version.go` и `policy_demo.go`. `domain/`, продуктовые `usecase/`, адаптеры Resend, SMTP и FSP, а также worker зарезервированы; их бизнес-логика не реализована. `main.go` только запускает bootstrap и обрабатывает ошибку процесса. Для публичного generated transport выбран ogen v1.24.0, контракты используют OpenAPI 3.2.0. Проверяется только применяемое подмножество, не вся спецификация. -Это компактная карта, а не обещание, что все запланированные продуктовые пакеты уже существуют. Сейчас Go-код включает health usecase/adapters, generated API clients, bootstrap с миграциями при старте, PostgreSQL health query, транзакционную запись outbox, репозитории identity без использующих их usecase, порт `PasswordHasher` с адаптером Argon2id и проверку пароля, которую вызовет регистрация, Redis cache adapter, S3-адаптер SeaweedFS и порт `MailSender` с транспортом `disabled`. Поведение аккаунтов (регистрация, подтверждение, вход, сессии), резюме, оценивание, приглашения, worker jobs, файловые сценарии, отправка почты, транспорты Resend и SMTP и FSP adapters остаются планом. Не создавайте пустые каталоги будущих модулей. +Это компактная карта, а не обещание, что все запланированные продуктовые пакеты уже существуют. Сейчас Go-код включает health usecase/adapters, generated API clients, bootstrap с миграциями при старте, PostgreSQL health query, транзакционную запись outbox, репозитории identity без использующих их usecase, версионированное хранилище политики с публикацией и начальным заполнением демонстрационной политики при старте, порт `PasswordHasher` с адаптером Argon2id и проверку пароля, которую вызовет регистрация, Redis cache adapter, S3-адаптер SeaweedFS и порт `MailSender` с транспортом `disabled`. Поведение аккаунтов (регистрация, подтверждение, вход, сессии), резюме, оценивание, приглашения, worker jobs, файловые сценарии, отправка почты, транспорты Resend и SMTP и FSP adapters остаются планом. Не создавайте пустые каталоги будущих модулей. `backend/pkg/` зарезервирован для небольших технических пакетов с оправданной общей границей, а не для продуктовых usecase или domain types. Возможные пакеты на будущее: `emailtemplate`, `mailer` и тестовые helpers. S3-клиент остается в адаптере SeaweedFS. Поведение, специфичное для этого сервиса, остается внутри `internal/`. @@ -196,11 +248,11 @@ contact_grant относится к паре кандидат-компания - до первого успешного теста статус unverified, заявленный грейд не дает подтвержденную категорию; - неудача не снижает подтвержденный грейд; - после первой неудачи кандидат сам выбирает тест более низкого уровня; система не назначает его автоматически; -- изменение грейда после успешной квалификации ограничено, исходный ориентир - 90 дней; -- первое понижение после неудачи не блокируется этим интервалом; повтор на том же уровне может иметь отдельный cooldown, исходный ориентир - 24 часа; +- повышение после успешной квалификации возможно не чаще одного раза в 90 дней; +- первое понижение после неудачи не блокируется этим интервалом; повтор того же грейда возможен через 30 дней, и за любые 180 дней кандидат проходит не более 3 попыток; - уверенный результат может предложить тест выше; история изменений доступна. -Пороги и интервалы - проектные решения для пилота, не проверенная психометрическая модель. Ротация задач и лимиты попыток уменьшают пользу утечки, но не доказывают защиту от подсказок или LLM. Уровни сложности нужно измерить. +Эти интервалы - принятая начальная политика, сохраненная как демонстрационная версия 1 [продуктовой политики](#версии-продуктовой-политики); ее пороги не откалиброваны и не являются проверенной психометрической моделью. Ротация задач и лимиты попыток уменьшают пользу утечки, но не доказывают защиту от подсказок или LLM. Уровни сложности нужно измерить. ## Подбор и объяснение @@ -369,7 +421,7 @@ ML eval фиксирует размеченные поля резюме, оши - Контакты отсутствуют до grant в API, поиске, PDF, ошибках и ML объяснении; другая компания не получает их после принятия. - Кандидат не читает чужие приглашения, документы, jobs и попытки; компания не читает чужие потребности и подборки. -- Провал не понижает грейд; первый переход на уровень ниже разрешен; 90-дневное ограничение не обходится конкурентными запросами. +- Провал не понижает грейд; первый переход на уровень ниже разрешен; 90-дневное ограничение на повышение не обходится конкурентными запросами. - Повтор submit/accept не создает второй результат; конкурентные переходы статусов согласованы. - Отключенный ML оставляет основной ручной путь; worker восстанавливает истекший lease; старый ответ не перезаписывает новую версию. - Пустая история ФСП отличается от ошибки; отсутствие истории не исключает кандидата. diff --git a/docs/ru/DEPLOY.md b/docs/ru/DEPLOY.md index 561a701..d49b36e 100644 --- a/docs/ru/DEPLOY.md +++ b/docs/ru/DEPLOY.md @@ -13,7 +13,7 @@ Основной файл deploy/docker/docker-compose.yml запускает PostgreSQL, Redis, SeaweedFS, Kafka, Go backend и frontend контейнер. Frontend контейнер раздает статические файлы через Nginx и проксирует /api в backend. PostgreSQL, Redis, SeaweedFS, Kafka, backend и Nginx общаются по выделенной Compose сети. -До открытия listeners backend применяет встроенные в бинарник миграции базы данных; ошибка миграции останавливает контейнер. Compose не передает `DATABASE_MIGRATE_ON_START`, поэтому развернутый backend всегда мигрирует при старте, и роли PostgreSQL из `DATABASE_URL` нужны права DDL на схему приложения. Этот флаг - опция локальной разработки; отдельная роль миграций с минимальными правами - будущая работа. См. [DEVELOPMENT.md](DEVELOPMENT.md#миграции-базы-данных). +До открытия listeners backend применяет встроенные в бинарник миграции базы данных; ошибка миграции останавливает контейнер. Compose не передает `DATABASE_MIGRATE_ON_START`, поэтому развернутый backend всегда мигрирует при старте, и роли PostgreSQL из `DATABASE_URL` нужны права DDL на схему приложения. Этот флаг - опция локальной разработки; отдельная роль миграций с минимальными правами - будущая работа. Сразу после миграций и только когда они выполняются backend заполняет демонстрационную продуктовую политику: если у семейства политики `product` нет ни одной версии, он публикует версию 1 и пишет в лог `demo product policy published`, иначе пишет, что заполнение пропущено, и ничего не меняет. При `DATABASE_MIGRATE_ON_START=false` заполнение тоже пропускается. Ошибка базы данных при заполнении останавливает контейнер так же, как ошибка миграции. См. [DEVELOPMENT.md](DEVELOPMENT.md#миграции-базы-данных) и [ARCHITECTURE.md](ARCHITECTURE.md#версии-продуктовой-политики). Контекст сборки backend - каталог `backend/`, поэтому Docker применяет `backend/.dockerignore`. Локальные инструменты, кеши, файлы окружения и результаты сборки не отправляются в этот build context. diff --git a/docs/ru/DEVELOPMENT.md b/docs/ru/DEVELOPMENT.md index 9e1d8cd..4cbdbf5 100644 --- a/docs/ru/DEVELOPMENT.md +++ b/docs/ru/DEVELOPMENT.md @@ -48,7 +48,7 @@ Frontend зависимости выбираются из актуальных s Что есть сейчас: - Маршруты health и readiness. Nginx сам отвечает на `GET /healthz` и проксирует в Go только `/api/` (deploy/nginx/conf.d/app.conf). Go обслуживает `GET /healthz` (`ok`) и `GET /readyz` (`ready` или 503 `not_ready` после проверки PostgreSQL, Redis и SeaweedFS) на внутреннем порту 8080 вне OpenAPI контракта, а также `GET /api/v1/healthz` из api/core/routes/healthz.yml через ogen handler (backend/internal/adapter/primary/http). Метрики Go отдаются на порту 9090 (`METRICS_ADDR`), Prometheus читает `/metrics`. ML обслуживает `GET /healthz`, `GET /readyz` (всегда 503 `not_ready`, потому что модель не подключена) и `/metrics` (ml/src/lincodex_ml, api/ml/routes). deploy/scripts/smoke.sh проверяет `/healthz` Nginx, `/api/v1/healthz`, `/readyz` Go изнутри сети Compose, 404 для неизвестного API маршрута и то, что backend запустился с `EMAIL_PROVIDER=disabled`; ML он не запускает и писем не отправляет. -- Адаптеры: PostgreSQL через pgxpool и generated запрос `SELECT 1`, runner миграций goose, применяемый при старте, transactor с записью transactional outbox и репозитории identity на sqlc для аккаунтов, email-токенов и сессий; Redis через go-cachekit, SeaweedFS через S3 API. Hasher паролей Argon2id и проверка пароля `identity.Credentials` есть и покрыты тестами, но в bootstrap не подключены. Generated Go client для ML контракта есть, но в bootstrap не подключен. +- Адаптеры: PostgreSQL через pgxpool и generated запрос `SELECT 1`, runner миграций goose, применяемый при старте, transactor с записью transactional outbox, репозитории identity на sqlc для аккаунтов, email-токенов и сессий, а также версионированный репозиторий политики, который при старте заполняет демонстрационную политику; Redis через go-cachekit, SeaweedFS через S3 API. Hasher паролей Argon2id и проверка пароля `identity.Credentials` есть и покрыты тестами, но в bootstrap не подключены. Generated Go client для ML контракта есть, но в bootstrap не подключен. - Почта: outbound порт `MailSender`, транспорт `disabled` и выбор `EMAIL_PROVIDER` в bootstrap. В этой сборке работает только `disabled`; `resend` и `smtp` после проверки своих настроек останавливают запуск. Пока ничто не отправляет письма. См. [DEPLOY.md](DEPLOY.md#почта) и [ARCHITECTURE.md](ARCHITECTURE.md#почтовый-транспорт). - OpenAPI контракты api/core/ и api/ml/ с объединением схем, bundles, lint и генерацией для Go (ogen), TypeScript (Orval) и Python (datamodel-code-generator). В SPA есть каркас интерфейса с экранами-заготовками, generated API client и MSW handlers. - Compose проекты: core (`deploy/docker/docker-compose.yml`: PostgreSQL, Redis, SeaweedFS, Kafka, backend, frontend), ML (`docker-compose.ml.yml`) и monitoring (`docker-compose.monitoring.yml`). @@ -56,7 +56,7 @@ Frontend зависимости выбираются из актуальных s - CI jobs в .github/workflows/ci.yml: `api`, `backend`, `integration` (matrix из двух шардов), `frontend`, `ml`, `codegen`, `infrastructure`, `security`, `security-images`, `smoke` и обязательный итог `aggregate`. Шардирование описано в [TESTING.md](TESTING.md). - Observability: Prometheus, Loki, Alloy, Grafana с provisioned datasources и dashboards, exporters для PostgreSQL, Redis и node. React-приложение пока не отправляет телеметрию. -Еще не реализованы: регистрация и вход (их контракт объявлен; операции отвечают 501 или 401), согласия, профили, анкета и тестирование, кабинет компании, потребности и подбор, приглашения и контакты, транспорты Resend и SMTP и отправка почты, Go клиент Kafka, relay для outbox, уведомления, поддержка и бизнес-E2E suite. В backend/db/migrations/ есть таблица outbox и таблицы хранения identity (`users`, `email_tokens`, `sessions`), другой бизнес-схемы нет; регистрация, подтверждение и сессии поверх этого хранения появятся в следующих задачах, каталоги продуктовых usecase и адаптеров, кроме частей для хеширования паролей, содержат только заглушки, а `make -C deploy test-e2e` остается отложенной заглушкой и завершается ошибкой. Целевая архитектура описана в [ARCHITECTURE.md](ARCHITECTURE.md). +Еще не реализованы: регистрация и вход (их контракт объявлен; операции отвечают 501 или 401), согласия, профили, анкета и тестирование, кабинет компании, потребности и подбор, приглашения и контакты, транспорты Resend и SMTP и отправка почты, Go клиент Kafka, relay для outbox, уведомления, поддержка и бизнес-E2E suite. В backend/db/migrations/ есть таблица outbox, таблицы хранения identity (`users`, `email_tokens`, `sessions`) и таблица `policy_versions`, другой бизнес-схемы нет; ни одно продуктовое правило пока не читает политику; регистрация, подтверждение и сессии поверх этого хранения появятся в следующих задачах, каталоги продуктовых usecase и адаптеров, кроме частей для хеширования паролей и политики, содержат только заглушки, а `make -C deploy test-e2e` остается отложенной заглушкой и завершается ошибкой. Целевая архитектура описана в [ARCHITECTURE.md](ARCHITECTURE.md). ## Установка и цикл работы @@ -170,6 +170,14 @@ goose выполняет каждую миграцию в отдельной т Пароль попадает в backend только как `domain.Password`: `domain.NewPassword` для нового пароля (от 15 до 128 кодовых точек после NFKC) и `domain.ParseLoginPassword` при входе (от 1 до 128). Исходный ввод длиннее 512 байт или с некорректным UTF-8 отклоняется до нормализации, и все проверки длины выполняются до хеширования. Адаптер `argon2id` реализует `outbound.PasswordHasher` с m=65536 KiB, t=3, p=4, бюджетом памяти на `PASSWORD_HASH_CONCURRENCY` вычислений (от 1 до 4; без значения - меньшее из 2 и GOMAXPROCS), `ErrPasswordMismatch` для неверного пароля, `ErrPasswordHashCorrupt` для некорректного или выходящего за границы сохраненного хеша, результатом `needsRehash` для старых параметров и `VerifyDummy` для неизвестных аккаунтов. Сохраненный хеш, не прошедший разбор или границы, оборачивает и `ErrPasswordHashCorrupt`, и `domain.ErrInvalidPasswordHash`. Unit-тесты используют дешевые параметры; эталонный вектор на 64 MiB пропускается с `-short`; `go test -run '^$' -bench . ./internal/adapter/secondary/argon2id/` в `backend/` измеряет один хеш с production-параметрами. См. [ARCHITECTURE.md](ARCHITECTURE.md#хеширование-паролей). +### Хранилище продуктовой политики + +Миграция `00003_create_policy_versions.sql` создает `policy_versions`, триггер, который ставит `created_at` по часам базы данных, и триггеры, отклоняющие UPDATE, DELETE и TRUNCATE; запросы лежат в `backend/db/queries/policy.sql`. `outbound.PolicyRepository` доступен через `UnitOfWork.Policies()` и вне транзакции через `postgres.PolicyStore`; `policy.Publisher` публикует версию под следующим свободным номером и выполняет начальное заполнение демонстрационной политики. Чтобы изменить значение, опубликуйте новую версию; сохраненная версия никогда не редактируется. `product` - единственное семейство политики. + +При старте backend публикует `domain.DemoProductPolicyV1()` как версию 1 семейства `product`, если у этого семейства нет ни одной версии. Заполнение выполняется сразу после миграций при старте и только вместе с ними: нужно, чтобы `DATABASE_MIGRATE_ON_START` был равен true и был задан `DATABASE_URL`. Если миграции при старте отключены, политику никто не заполняет. Заполнение проверяет только наличие версий, никогда не меняет и не разбирает существующую версию и пишет в лог только ключ, номер, вид и ID. Демонстрационные значения - принятая начальная политика, а не калиброванные значения. + +Запись, которая зависит от значений политики, добавляет `policy_version_id uuid NOT NULL REFERENCES policy_versions (id)`, хранит использованную версию и читает ее обратно по ID; не пересчитывайте существующую запись через `GetEffective`. Тесты используют собственные значения и не подменяют демонстрационную политику. Поскольку `product` - единственное семейство, а таблица отклоняет TRUNCATE, интеграционные тесты дают каждому случаю отдельную базу данных. Новой структуре документа нужны новая `schema_version` и свой декодер; не меняйте golden-документ в `backend/internal/domain/policy_test.go`, чтобы принять измененную каноническую форму. См. [ARCHITECTURE.md](ARCHITECTURE.md#версии-продуктовой-политики). + ## Читаемость Go-кода - Повторяющиеся parsing, setup и cleanup выносятся в небольшие типизированные helpers рядом с потребителями. В `pkg/` код переносится при реальном использовании несколькими пакетами. Обертка, которая лишь переименовывает вызов, не нужна.